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"
21c43df518SAkira Hatanaka #include "llvm/ADT/Triple.h"
229fb823bbSChandler Carruth #include "llvm/IR/Constants.h"
23fda0cee7SDuncan P. N. Exon Smith #include "llvm/IR/DebugInfo.h"
24d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h"
25d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h"
26d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h"
279fb823bbSChandler Carruth #include "llvm/IR/Module.h"
28dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h"
29e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h"
30b6af2f36SBill Wendling #include "llvm/Support/Debug.h"
31b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h"
32cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h"
33981af002SWill Dietz #include <cctype>
3482d6ff6bSDavid Majnemer #include <tuple>
35361e513dSReid Spencer using namespace llvm;
36361e513dSReid Spencer 
37e17f3708SEli Bendersky 
38b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
39b1ed91f3SChris Lattner // TypeMap implementation.
40b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
41b1ed91f3SChris Lattner 
42b1ed91f3SChris Lattner namespace {
43b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper {
4418c89411SRafael Espindola   /// This is a mapping from a source type to a destination type to use.
45b1ed91f3SChris Lattner   DenseMap<Type*, Type*> MappedTypes;
46b1ed91f3SChris Lattner 
4718c89411SRafael Espindola   /// When checking to see if two subgraphs are isomorphic, we speculatively
4818c89411SRafael Espindola   /// add types to MappedTypes, but keep track of them here in case we need to
4918c89411SRafael Espindola   /// roll back.
50b1ed91f3SChris Lattner   SmallVector<Type*, 16> SpeculativeTypes;
51b1ed91f3SChris Lattner 
52a96f235cSRafael Espindola   SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes;
53a96f235cSRafael Espindola 
5418c89411SRafael Espindola   /// This is a list of non-opaque structs in the source module that are mapped
5518c89411SRafael Espindola   /// to an opaque struct in the destination module.
565e3bd972SChris Lattner   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
575e3bd972SChris Lattner 
5818c89411SRafael Espindola   /// This is the set of opaque types in the destination modules who are
5918c89411SRafael Espindola   /// getting a body from the source module.
605e3bd972SChris Lattner   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
61d48b7783SBill Wendling 
628c2cc416SBill Wendling public:
6331ad468dSRafael Espindola   TypeMapTy(Linker::IdentifiedStructTypeSet &DstStructTypesSet)
6431ad468dSRafael Espindola       : DstStructTypesSet(DstStructTypesSet) {}
65aa9918aaSRafael Espindola 
6631ad468dSRafael Espindola   Linker::IdentifiedStructTypeSet &DstStructTypesSet;
6718c89411SRafael Espindola   /// Indicate that the specified type in the destination module is conceptually
6818c89411SRafael Espindola   /// equivalent to the specified type in the source module.
69b1ed91f3SChris Lattner   void addTypeMapping(Type *DstTy, Type *SrcTy);
70b1ed91f3SChris Lattner 
71d2a13a2eSRafael Espindola   /// Produce a body for an opaque type in the dest module from a type
72d2a13a2eSRafael Espindola   /// definition in the source module.
73b1ed91f3SChris Lattner   void linkDefinedTypeBodies();
74b1ed91f3SChris Lattner 
7518c89411SRafael Espindola   /// Return the mapped type to use for the specified input type from the
76b1ed91f3SChris Lattner   /// source module.
77b1ed91f3SChris Lattner   Type *get(Type *SrcTy);
7831ad468dSRafael Espindola   Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
7931ad468dSRafael Espindola 
8031ad468dSRafael Espindola   void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
81b1ed91f3SChris Lattner 
82290e2cc5SRafael Espindola   FunctionType *get(FunctionType *T) {
83290e2cc5SRafael Espindola     return cast<FunctionType>(get((Type *)T));
84290e2cc5SRafael Espindola   }
85b1ed91f3SChris Lattner 
8618c89411SRafael Espindola   /// Dump out the type map for debugging purposes.
87b6af2f36SBill Wendling   void dump() const {
888f14471eSRafael Espindola     for (auto &Pair : MappedTypes) {
89b6af2f36SBill Wendling       dbgs() << "TypeMap: ";
908f14471eSRafael Espindola       Pair.first->print(dbgs());
91b6af2f36SBill Wendling       dbgs() << " => ";
928f14471eSRafael Espindola       Pair.second->print(dbgs());
93b6af2f36SBill Wendling       dbgs() << '\n';
94b6af2f36SBill Wendling     }
95b6af2f36SBill Wendling   }
96b6af2f36SBill Wendling 
97b1ed91f3SChris Lattner private:
98290e2cc5SRafael Espindola   Type *remapType(Type *SrcTy) override { return get(SrcTy); }
99b1ed91f3SChris Lattner 
100b1ed91f3SChris Lattner   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
101b1ed91f3SChris Lattner };
102f00654e3SAlexander Kornienko }
103b1ed91f3SChris Lattner 
104b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
1053d097410SRafael Espindola   assert(SpeculativeTypes.empty());
106a96f235cSRafael Espindola   assert(SpeculativeDstOpaqueTypes.empty());
1073d097410SRafael Espindola 
108b1ed91f3SChris Lattner   // Check to see if these types are recursively isomorphic and establish a
109b1ed91f3SChris Lattner   // mapping between them if so.
110c586eaa1SDuncan P. N. Exon Smith   if (!areTypesIsomorphic(DstTy, SrcTy)) {
111b1ed91f3SChris Lattner     // Oops, they aren't isomorphic.  Just discard this request by rolling out
112b1ed91f3SChris Lattner     // any speculative mappings we've established.
1133d097410SRafael Espindola     for (Type *Ty : SpeculativeTypes)
1143d097410SRafael Espindola       MappedTypes.erase(Ty);
115a96f235cSRafael Espindola 
116a96f235cSRafael Espindola     SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
117a96f235cSRafael Espindola                                    SpeculativeDstOpaqueTypes.size());
118a96f235cSRafael Espindola     for (StructType *Ty : SpeculativeDstOpaqueTypes)
119a96f235cSRafael Espindola       DstResolvedOpaqueTypes.erase(Ty);
12004a74af7SRafael Espindola   } else {
12104a74af7SRafael Espindola     for (Type *Ty : SpeculativeTypes)
12204a74af7SRafael Espindola       if (auto *STy = dyn_cast<StructType>(Ty))
12304a74af7SRafael Espindola         if (STy->hasName())
12404a74af7SRafael Espindola           STy->setName("");
125d48b7783SBill Wendling   }
126b1ed91f3SChris Lattner   SpeculativeTypes.clear();
127a96f235cSRafael Espindola   SpeculativeDstOpaqueTypes.clear();
128b1ed91f3SChris Lattner }
129b1ed91f3SChris Lattner 
13018c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic,
13118c89411SRafael Espindola /// false if they are not.
132b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
133b1ed91f3SChris Lattner   // Two types with differing kinds are clearly not isomorphic.
134290e2cc5SRafael Espindola   if (DstTy->getTypeID() != SrcTy->getTypeID())
135290e2cc5SRafael Espindola     return false;
136b1ed91f3SChris Lattner 
137b1ed91f3SChris Lattner   // If we have an entry in the MappedTypes table, then we have our answer.
138b1ed91f3SChris Lattner   Type *&Entry = MappedTypes[SrcTy];
139b1ed91f3SChris Lattner   if (Entry)
140b1ed91f3SChris Lattner     return Entry == DstTy;
141b1ed91f3SChris Lattner 
142b1ed91f3SChris Lattner   // Two identical types are clearly isomorphic.  Remember this
143b1ed91f3SChris Lattner   // non-speculatively.
144b1ed91f3SChris Lattner   if (DstTy == SrcTy) {
145b1ed91f3SChris Lattner     Entry = DstTy;
146361e513dSReid Spencer     return true;
147361e513dSReid Spencer   }
148361e513dSReid Spencer 
149b1ed91f3SChris Lattner   // Okay, we have two types with identical kinds that we haven't seen before.
150361e513dSReid Spencer 
151b1ed91f3SChris Lattner   // If this is an opaque struct type, special case it.
152b1ed91f3SChris Lattner   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
153b1ed91f3SChris Lattner     // Mapping an opaque type to any struct, just keep the dest struct.
154b1ed91f3SChris Lattner     if (SSTy->isOpaque()) {
155b1ed91f3SChris Lattner       Entry = DstTy;
156b1ed91f3SChris Lattner       SpeculativeTypes.push_back(SrcTy);
157b1ed91f3SChris Lattner       return true;
158361e513dSReid Spencer     }
159b1ed91f3SChris Lattner 
1605e3bd972SChris Lattner     // Mapping a non-opaque source type to an opaque dest.  If this is the first
1615e3bd972SChris Lattner     // type that we're mapping onto this destination type then we succeed.  Keep
162a96f235cSRafael Espindola     // the dest, but fill it in later. If this is the second (different) type
163a96f235cSRafael Espindola     // that we're trying to map onto the same opaque type then we fail.
164b1ed91f3SChris Lattner     if (cast<StructType>(DstTy)->isOpaque()) {
1655e3bd972SChris Lattner       // We can only map one source type onto the opaque destination type.
16670573dcdSDavid Blaikie       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
1675e3bd972SChris Lattner         return false;
1685e3bd972SChris Lattner       SrcDefinitionsToResolve.push_back(SSTy);
169a96f235cSRafael Espindola       SpeculativeTypes.push_back(SrcTy);
170a96f235cSRafael Espindola       SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
171b1ed91f3SChris Lattner       Entry = DstTy;
172b1ed91f3SChris Lattner       return true;
173b1ed91f3SChris Lattner     }
174b1ed91f3SChris Lattner   }
175b1ed91f3SChris Lattner 
176b1ed91f3SChris Lattner   // If the number of subtypes disagree between the two types, then we fail.
177b1ed91f3SChris Lattner   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
178b1ed91f3SChris Lattner     return false;
179b1ed91f3SChris Lattner 
180b1ed91f3SChris Lattner   // Fail if any of the extra properties (e.g. array size) of the type disagree.
181b1ed91f3SChris Lattner   if (isa<IntegerType>(DstTy))
182b1ed91f3SChris Lattner     return false;  // bitwidth disagrees.
183b1ed91f3SChris Lattner   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
184b1ed91f3SChris Lattner     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
185b1ed91f3SChris Lattner       return false;
186eaf9b762SChris Lattner 
187b1ed91f3SChris Lattner   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
188b1ed91f3SChris Lattner     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
189b1ed91f3SChris Lattner       return false;
190b1ed91f3SChris Lattner   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
191b1ed91f3SChris Lattner     StructType *SSTy = cast<StructType>(SrcTy);
19244f7ab45SChris Lattner     if (DSTy->isLiteral() != SSTy->isLiteral() ||
193b1ed91f3SChris Lattner         DSTy->isPacked() != SSTy->isPacked())
194b1ed91f3SChris Lattner       return false;
195b1ed91f3SChris Lattner   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
196b1ed91f3SChris Lattner     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
197b1ed91f3SChris Lattner       return false;
198b1ed91f3SChris Lattner   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
1995fad3e9aSJoey Gouly     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
200361e513dSReid Spencer       return false;
201361e513dSReid Spencer   }
202361e513dSReid Spencer 
203b1ed91f3SChris Lattner   // Otherwise, we speculate that these two types will line up and recursively
204b1ed91f3SChris Lattner   // check the subelements.
205b1ed91f3SChris Lattner   Entry = DstTy;
206b1ed91f3SChris Lattner   SpeculativeTypes.push_back(SrcTy);
207eee6f995SChris Lattner 
208290e2cc5SRafael Espindola   for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
209290e2cc5SRafael Espindola     if (!areTypesIsomorphic(DstTy->getContainedType(I),
210290e2cc5SRafael Espindola                             SrcTy->getContainedType(I)))
211b1ed91f3SChris Lattner       return false;
212eee6f995SChris Lattner 
213b1ed91f3SChris Lattner   // If everything seems to have lined up, then everything is great.
214eee6f995SChris Lattner   return true;
215eee6f995SChris Lattner }
216eee6f995SChris Lattner 
217b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() {
218b1ed91f3SChris Lattner   SmallVector<Type*, 16> Elements;
219c81c3f55SRafael Espindola   for (StructType *SrcSTy : SrcDefinitionsToResolve) {
220b1ed91f3SChris Lattner     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
221c81c3f55SRafael Espindola     assert(DstSTy->isOpaque());
222b1ed91f3SChris Lattner 
223b1ed91f3SChris Lattner     // Map the body of the source type over to a new body for the dest type.
224b1ed91f3SChris Lattner     Elements.resize(SrcSTy->getNumElements());
225290e2cc5SRafael Espindola     for (unsigned I = 0, E = Elements.size(); I != E; ++I)
226c81c3f55SRafael Espindola       Elements[I] = get(SrcSTy->getElementType(I));
227b1ed91f3SChris Lattner 
228b1ed91f3SChris Lattner     DstSTy->setBody(Elements, SrcSTy->isPacked());
229a5b9e1cfSRafael Espindola     DstStructTypesSet.switchToNonOpaque(DstSTy);
230b1ed91f3SChris Lattner   }
231c81c3f55SRafael Espindola   SrcDefinitionsToResolve.clear();
2325e3bd972SChris Lattner   DstResolvedOpaqueTypes.clear();
233eee6f995SChris Lattner }
234eee6f995SChris Lattner 
23531ad468dSRafael Espindola void TypeMapTy::finishType(StructType *DTy, StructType *STy,
23631ad468dSRafael Espindola                            ArrayRef<Type *> ETypes) {
23731ad468dSRafael Espindola   DTy->setBody(ETypes, STy->isPacked());
238a4e85e3dSRafael Espindola 
23931ad468dSRafael Espindola   // Steal STy's name.
24031ad468dSRafael Espindola   if (STy->hasName()) {
24131ad468dSRafael Espindola     SmallString<16> TmpName = STy->getName();
24231ad468dSRafael Espindola     STy->setName("");
24331ad468dSRafael Espindola     DTy->setName(TmpName);
24431ad468dSRafael Espindola   }
24531ad468dSRafael Espindola 
24631ad468dSRafael Espindola   DstStructTypesSet.addNonOpaque(DTy);
24731ad468dSRafael Espindola }
24831ad468dSRafael Espindola 
24931ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty) {
25031ad468dSRafael Espindola   SmallPtrSet<StructType *, 8> Visited;
25131ad468dSRafael Espindola   return get(Ty, Visited);
25231ad468dSRafael Espindola }
25331ad468dSRafael Espindola 
25431ad468dSRafael Espindola Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
255b1ed91f3SChris Lattner   // If we already have an entry for this type, return it.
256b1ed91f3SChris Lattner   Type **Entry = &MappedTypes[Ty];
257290e2cc5SRafael Espindola   if (*Entry)
258290e2cc5SRafael Espindola     return *Entry;
259b1ed91f3SChris Lattner 
26031ad468dSRafael Espindola   // These are types that LLVM itself will unique.
26131ad468dSRafael Espindola   bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
26231ad468dSRafael Espindola 
26331ad468dSRafael Espindola #ifndef NDEBUG
26431ad468dSRafael Espindola   if (!IsUniqued) {
26531ad468dSRafael Espindola     for (auto &Pair : MappedTypes) {
26631ad468dSRafael Espindola       assert(!(Pair.first != Ty && Pair.second == Ty) &&
26731ad468dSRafael Espindola              "mapping to a source type");
26831ad468dSRafael Espindola     }
26931ad468dSRafael Espindola   }
27031ad468dSRafael Espindola #endif
27131ad468dSRafael Espindola 
27231ad468dSRafael Espindola   if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
27331ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
27431ad468dSRafael Espindola     return *Entry = DTy;
27531ad468dSRafael Espindola   }
27631ad468dSRafael Espindola 
27731ad468dSRafael Espindola   // If this is not a recursive type, then just map all of the elements and
278b1ed91f3SChris Lattner   // then rebuild the type from inside out.
27931ad468dSRafael Espindola   SmallVector<Type *, 4> ElementTypes;
28031ad468dSRafael Espindola 
281b1ed91f3SChris Lattner   // If there are no element types to map, then the type is itself.  This is
282b1ed91f3SChris Lattner   // true for the anonymous {} struct, things like 'float', integers, etc.
28331ad468dSRafael Espindola   if (Ty->getNumContainedTypes() == 0 && IsUniqued)
284b1ed91f3SChris Lattner     return *Entry = Ty;
285b1ed91f3SChris Lattner 
286b1ed91f3SChris Lattner   // Remap all of the elements, keeping track of whether any of them change.
287b1ed91f3SChris Lattner   bool AnyChange = false;
288b1ed91f3SChris Lattner   ElementTypes.resize(Ty->getNumContainedTypes());
289290e2cc5SRafael Espindola   for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
29031ad468dSRafael Espindola     ElementTypes[I] = get(Ty->getContainedType(I), Visited);
291290e2cc5SRafael Espindola     AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
292eee6f995SChris Lattner   }
293b1ed91f3SChris Lattner 
294b1ed91f3SChris Lattner   // If we found our type while recursively processing stuff, just use it.
295b1ed91f3SChris Lattner   Entry = &MappedTypes[Ty];
29631ad468dSRafael Espindola   if (*Entry) {
29731ad468dSRafael Espindola     if (auto *DTy = dyn_cast<StructType>(*Entry)) {
29831ad468dSRafael Espindola       if (DTy->isOpaque()) {
29931ad468dSRafael Espindola         auto *STy = cast<StructType>(Ty);
30031ad468dSRafael Espindola         finishType(DTy, STy, ElementTypes);
30131ad468dSRafael Espindola       }
30231ad468dSRafael Espindola     }
303290e2cc5SRafael Espindola     return *Entry;
30431ad468dSRafael Espindola   }
305b1ed91f3SChris Lattner 
30631ad468dSRafael Espindola   // If all of the element types mapped directly over and the type is not
30731ad468dSRafael Espindola   // a nomed struct, then the type is usable as-is.
30831ad468dSRafael Espindola   if (!AnyChange && IsUniqued)
309b1ed91f3SChris Lattner     return *Entry = Ty;
310b1ed91f3SChris Lattner 
311b1ed91f3SChris Lattner   // Otherwise, rebuild a modified type.
312b1ed91f3SChris Lattner   switch (Ty->getTypeID()) {
313290e2cc5SRafael Espindola   default:
314290e2cc5SRafael Espindola     llvm_unreachable("unknown derived type to remap");
315b1ed91f3SChris Lattner   case Type::ArrayTyID:
316b1ed91f3SChris Lattner     return *Entry = ArrayType::get(ElementTypes[0],
317b1ed91f3SChris Lattner                                    cast<ArrayType>(Ty)->getNumElements());
318b1ed91f3SChris Lattner   case Type::VectorTyID:
319b1ed91f3SChris Lattner     return *Entry = VectorType::get(ElementTypes[0],
320b1ed91f3SChris Lattner                                     cast<VectorType>(Ty)->getNumElements());
321b1ed91f3SChris Lattner   case Type::PointerTyID:
32231ad468dSRafael Espindola     return *Entry = PointerType::get(ElementTypes[0],
32331ad468dSRafael Espindola                                      cast<PointerType>(Ty)->getAddressSpace());
324b1ed91f3SChris Lattner   case Type::FunctionTyID:
325b1ed91f3SChris Lattner     return *Entry = FunctionType::get(ElementTypes[0],
326717d7eddSFrits van Bommel                                       makeArrayRef(ElementTypes).slice(1),
327b1ed91f3SChris Lattner                                       cast<FunctionType>(Ty)->isVarArg());
32831ad468dSRafael Espindola   case Type::StructTyID: {
32931ad468dSRafael Espindola     auto *STy = cast<StructType>(Ty);
33031ad468dSRafael Espindola     bool IsPacked = STy->isPacked();
33131ad468dSRafael Espindola     if (IsUniqued)
33231ad468dSRafael Espindola       return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
333b1ed91f3SChris Lattner 
334b1ed91f3SChris Lattner     // If the type is opaque, we can just use it directly.
335aa9918aaSRafael Espindola     if (STy->isOpaque()) {
33631ad468dSRafael Espindola       DstStructTypesSet.addOpaque(STy);
33731ad468dSRafael Espindola       return *Entry = Ty;
338aa9918aaSRafael Espindola     }
339b1ed91f3SChris Lattner 
34031ad468dSRafael Espindola     if (StructType *OldT =
34131ad468dSRafael Espindola             DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
342c81c3f55SRafael Espindola       STy->setName("");
34331ad468dSRafael Espindola       return *Entry = OldT;
344c81c3f55SRafael Espindola     }
345c81c3f55SRafael Espindola 
34631ad468dSRafael Espindola     if (!AnyChange) {
34731ad468dSRafael Espindola       DstStructTypesSet.addNonOpaque(STy);
34831ad468dSRafael Espindola       return *Entry = Ty;
34931ad468dSRafael Espindola     }
35031ad468dSRafael Espindola 
35131ad468dSRafael Espindola     StructType *DTy = StructType::create(Ty->getContext());
35231ad468dSRafael Espindola     finishType(DTy, STy, ElementTypes);
35331ad468dSRafael Espindola     return *Entry = DTy;
35431ad468dSRafael Espindola   }
35531ad468dSRafael Espindola   }
356b1ed91f3SChris Lattner }
357b1ed91f3SChris Lattner 
358b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
359b1ed91f3SChris Lattner // ModuleLinker implementation.
360b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
361b1ed91f3SChris Lattner 
362b1ed91f3SChris Lattner namespace {
363f6f121e2SJames Molloy class ModuleLinker;
364f6f121e2SJames Molloy 
36518c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This
36618c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which
36718c89411SRafael Espindola /// few get used.
368437aafdaSDavid Blaikie class ValueMaterializerTy final : public ValueMaterializer {
369c7ed52f2STeresa Johnson   ModuleLinker *ModLinker;
370c84f608bSRafael Espindola 
371f6f121e2SJames Molloy public:
37219b52383SRafael Espindola   ValueMaterializerTy(ModuleLinker *ModLinker) : ModLinker(ModLinker) {}
373f6f121e2SJames Molloy 
37419b52383SRafael Espindola   Value *materializeDeclFor(Value *V) override;
37519b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
376f6f121e2SJames Molloy };
377f6f121e2SJames Molloy 
378d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo {
379d12b4a33SRafael Espindola   const Twine &Msg;
380d12b4a33SRafael Espindola 
381d12b4a33SRafael Espindola public:
382d12b4a33SRafael Espindola   LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg);
383d12b4a33SRafael Espindola   void print(DiagnosticPrinter &DP) const override;
384d12b4a33SRafael Espindola };
385d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
386d12b4a33SRafael Espindola                                        const Twine &Msg)
387d12b4a33SRafael Espindola     : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
388d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
389d12b4a33SRafael Espindola 
39018c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the
39118c89411SRafael Espindola /// entrypoint for this file.
392b1ed91f3SChris Lattner class ModuleLinker {
393b1ed91f3SChris Lattner   Module *DstM, *SrcM;
394b1ed91f3SChris Lattner 
395b1ed91f3SChris Lattner   TypeMapTy TypeMap;
396f6f121e2SJames Molloy   ValueMaterializerTy ValMaterializer;
397b1ed91f3SChris Lattner 
39818c89411SRafael Espindola   /// Mapping of values from what they used to be in Src, to what they are now
39918c89411SRafael Espindola   /// in DstM.  ValueToValueMapTy is a ValueMap, which involves some overhead
40018c89411SRafael Espindola   /// due to the use of Value handles which the Linker doesn't actually need,
40118c89411SRafael Espindola   /// but this allows us to reuse the ValueMapper code.
402b1ed91f3SChris Lattner   ValueToValueMapTy ValueMap;
403b1ed91f3SChris Lattner 
404b1ed91f3SChris Lattner   struct AppendingVarInfo {
405b1ed91f3SChris Lattner     GlobalVariable *NewGV;   // New aggregate global in dest module.
4063e8bc6a8SRafael Espindola     const Constant *DstInit; // Old initializer from dest module.
4073e8bc6a8SRafael Espindola     const Constant *SrcInit; // Old initializer from src module.
408b1ed91f3SChris Lattner   };
409b1ed91f3SChris Lattner 
410b1ed91f3SChris Lattner   std::vector<AppendingVarInfo> AppendingVars;
411b1ed91f3SChris Lattner 
412cbb91408STanya Lattner   // Set of items not to link in from source.
413*c98b20b0SRafael Espindola   SmallPtrSet<const GlobalValue *, 16> DoNotLinkFromSource;
414cbb91408STanya Lattner 
415d0b23befSRafael Espindola   DiagnosticHandlerFunction DiagnosticHandler;
4164160f5d3SRafael Espindola 
417e868123dSDuncan P. N. Exon Smith   /// For symbol clashes, prefer those from Src.
418020d4fb1SArtem Belevich   unsigned Flags;
419e868123dSDuncan P. N. Exon Smith 
420c7ed52f2STeresa Johnson   /// Function index passed into ModuleLinker for using in function
421c7ed52f2STeresa Johnson   /// importing/exporting handling.
4228220e8a8SMehdi Amini   const FunctionInfoIndex *ImportIndex;
423c7ed52f2STeresa Johnson 
424c7ed52f2STeresa Johnson   /// Function to import from source module, all other functions are
425c7ed52f2STeresa Johnson   /// imported as declarations instead of definitions.
426c7ed52f2STeresa Johnson   Function *ImportFunction;
427c7ed52f2STeresa Johnson 
428c7ed52f2STeresa Johnson   /// Set to true if the given FunctionInfoIndex contains any functions
429c7ed52f2STeresa Johnson   /// from this source module, in which case we must conservatively assume
430c7ed52f2STeresa Johnson   /// that any of its functions may be imported into another module
431c7ed52f2STeresa Johnson   /// as part of a different backend compilation process.
432c7ed52f2STeresa Johnson   bool HasExportedFunctions;
433c7ed52f2STeresa Johnson 
4341063293aSTeresa Johnson   /// Set to true when all global value body linking is complete (including
4351063293aSTeresa Johnson   /// lazy linking). Used to prevent metadata linking from creating new
4361063293aSTeresa Johnson   /// references.
4371063293aSTeresa Johnson   bool DoneLinkingBodies;
4381063293aSTeresa Johnson 
439b1ed91f3SChris Lattner public:
44031ad468dSRafael Espindola   ModuleLinker(Module *dstM, Linker::IdentifiedStructTypeSet &Set, Module *srcM,
441c7ed52f2STeresa Johnson                DiagnosticHandlerFunction DiagnosticHandler, unsigned Flags,
4428220e8a8SMehdi Amini                const FunctionInfoIndex *Index = nullptr,
443c7ed52f2STeresa Johnson                Function *FuncToImport = nullptr)
44419b52383SRafael Espindola       : DstM(dstM), SrcM(srcM), TypeMap(Set), ValMaterializer(this),
445c7ed52f2STeresa Johnson         DiagnosticHandler(DiagnosticHandler), Flags(Flags), ImportIndex(Index),
4461063293aSTeresa Johnson         ImportFunction(FuncToImport), HasExportedFunctions(false),
4471063293aSTeresa Johnson         DoneLinkingBodies(false) {
448c7ed52f2STeresa Johnson     assert((ImportIndex || !ImportFunction) &&
449c7ed52f2STeresa Johnson            "Expect a FunctionInfoIndex when importing");
450c7ed52f2STeresa Johnson     // If we have a FunctionInfoIndex but no function to import,
451c7ed52f2STeresa Johnson     // then this is the primary module being compiled in a ThinLTO
452c7ed52f2STeresa Johnson     // backend compilation, and we need to see if it has functions that
453c7ed52f2STeresa Johnson     // may be exported to another backend compilation.
454c7ed52f2STeresa Johnson     if (ImportIndex && !ImportFunction)
455c7ed52f2STeresa Johnson       HasExportedFunctions = ImportIndex->hasExportedFunctions(SrcM);
456c7ed52f2STeresa Johnson   }
457b1ed91f3SChris Lattner 
458b1ed91f3SChris Lattner   bool run();
45919b52383SRafael Espindola   Value *materializeDeclFor(Value *V);
46019b52383SRafael Espindola   void materializeInitFor(GlobalValue *New, GlobalValue *Old);
461b1ed91f3SChris Lattner 
46219b52383SRafael Espindola private:
463020d4fb1SArtem Belevich   bool shouldOverrideFromSrc() { return Flags & Linker::OverrideFromSrc; }
464020d4fb1SArtem Belevich   bool shouldLinkOnlyNeeded() { return Flags & Linker::LinkOnlyNeeded; }
465020d4fb1SArtem Belevich   bool shouldInternalizeLinkedSymbols() {
466020d4fb1SArtem Belevich     return Flags & Linker::InternalizeLinkedSymbols;
467020d4fb1SArtem Belevich   }
468020d4fb1SArtem Belevich 
469c7ed52f2STeresa Johnson   /// Handles cloning of a global values from the source module into
470c7ed52f2STeresa Johnson   /// the destination module, including setting the attributes and visibility.
471c7ed52f2STeresa Johnson   GlobalValue *copyGlobalValueProto(TypeMapTy &TypeMap, const GlobalValue *SGV,
472c7ed52f2STeresa Johnson                                     const GlobalValue *DGV = nullptr);
473c7ed52f2STeresa Johnson 
474c7ed52f2STeresa Johnson   /// Check if we should promote the given local value to global scope.
475c7ed52f2STeresa Johnson   bool doPromoteLocalToGlobal(const GlobalValue *SGV);
476c7ed52f2STeresa Johnson 
4771063293aSTeresa Johnson   /// Check if all global value body linking is complete.
4781063293aSTeresa Johnson   bool doneLinkingBodies() { return DoneLinkingBodies; }
4791063293aSTeresa Johnson 
480d12b4a33SRafael Espindola   bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest,
481d12b4a33SRafael Espindola                             const GlobalValue &Src);
482dbb0bd1aSRafael Espindola 
483d12b4a33SRafael Espindola   /// Helper method for setting a message and returning an error code.
484b1ed91f3SChris Lattner   bool emitError(const Twine &Message) {
4854160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message));
486b1ed91f3SChris Lattner     return true;
487b1ed91f3SChris Lattner   }
488b1ed91f3SChris Lattner 
489d12b4a33SRafael Espindola   void emitWarning(const Twine &Message) {
4904160f5d3SRafael Espindola     DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message));
491d12b4a33SRafael Espindola   }
492d12b4a33SRafael Espindola 
493dad0a645SDavid Majnemer   bool getComdatLeader(Module *M, StringRef ComdatName,
494dad0a645SDavid Majnemer                        const GlobalVariable *&GVar);
495dad0a645SDavid Majnemer   bool computeResultingSelectionKind(StringRef ComdatName,
496dad0a645SDavid Majnemer                                      Comdat::SelectionKind Src,
497dad0a645SDavid Majnemer                                      Comdat::SelectionKind Dst,
498dad0a645SDavid Majnemer                                      Comdat::SelectionKind &Result,
499dad0a645SDavid Majnemer                                      bool &LinkFromSrc);
500dad0a645SDavid Majnemer   std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>>
501dad0a645SDavid Majnemer       ComdatsChosen;
502dad0a645SDavid Majnemer   bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK,
503dad0a645SDavid Majnemer                        bool &LinkFromSrc);
5042d5fb8caSTeresa Johnson   // Keep track of the global value members of each comdat in source.
5052d5fb8caSTeresa Johnson   DenseMap<const Comdat *, std::vector<GlobalValue *>> ComdatMembers;
506dad0a645SDavid Majnemer 
50718c89411SRafael Espindola   /// Given a global in the source module, return the global in the
50818c89411SRafael Espindola   /// destination module that is being linked to, if any.
5093e8bc6a8SRafael Espindola   GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
510b1ed91f3SChris Lattner     // If the source has no name it can't link.  If it has local linkage,
511b1ed91f3SChris Lattner     // there is no name match-up going on.
512b098f0c1STeresa Johnson     if (!SrcGV->hasName() || GlobalValue::isLocalLinkage(getLinkage(SrcGV)))
5132617dcceSCraig Topper       return nullptr;
514b1ed91f3SChris Lattner 
515b1ed91f3SChris Lattner     // Otherwise see if we have a match in the destination module's symtab.
516b098f0c1STeresa Johnson     GlobalValue *DGV = DstM->getNamedValue(getName(SrcGV));
517c84f608bSRafael Espindola     if (!DGV)
518c84f608bSRafael Espindola       return nullptr;
519b1ed91f3SChris Lattner 
520b1ed91f3SChris Lattner     // If we found a global with the same name in the dest module, but it has
521b1ed91f3SChris Lattner     // internal linkage, we are really not doing any linkage here.
522b1ed91f3SChris Lattner     if (DGV->hasLocalLinkage())
5232617dcceSCraig Topper       return nullptr;
524b1ed91f3SChris Lattner 
525b1ed91f3SChris Lattner     // Otherwise, we do in fact link to the destination global.
526b1ed91f3SChris Lattner     return DGV;
527b1ed91f3SChris Lattner   }
528b1ed91f3SChris Lattner 
529b1ed91f3SChris Lattner   void computeTypeMapping();
530b1ed91f3SChris Lattner 
53109d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobalArray(StringRef Name);
53209d84addSDuncan P. N. Exon Smith   void upgradeMismatchedGlobals();
53309d84addSDuncan P. N. Exon Smith 
5343e8bc6a8SRafael Espindola   bool linkAppendingVarProto(GlobalVariable *DstGV,
5353e8bc6a8SRafael Espindola                              const GlobalVariable *SrcGV);
536778fcc77SRafael Espindola 
537778fcc77SRafael Espindola   bool linkGlobalValueProto(GlobalValue *GV);
53866f02413SBill Wendling   bool linkModuleFlagsMetadata();
539b1ed91f3SChris Lattner 
5409f30fac4SRafael Espindola   void linkAppendingVarInit(AppendingVarInfo &AVI);
541ef23711eSRafael Espindola 
542ef23711eSRafael Espindola   void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
543ef23711eSRafael Espindola   bool linkFunctionBody(Function &Dst, Function &Src);
544ef23711eSRafael Espindola   void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
545ef23711eSRafael Espindola   bool linkGlobalValueBody(GlobalValue &Src);
546ef23711eSRafael Espindola 
547c7ed52f2STeresa Johnson   /// Functions that take care of cloning a specific global value type
548c7ed52f2STeresa Johnson   /// into the destination module.
549c7ed52f2STeresa Johnson   GlobalVariable *copyGlobalVariableProto(TypeMapTy &TypeMap,
550c7ed52f2STeresa Johnson                                           const GlobalVariable *SGVar);
551c7ed52f2STeresa Johnson   Function *copyFunctionProto(TypeMapTy &TypeMap, const Function *SF);
552c7ed52f2STeresa Johnson   GlobalValue *copyGlobalAliasProto(TypeMapTy &TypeMap, const GlobalAlias *SGA);
553c7ed52f2STeresa Johnson 
554c7ed52f2STeresa Johnson   /// Helper methods to check if we are importing from or potentially
555c7ed52f2STeresa Johnson   /// exporting from the current source module.
556c7ed52f2STeresa Johnson   bool isPerformingImport() { return ImportFunction != nullptr; }
557c7ed52f2STeresa Johnson   bool isModuleExporting() { return HasExportedFunctions; }
558c7ed52f2STeresa Johnson 
559c7ed52f2STeresa Johnson   /// If we are importing from the source module, checks if we should
560c7ed52f2STeresa Johnson   /// import SGV as a definition, otherwise import as a declaration.
561c7ed52f2STeresa Johnson   bool doImportAsDefinition(const GlobalValue *SGV);
562c7ed52f2STeresa Johnson 
563c7ed52f2STeresa Johnson   /// Get the name for SGV that should be used in the linked destination
564c7ed52f2STeresa Johnson   /// module. Specifically, this handles the case where we need to rename
565c7ed52f2STeresa Johnson   /// a local that is being promoted to global scope.
566c7ed52f2STeresa Johnson   std::string getName(const GlobalValue *SGV);
567c7ed52f2STeresa Johnson 
568c7ed52f2STeresa Johnson   /// Get the new linkage for SGV that should be used in the linked destination
569c7ed52f2STeresa Johnson   /// module. Specifically, for ThinLTO importing or exporting it may need
570c7ed52f2STeresa Johnson   /// to be adjusted.
571c7ed52f2STeresa Johnson   GlobalValue::LinkageTypes getLinkage(const GlobalValue *SGV);
572c7ed52f2STeresa Johnson 
573c7ed52f2STeresa Johnson   /// Copies the necessary global value attributes and name from the source
574c7ed52f2STeresa Johnson   /// to the newly cloned global value.
575c7ed52f2STeresa Johnson   void copyGVAttributes(GlobalValue *NewGV, const GlobalValue *SrcGV);
576c7ed52f2STeresa Johnson 
577c7ed52f2STeresa Johnson   /// Updates the visibility for the new global cloned from the source
578c7ed52f2STeresa Johnson   /// and, if applicable, linked with an existing destination global.
579c7ed52f2STeresa Johnson   /// Handles visibility change required for promoted locals.
580c7ed52f2STeresa Johnson   void setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
581c7ed52f2STeresa Johnson                      const GlobalValue *DGV = nullptr);
582c7ed52f2STeresa Johnson 
583b1ed91f3SChris Lattner   void linkNamedMDNodes();
584eee6f995SChris Lattner };
585f00654e3SAlexander Kornienko }
586d48b7783SBill Wendling 
58718c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol
58818c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble
58918c89411SRafael Espindola /// to force this back.
590b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) {
591b1ed91f3SChris Lattner   // If the global doesn't force its name or if it already has the right name,
592b1ed91f3SChris Lattner   // there is nothing for us to do.
593c7ed52f2STeresa Johnson   // Note that any required local to global promotion should already be done,
594c7ed52f2STeresa Johnson   // so promoted locals will not skip this handling as their linkage is no
595c7ed52f2STeresa Johnson   // longer local.
596b1ed91f3SChris Lattner   if (GV->hasLocalLinkage() || GV->getName() == Name)
597b1ed91f3SChris Lattner     return;
598b1ed91f3SChris Lattner 
599b1ed91f3SChris Lattner   Module *M = GV->getParent();
600361e513dSReid Spencer 
601361e513dSReid Spencer   // If there is a conflict, rename the conflict.
602b1ed91f3SChris Lattner   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
6032a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
604361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
605b1ed91f3SChris Lattner     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
6062a8d2e0eSChris Lattner   } else {
6072a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
6083aaaa0b2SReid Spencer   }
6093aaaa0b2SReid Spencer }
6103aaaa0b2SReid Spencer 
61118c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue)
61218c89411SRafael Espindola /// from the SrcGV to the DestGV.
613c7ed52f2STeresa Johnson void ModuleLinker::copyGVAttributes(GlobalValue *NewGV,
614c7ed52f2STeresa Johnson                                     const GlobalValue *SrcGV) {
615c7ed52f2STeresa Johnson   auto *GA = dyn_cast<GlobalAlias>(SrcGV);
616c7ed52f2STeresa Johnson   // Check for the special case of converting an alias (definition) to a
617c7ed52f2STeresa Johnson   // non-alias (declaration). This can happen when we are importing and
618c7ed52f2STeresa Johnson   // encounter a weak_any alias (weak_any defs may not be imported, see
619c7ed52f2STeresa Johnson   // comments in ModuleLinker::getLinkage) or an alias whose base object is
620c7ed52f2STeresa Johnson   // being imported as a declaration. In that case copy the attributes from the
621c7ed52f2STeresa Johnson   // base object.
622c7ed52f2STeresa Johnson   if (GA && !dyn_cast<GlobalAlias>(NewGV)) {
6233cd8161cSTeresa Johnson     assert(isPerformingImport() && !doImportAsDefinition(GA));
624c7ed52f2STeresa Johnson     NewGV->copyAttributesFrom(GA->getBaseObject());
625c7ed52f2STeresa Johnson   } else
626c7ed52f2STeresa Johnson     NewGV->copyAttributesFrom(SrcGV);
627c7ed52f2STeresa Johnson   forceRenaming(NewGV, getName(SrcGV));
628361e513dSReid Spencer }
629361e513dSReid Spencer 
630c7ed52f2STeresa Johnson bool ModuleLinker::doImportAsDefinition(const GlobalValue *SGV) {
631c7ed52f2STeresa Johnson   if (!isPerformingImport())
632c7ed52f2STeresa Johnson     return false;
6333cd8161cSTeresa Johnson   auto *GA = dyn_cast<GlobalAlias>(SGV);
6343cd8161cSTeresa Johnson   if (GA) {
6353cd8161cSTeresa Johnson     if (GA->hasWeakAnyLinkage())
6363cd8161cSTeresa Johnson       return false;
63789345771SRafael Espindola     const GlobalObject *GO = GA->getBaseObject();
63889345771SRafael Espindola     if (!GO->hasLinkOnceODRLinkage())
63989345771SRafael Espindola       return false;
64089345771SRafael Espindola     return doImportAsDefinition(GO);
6413cd8161cSTeresa Johnson   }
642dfbebc37STeresa Johnson   // Always import GlobalVariable definitions, except for the special
643dfbebc37STeresa Johnson   // case of WeakAny which are imported as ExternalWeak declarations
644dfbebc37STeresa Johnson   // (see comments in ModuleLinker::getLinkage). The linkage changes
645c7ed52f2STeresa Johnson   // described in ModuleLinker::getLinkage ensure the correct behavior (e.g.
646c7ed52f2STeresa Johnson   // global variables with external linkage are transformed to
6473cd8161cSTeresa Johnson   // available_externally definitions, which are ultimately turned into
6483cd8161cSTeresa Johnson   // declarations after the EliminateAvailableExternally pass).
64966059c9fSCraig Topper   if (isa<GlobalVariable>(SGV) && !SGV->isDeclaration() &&
6503cd8161cSTeresa Johnson       !SGV->hasWeakAnyLinkage())
651c7ed52f2STeresa Johnson     return true;
652c7ed52f2STeresa Johnson   // Only import the function requested for importing.
653c7ed52f2STeresa Johnson   auto *SF = dyn_cast<Function>(SGV);
654c7ed52f2STeresa Johnson   if (SF && SF == ImportFunction)
655c7ed52f2STeresa Johnson     return true;
656c7ed52f2STeresa Johnson   // Otherwise no.
657c7ed52f2STeresa Johnson   return false;
658c7ed52f2STeresa Johnson }
659c7ed52f2STeresa Johnson 
660c7ed52f2STeresa Johnson bool ModuleLinker::doPromoteLocalToGlobal(const GlobalValue *SGV) {
661c7ed52f2STeresa Johnson   assert(SGV->hasLocalLinkage());
662c7ed52f2STeresa Johnson   // Both the imported references and the original local variable must
663c7ed52f2STeresa Johnson   // be promoted.
664c7ed52f2STeresa Johnson   if (!isPerformingImport() && !isModuleExporting())
665c7ed52f2STeresa Johnson     return false;
666c7ed52f2STeresa Johnson 
667c7ed52f2STeresa Johnson   // Local const variables never need to be promoted unless they are address
668c7ed52f2STeresa Johnson   // taken. The imported uses can simply use the clone created in this module.
669c7ed52f2STeresa Johnson   // For now we are conservative in determining which variables are not
670c7ed52f2STeresa Johnson   // address taken by checking the unnamed addr flag. To be more aggressive,
671c7ed52f2STeresa Johnson   // the address taken information must be checked earlier during parsing
672c7ed52f2STeresa Johnson   // of the module and recorded in the function index for use when importing
673c7ed52f2STeresa Johnson   // from that module.
674c7ed52f2STeresa Johnson   auto *GVar = dyn_cast<GlobalVariable>(SGV);
675c7ed52f2STeresa Johnson   if (GVar && GVar->isConstant() && GVar->hasUnnamedAddr())
676c7ed52f2STeresa Johnson     return false;
677c7ed52f2STeresa Johnson 
678c7ed52f2STeresa Johnson   // Eventually we only need to promote functions in the exporting module that
679c7ed52f2STeresa Johnson   // are referenced by a potentially exported function (i.e. one that is in the
680c7ed52f2STeresa Johnson   // function index).
681c7ed52f2STeresa Johnson   return true;
682c7ed52f2STeresa Johnson }
683c7ed52f2STeresa Johnson 
684c7ed52f2STeresa Johnson std::string ModuleLinker::getName(const GlobalValue *SGV) {
685c7ed52f2STeresa Johnson   // For locals that must be promoted to global scope, ensure that
686c7ed52f2STeresa Johnson   // the promoted name uniquely identifies the copy in the original module,
687c7ed52f2STeresa Johnson   // using the ID assigned during combined index creation. When importing,
688c7ed52f2STeresa Johnson   // we rename all locals (not just those that are promoted) in order to
689c7ed52f2STeresa Johnson   // avoid naming conflicts between locals imported from different modules.
690c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() &&
691c7ed52f2STeresa Johnson       (doPromoteLocalToGlobal(SGV) || isPerformingImport()))
692c7ed52f2STeresa Johnson     return FunctionInfoIndex::getGlobalNameForLocal(
693c7ed52f2STeresa Johnson         SGV->getName(),
694c7ed52f2STeresa Johnson         ImportIndex->getModuleId(SGV->getParent()->getModuleIdentifier()));
695c7ed52f2STeresa Johnson   return SGV->getName();
696c7ed52f2STeresa Johnson }
697c7ed52f2STeresa Johnson 
698c7ed52f2STeresa Johnson GlobalValue::LinkageTypes ModuleLinker::getLinkage(const GlobalValue *SGV) {
699c7ed52f2STeresa Johnson   // Any local variable that is referenced by an exported function needs
700c7ed52f2STeresa Johnson   // to be promoted to global scope. Since we don't currently know which
701c7ed52f2STeresa Johnson   // functions reference which local variables/functions, we must treat
702c7ed52f2STeresa Johnson   // all as potentially exported if this module is exporting anything.
703c7ed52f2STeresa Johnson   if (isModuleExporting()) {
704c7ed52f2STeresa Johnson     if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
705c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
706c7ed52f2STeresa Johnson     return SGV->getLinkage();
707c7ed52f2STeresa Johnson   }
708c7ed52f2STeresa Johnson 
709c7ed52f2STeresa Johnson   // Otherwise, if we aren't importing, no linkage change is needed.
710c7ed52f2STeresa Johnson   if (!isPerformingImport())
711c7ed52f2STeresa Johnson     return SGV->getLinkage();
712c7ed52f2STeresa Johnson 
713c7ed52f2STeresa Johnson   switch (SGV->getLinkage()) {
714c7ed52f2STeresa Johnson   case GlobalValue::ExternalLinkage:
715c7ed52f2STeresa Johnson     // External defnitions are converted to available_externally
716c7ed52f2STeresa Johnson     // definitions upon import, so that they are available for inlining
717c7ed52f2STeresa Johnson     // and/or optimization, but are turned into declarations later
718c7ed52f2STeresa Johnson     // during the EliminateAvailableExternally pass.
7193cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
720c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
721c7ed52f2STeresa Johnson     // An imported external declaration stays external.
722c7ed52f2STeresa Johnson     return SGV->getLinkage();
723c7ed52f2STeresa Johnson 
724c7ed52f2STeresa Johnson   case GlobalValue::AvailableExternallyLinkage:
725c7ed52f2STeresa Johnson     // An imported available_externally definition converts
726c7ed52f2STeresa Johnson     // to external if imported as a declaration.
727c7ed52f2STeresa Johnson     if (!doImportAsDefinition(SGV))
728c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
729c7ed52f2STeresa Johnson     // An imported available_externally declaration stays that way.
730c7ed52f2STeresa Johnson     return SGV->getLinkage();
731c7ed52f2STeresa Johnson 
732c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceAnyLinkage:
733c7ed52f2STeresa Johnson   case GlobalValue::LinkOnceODRLinkage:
734c7ed52f2STeresa Johnson     // These both stay the same when importing the definition.
735c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
736c7ed52f2STeresa Johnson     return SGV->getLinkage();
737c7ed52f2STeresa Johnson 
738c7ed52f2STeresa Johnson   case GlobalValue::WeakAnyLinkage:
739c7ed52f2STeresa Johnson     // Can't import weak_any definitions correctly, or we might change the
740c7ed52f2STeresa Johnson     // program semantics, since the linker will pick the first weak_any
741c7ed52f2STeresa Johnson     // definition and importing would change the order they are seen by the
742c7ed52f2STeresa Johnson     // linker. The module linking caller needs to enforce this.
743c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
744c7ed52f2STeresa Johnson     // If imported as a declaration, it becomes external_weak.
745c7ed52f2STeresa Johnson     return GlobalValue::ExternalWeakLinkage;
746c7ed52f2STeresa Johnson 
747c7ed52f2STeresa Johnson   case GlobalValue::WeakODRLinkage:
748c7ed52f2STeresa Johnson     // For weak_odr linkage, there is a guarantee that all copies will be
749c7ed52f2STeresa Johnson     // equivalent, so the issue described above for weak_any does not exist,
750c7ed52f2STeresa Johnson     // and the definition can be imported. It can be treated similarly
751c7ed52f2STeresa Johnson     // to an imported externally visible global value.
7523cd8161cSTeresa Johnson     if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
753c7ed52f2STeresa Johnson       return GlobalValue::AvailableExternallyLinkage;
754c7ed52f2STeresa Johnson     else
755c7ed52f2STeresa Johnson       return GlobalValue::ExternalLinkage;
756c7ed52f2STeresa Johnson 
757c7ed52f2STeresa Johnson   case GlobalValue::AppendingLinkage:
758c7ed52f2STeresa Johnson     // It would be incorrect to import an appending linkage variable,
759c7ed52f2STeresa Johnson     // since it would cause global constructors/destructors to be
760c7ed52f2STeresa Johnson     // executed multiple times. This should have already been handled
761c7ed52f2STeresa Johnson     // by linkGlobalValueProto.
762f3d2329dSDavide Italiano     llvm_unreachable("Cannot import appending linkage variable");
763c7ed52f2STeresa Johnson 
764c7ed52f2STeresa Johnson   case GlobalValue::InternalLinkage:
765c7ed52f2STeresa Johnson   case GlobalValue::PrivateLinkage:
766c7ed52f2STeresa Johnson     // If we are promoting the local to global scope, it is handled
767c7ed52f2STeresa Johnson     // similarly to a normal externally visible global.
768c7ed52f2STeresa Johnson     if (doPromoteLocalToGlobal(SGV)) {
7693cd8161cSTeresa Johnson       if (doImportAsDefinition(SGV) && !dyn_cast<GlobalAlias>(SGV))
770c7ed52f2STeresa Johnson         return GlobalValue::AvailableExternallyLinkage;
771c7ed52f2STeresa Johnson       else
772c7ed52f2STeresa Johnson         return GlobalValue::ExternalLinkage;
773c7ed52f2STeresa Johnson     }
774c7ed52f2STeresa Johnson     // A non-promoted imported local definition stays local.
775c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
776c7ed52f2STeresa Johnson     return SGV->getLinkage();
777c7ed52f2STeresa Johnson 
778c7ed52f2STeresa Johnson   case GlobalValue::ExternalWeakLinkage:
779c7ed52f2STeresa Johnson     // External weak doesn't apply to definitions, must be a declaration.
780c7ed52f2STeresa Johnson     assert(!doImportAsDefinition(SGV));
781c7ed52f2STeresa Johnson     // Linkage stays external_weak.
782c7ed52f2STeresa Johnson     return SGV->getLinkage();
783c7ed52f2STeresa Johnson 
784c7ed52f2STeresa Johnson   case GlobalValue::CommonLinkage:
785c7ed52f2STeresa Johnson     // Linkage stays common on definitions.
786c7ed52f2STeresa Johnson     // The ThinLTO pass will eventually force-import their definitions.
787c7ed52f2STeresa Johnson     return SGV->getLinkage();
788c7ed52f2STeresa Johnson   }
789c7ed52f2STeresa Johnson 
790c7ed52f2STeresa Johnson   llvm_unreachable("unknown linkage type");
791c7ed52f2STeresa Johnson }
792c7ed52f2STeresa Johnson 
793ef23711eSRafael Espindola /// Loop through the global variables in the src module and merge them into the
794ef23711eSRafael Espindola /// dest module.
795c7ed52f2STeresa Johnson GlobalVariable *
796c7ed52f2STeresa Johnson ModuleLinker::copyGlobalVariableProto(TypeMapTy &TypeMap,
797ef23711eSRafael Espindola                                       const GlobalVariable *SGVar) {
798ef23711eSRafael Espindola   // No linking to be performed or linking from the source: simply create an
799ef23711eSRafael Espindola   // identical version of the symbol over in the dest module... the
800ef23711eSRafael Espindola   // initializer will be filled in later by LinkGlobalInits.
801ef23711eSRafael Espindola   GlobalVariable *NewDGV = new GlobalVariable(
802c7ed52f2STeresa Johnson       *DstM, TypeMap.get(SGVar->getType()->getElementType()),
803c7ed52f2STeresa Johnson       SGVar->isConstant(), getLinkage(SGVar), /*init*/ nullptr, getName(SGVar),
804c7ed52f2STeresa Johnson       /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
805ef23711eSRafael Espindola       SGVar->getType()->getAddressSpace());
806f6f121e2SJames Molloy 
807ef23711eSRafael Espindola   return NewDGV;
8083931c28bSRafael Espindola }
8093931c28bSRafael Espindola 
810ef23711eSRafael Espindola /// Link the function in the source module into the destination module if
811ef23711eSRafael Espindola /// needed, setting up mapping information.
812c7ed52f2STeresa Johnson Function *ModuleLinker::copyFunctionProto(TypeMapTy &TypeMap,
813ef23711eSRafael Espindola                                           const Function *SF) {
814ef23711eSRafael Espindola   // If there is no linkage to be performed or we are linking from the source,
815ef23711eSRafael Espindola   // bring SF over.
816c7ed52f2STeresa Johnson   return Function::Create(TypeMap.get(SF->getFunctionType()), getLinkage(SF),
817c7ed52f2STeresa Johnson                           getName(SF), DstM);
818ef23711eSRafael Espindola }
819ef23711eSRafael Espindola 
820ef23711eSRafael Espindola /// Set up prototypes for any aliases that come over from the source module.
821c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalAliasProto(TypeMapTy &TypeMap,
822ef23711eSRafael Espindola                                                 const GlobalAlias *SGA) {
823c7ed52f2STeresa Johnson   // If we are importing and encounter a weak_any alias, or an alias to
824c7ed52f2STeresa Johnson   // an object being imported as a declaration, we must import the alias
825c7ed52f2STeresa Johnson   // as a declaration as well, which involves converting it to a non-alias.
826c7ed52f2STeresa Johnson   // See comments in ModuleLinker::getLinkage for why we cannot import
827c7ed52f2STeresa Johnson   // weak_any defintions.
8283cd8161cSTeresa Johnson   if (isPerformingImport() && !doImportAsDefinition(SGA)) {
829c7ed52f2STeresa Johnson     // Need to convert to declaration. All aliases must be definitions.
830c7ed52f2STeresa Johnson     const GlobalValue *GVal = SGA->getBaseObject();
831c7ed52f2STeresa Johnson     GlobalValue *NewGV;
832c7ed52f2STeresa Johnson     if (auto *GVar = dyn_cast<GlobalVariable>(GVal))
833c7ed52f2STeresa Johnson       NewGV = copyGlobalVariableProto(TypeMap, GVar);
834c7ed52f2STeresa Johnson     else {
835c7ed52f2STeresa Johnson       auto *F = dyn_cast<Function>(GVal);
836c7ed52f2STeresa Johnson       assert(F);
837c7ed52f2STeresa Johnson       NewGV = copyFunctionProto(TypeMap, F);
838c7ed52f2STeresa Johnson     }
839f1b0a6e3STeresa Johnson     // Set the linkage to External or ExternalWeak (see comments in
840f1b0a6e3STeresa Johnson     // ModuleLinker::getLinkage for why WeakAny is converted to ExternalWeak).
841c7ed52f2STeresa Johnson     if (SGA->hasWeakAnyLinkage())
842c7ed52f2STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
843f1b0a6e3STeresa Johnson     else
844f1b0a6e3STeresa Johnson       NewGV->setLinkage(GlobalValue::ExternalLinkage);
845c7ed52f2STeresa Johnson     return NewGV;
846c7ed52f2STeresa Johnson   }
847ef23711eSRafael Espindola   // If there is no linkage to be performed or we're linking from the source,
848ef23711eSRafael Espindola   // bring over SGA.
8496614d8d2SDavid Blaikie   auto *Ty = TypeMap.get(SGA->getValueType());
8506614d8d2SDavid Blaikie   return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
851c7ed52f2STeresa Johnson                              getLinkage(SGA), getName(SGA), DstM);
852ef23711eSRafael Espindola }
853ef23711eSRafael Espindola 
854eb5e0a77SRafael Espindola static GlobalValue::VisibilityTypes
855eb5e0a77SRafael Espindola getMinVisibility(GlobalValue::VisibilityTypes A,
856eb5e0a77SRafael Espindola                  GlobalValue::VisibilityTypes B) {
857eb5e0a77SRafael Espindola   if (A == GlobalValue::HiddenVisibility || B == GlobalValue::HiddenVisibility)
858eb5e0a77SRafael Espindola     return GlobalValue::HiddenVisibility;
859eb5e0a77SRafael Espindola   if (A == GlobalValue::ProtectedVisibility ||
860eb5e0a77SRafael Espindola       B == GlobalValue::ProtectedVisibility)
861eb5e0a77SRafael Espindola     return GlobalValue::ProtectedVisibility;
862eb5e0a77SRafael Espindola   return GlobalValue::DefaultVisibility;
863eb5e0a77SRafael Espindola }
864eb5e0a77SRafael Espindola 
865c7ed52f2STeresa Johnson void ModuleLinker::setVisibility(GlobalValue *NewGV, const GlobalValue *SGV,
866c7ed52f2STeresa Johnson                                  const GlobalValue *DGV) {
867c7ed52f2STeresa Johnson   GlobalValue::VisibilityTypes Visibility = SGV->getVisibility();
868c7ed52f2STeresa Johnson   if (DGV)
869eb5e0a77SRafael Espindola     Visibility = getMinVisibility(DGV->getVisibility(), Visibility);
870c7ed52f2STeresa Johnson   // For promoted locals, mark them hidden so that they can later be
871c7ed52f2STeresa Johnson   // stripped from the symbol table to reduce bloat.
872c7ed52f2STeresa Johnson   if (SGV->hasLocalLinkage() && doPromoteLocalToGlobal(SGV))
873c7ed52f2STeresa Johnson     Visibility = GlobalValue::HiddenVisibility;
874c7ed52f2STeresa Johnson   NewGV->setVisibility(Visibility);
875c7ed52f2STeresa Johnson }
876c7ed52f2STeresa Johnson 
877c7ed52f2STeresa Johnson GlobalValue *ModuleLinker::copyGlobalValueProto(TypeMapTy &TypeMap,
878c7ed52f2STeresa Johnson                                                 const GlobalValue *SGV,
879c7ed52f2STeresa Johnson                                                 const GlobalValue *DGV) {
880ef23711eSRafael Espindola   GlobalValue *NewGV;
881ef23711eSRafael Espindola   if (auto *SGVar = dyn_cast<GlobalVariable>(SGV))
882c7ed52f2STeresa Johnson     NewGV = copyGlobalVariableProto(TypeMap, SGVar);
883ef23711eSRafael Espindola   else if (auto *SF = dyn_cast<Function>(SGV))
884c7ed52f2STeresa Johnson     NewGV = copyFunctionProto(TypeMap, SF);
885ef23711eSRafael Espindola   else
886c7ed52f2STeresa Johnson     NewGV = copyGlobalAliasProto(TypeMap, cast<GlobalAlias>(SGV));
887ef23711eSRafael Espindola   copyGVAttributes(NewGV, SGV);
888c7ed52f2STeresa Johnson   setVisibility(NewGV, SGV, DGV);
889ef23711eSRafael Espindola   return NewGV;
890ef23711eSRafael Espindola }
891ef23711eSRafael Espindola 
89219b52383SRafael Espindola Value *ValueMaterializerTy::materializeDeclFor(Value *V) {
89319b52383SRafael Espindola   return ModLinker->materializeDeclFor(V);
89419b52383SRafael Espindola }
89519b52383SRafael Espindola 
89619b52383SRafael Espindola Value *ModuleLinker::materializeDeclFor(Value *V) {
897ef23711eSRafael Espindola   auto *SGV = dyn_cast<GlobalValue>(V);
898ef23711eSRafael Espindola   if (!SGV)
899ef23711eSRafael Espindola     return nullptr;
900ef23711eSRafael Espindola 
9011063293aSTeresa Johnson   // If we are done linking global value bodies (i.e. we are performing
9021063293aSTeresa Johnson   // metadata linking), don't link in the global value due to this
9031063293aSTeresa Johnson   // reference, simply map it to null.
90419b52383SRafael Espindola   if (doneLinkingBodies())
9051063293aSTeresa Johnson     return nullptr;
9061063293aSTeresa Johnson 
90719b52383SRafael Espindola   GlobalValue *DGV = copyGlobalValueProto(TypeMap, SGV);
908ef23711eSRafael Espindola 
909ef23711eSRafael Espindola   if (Comdat *SC = SGV->getComdat()) {
910ef23711eSRafael Espindola     if (auto *DGO = dyn_cast<GlobalObject>(DGV)) {
911ef23711eSRafael Espindola       Comdat *DC = DstM->getOrInsertComdat(SC->getName());
912ef23711eSRafael Espindola       DGO->setComdat(DC);
913ef23711eSRafael Espindola     }
914ef23711eSRafael Espindola   }
915ef23711eSRafael Espindola 
916ef23711eSRafael Espindola   return DGV;
917f6f121e2SJames Molloy }
918f6f121e2SJames Molloy 
91919b52383SRafael Espindola void ValueMaterializerTy::materializeInitFor(GlobalValue *New,
92019b52383SRafael Espindola                                              GlobalValue *Old) {
92119b52383SRafael Espindola   return ModLinker->materializeInitFor(New, Old);
92219b52383SRafael Espindola }
92319b52383SRafael Espindola 
92419b52383SRafael Espindola void ModuleLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
92519b52383SRafael Espindola   if (isPerformingImport() && !doImportAsDefinition(Old))
92619b52383SRafael Espindola     return;
92719b52383SRafael Espindola 
92819b52383SRafael Espindola   // Skip declarations that ValueMaterializer may have created in
92919b52383SRafael Espindola   // case we link in only some of SrcM.
93019b52383SRafael Espindola   if (shouldLinkOnlyNeeded() && Old->isDeclaration())
93119b52383SRafael Espindola     return;
93219b52383SRafael Espindola 
93319b52383SRafael Espindola   assert(!Old->isDeclaration() && "users should not pass down decls");
93419b52383SRafael Espindola   linkGlobalValueBody(*Old);
93519b52383SRafael Espindola }
93619b52383SRafael Espindola 
937dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName,
938dad0a645SDavid Majnemer                                    const GlobalVariable *&GVar) {
939dad0a645SDavid Majnemer   const GlobalValue *GVal = M->getNamedValue(ComdatName);
940dad0a645SDavid Majnemer   if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) {
941dad0a645SDavid Majnemer     GVal = GA->getBaseObject();
942dad0a645SDavid Majnemer     if (!GVal)
943dad0a645SDavid Majnemer       // We cannot resolve the size of the aliasee yet.
944dad0a645SDavid Majnemer       return emitError("Linking COMDATs named '" + ComdatName +
945dad0a645SDavid Majnemer                        "': COMDAT key involves incomputable alias size.");
946dad0a645SDavid Majnemer   }
947dad0a645SDavid Majnemer 
948dad0a645SDavid Majnemer   GVar = dyn_cast_or_null<GlobalVariable>(GVal);
949dad0a645SDavid Majnemer   if (!GVar)
950dad0a645SDavid Majnemer     return emitError(
951dad0a645SDavid Majnemer         "Linking COMDATs named '" + ComdatName +
952dad0a645SDavid Majnemer         "': GlobalVariable required for data dependent selection!");
953dad0a645SDavid Majnemer 
954dad0a645SDavid Majnemer   return false;
955dad0a645SDavid Majnemer }
956dad0a645SDavid Majnemer 
957dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName,
958dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Src,
959dad0a645SDavid Majnemer                                                  Comdat::SelectionKind Dst,
960dad0a645SDavid Majnemer                                                  Comdat::SelectionKind &Result,
961dad0a645SDavid Majnemer                                                  bool &LinkFromSrc) {
962dad0a645SDavid Majnemer   // The ability to mix Comdat::SelectionKind::Any with
963dad0a645SDavid Majnemer   // Comdat::SelectionKind::Largest is a behavior that comes from COFF.
964dad0a645SDavid Majnemer   bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any ||
965dad0a645SDavid Majnemer                          Dst == Comdat::SelectionKind::Largest;
966dad0a645SDavid Majnemer   bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any ||
967dad0a645SDavid Majnemer                          Src == Comdat::SelectionKind::Largest;
968dad0a645SDavid Majnemer   if (DstAnyOrLargest && SrcAnyOrLargest) {
969dad0a645SDavid Majnemer     if (Dst == Comdat::SelectionKind::Largest ||
970dad0a645SDavid Majnemer         Src == Comdat::SelectionKind::Largest)
971dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Largest;
972dad0a645SDavid Majnemer     else
973dad0a645SDavid Majnemer       Result = Comdat::SelectionKind::Any;
974dad0a645SDavid Majnemer   } else if (Src == Dst) {
975dad0a645SDavid Majnemer     Result = Dst;
976dad0a645SDavid Majnemer   } else {
977dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
978dad0a645SDavid Majnemer                      "': invalid selection kinds!");
979dad0a645SDavid Majnemer   }
980dad0a645SDavid Majnemer 
981dad0a645SDavid Majnemer   switch (Result) {
982dad0a645SDavid Majnemer   case Comdat::SelectionKind::Any:
983dad0a645SDavid Majnemer     // Go with Dst.
984dad0a645SDavid Majnemer     LinkFromSrc = false;
985dad0a645SDavid Majnemer     break;
986dad0a645SDavid Majnemer   case Comdat::SelectionKind::NoDuplicates:
987dad0a645SDavid Majnemer     return emitError("Linking COMDATs named '" + ComdatName +
988dad0a645SDavid Majnemer                      "': noduplicates has been violated!");
989dad0a645SDavid Majnemer   case Comdat::SelectionKind::ExactMatch:
990dad0a645SDavid Majnemer   case Comdat::SelectionKind::Largest:
991dad0a645SDavid Majnemer   case Comdat::SelectionKind::SameSize: {
992dad0a645SDavid Majnemer     const GlobalVariable *DstGV;
993dad0a645SDavid Majnemer     const GlobalVariable *SrcGV;
994dad0a645SDavid Majnemer     if (getComdatLeader(DstM, ComdatName, DstGV) ||
995dad0a645SDavid Majnemer         getComdatLeader(SrcM, ComdatName, SrcGV))
996dad0a645SDavid Majnemer       return true;
997dad0a645SDavid Majnemer 
99846a43556SMehdi Amini     const DataLayout &DstDL = DstM->getDataLayout();
99946a43556SMehdi Amini     const DataLayout &SrcDL = SrcM->getDataLayout();
1000dad0a645SDavid Majnemer     uint64_t DstSize =
100146a43556SMehdi Amini         DstDL.getTypeAllocSize(DstGV->getType()->getPointerElementType());
1002dad0a645SDavid Majnemer     uint64_t SrcSize =
100346a43556SMehdi Amini         SrcDL.getTypeAllocSize(SrcGV->getType()->getPointerElementType());
1004dad0a645SDavid Majnemer     if (Result == Comdat::SelectionKind::ExactMatch) {
1005dad0a645SDavid Majnemer       if (SrcGV->getInitializer() != DstGV->getInitializer())
1006dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1007dad0a645SDavid Majnemer                          "': ExactMatch violated!");
1008dad0a645SDavid Majnemer       LinkFromSrc = false;
1009dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::Largest) {
1010dad0a645SDavid Majnemer       LinkFromSrc = SrcSize > DstSize;
1011dad0a645SDavid Majnemer     } else if (Result == Comdat::SelectionKind::SameSize) {
1012dad0a645SDavid Majnemer       if (SrcSize != DstSize)
1013dad0a645SDavid Majnemer         return emitError("Linking COMDATs named '" + ComdatName +
1014dad0a645SDavid Majnemer                          "': SameSize violated!");
1015dad0a645SDavid Majnemer       LinkFromSrc = false;
1016dad0a645SDavid Majnemer     } else {
1017dad0a645SDavid Majnemer       llvm_unreachable("unknown selection kind");
1018dad0a645SDavid Majnemer     }
1019dad0a645SDavid Majnemer     break;
1020dad0a645SDavid Majnemer   }
1021dad0a645SDavid Majnemer   }
1022dad0a645SDavid Majnemer 
1023dad0a645SDavid Majnemer   return false;
1024dad0a645SDavid Majnemer }
1025dad0a645SDavid Majnemer 
1026dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC,
1027dad0a645SDavid Majnemer                                    Comdat::SelectionKind &Result,
1028dad0a645SDavid Majnemer                                    bool &LinkFromSrc) {
1029b16196a3SRafael Espindola   Comdat::SelectionKind SSK = SrcC->getSelectionKind();
1030dad0a645SDavid Majnemer   StringRef ComdatName = SrcC->getName();
1031dad0a645SDavid Majnemer   Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable();
1032dad0a645SDavid Majnemer   Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName);
10332ef3f299SRafael Espindola 
1034b16196a3SRafael Espindola   if (DstCI == ComdatSymTab.end()) {
1035b16196a3SRafael Espindola     // Use the comdat if it is only available in one of the modules.
1036b16196a3SRafael Espindola     LinkFromSrc = true;
1037b16196a3SRafael Espindola     Result = SSK;
10382ef3f299SRafael Espindola     return false;
1039b16196a3SRafael Espindola   }
10402ef3f299SRafael Espindola 
1041dad0a645SDavid Majnemer   const Comdat *DstC = &DstCI->second;
1042dad0a645SDavid Majnemer   Comdat::SelectionKind DSK = DstC->getSelectionKind();
10432ef3f299SRafael Espindola   return computeResultingSelectionKind(ComdatName, SSK, DSK, Result,
10442ef3f299SRafael Espindola                                        LinkFromSrc);
1045dad0a645SDavid Majnemer }
1046f6f121e2SJames Molloy 
1047d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc,
1048d12b4a33SRafael Espindola                                         const GlobalValue &Dest,
1049dbb0bd1aSRafael Espindola                                         const GlobalValue &Src) {
1050e868123dSDuncan P. N. Exon Smith   // Should we unconditionally use the Src?
1051020d4fb1SArtem Belevich   if (shouldOverrideFromSrc()) {
1052e868123dSDuncan P. N. Exon Smith     LinkFromSrc = true;
1053e868123dSDuncan P. N. Exon Smith     return false;
1054e868123dSDuncan P. N. Exon Smith   }
1055e868123dSDuncan P. N. Exon Smith 
1056778fcc77SRafael Espindola   // We always have to add Src if it has appending linkage.
1057778fcc77SRafael Espindola   if (Src.hasAppendingLinkage()) {
1058c7ed52f2STeresa Johnson     // Caller should have already determined that we can't link from source
1059c7ed52f2STeresa Johnson     // when importing (see comments in linkGlobalValueProto).
1060c7ed52f2STeresa Johnson     assert(!isPerformingImport());
1061778fcc77SRafael Espindola     LinkFromSrc = true;
1062778fcc77SRafael Espindola     return false;
1063778fcc77SRafael Espindola   }
1064778fcc77SRafael Espindola 
1065d4bcefc7SRafael Espindola   bool SrcIsDeclaration = Src.isDeclarationForLinker();
1066d4bcefc7SRafael Espindola   bool DestIsDeclaration = Dest.isDeclarationForLinker();
1067dbb0bd1aSRafael Espindola 
1068c7ed52f2STeresa Johnson   if (isPerformingImport()) {
1069c7ed52f2STeresa Johnson     if (isa<Function>(&Src)) {
1070c7ed52f2STeresa Johnson       // For functions, LinkFromSrc iff this is the function requested
1071c7ed52f2STeresa Johnson       // for importing. For variables, decide below normally.
1072c7ed52f2STeresa Johnson       LinkFromSrc = (&Src == ImportFunction);
1073c7ed52f2STeresa Johnson       return false;
1074c7ed52f2STeresa Johnson     }
1075c7ed52f2STeresa Johnson 
1076c7ed52f2STeresa Johnson     // Check if this is an alias with an already existing definition
1077c7ed52f2STeresa Johnson     // in Dest, which must have come from a prior importing pass from
1078c7ed52f2STeresa Johnson     // the same Src module. Unlike imported function and variable
1079c7ed52f2STeresa Johnson     // definitions, which are imported as available_externally and are
1080c7ed52f2STeresa Johnson     // not definitions for the linker, that is not a valid linkage for
1081c7ed52f2STeresa Johnson     // imported aliases which must be definitions. Simply use the existing
1082c7ed52f2STeresa Johnson     // Dest copy.
1083c7ed52f2STeresa Johnson     if (isa<GlobalAlias>(&Src) && !DestIsDeclaration) {
1084c7ed52f2STeresa Johnson       assert(isa<GlobalAlias>(&Dest));
1085c7ed52f2STeresa Johnson       LinkFromSrc = false;
1086c7ed52f2STeresa Johnson       return false;
1087c7ed52f2STeresa Johnson     }
1088c7ed52f2STeresa Johnson   }
1089c7ed52f2STeresa Johnson 
1090dbb0bd1aSRafael Espindola   if (SrcIsDeclaration) {
1091dbb0bd1aSRafael Espindola     // If Src is external or if both Src & Dest are external..  Just link the
1092dbb0bd1aSRafael Espindola     // external globals, we aren't adding anything.
1093d12b4a33SRafael Espindola     if (Src.hasDLLImportStorageClass()) {
1094dbb0bd1aSRafael Espindola       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
1095d12b4a33SRafael Espindola       LinkFromSrc = DestIsDeclaration;
1096d12b4a33SRafael Espindola       return false;
1097d12b4a33SRafael Espindola     }
1098dbb0bd1aSRafael Espindola     // If the Dest is weak, use the source linkage.
1099d12b4a33SRafael Espindola     LinkFromSrc = Dest.hasExternalWeakLinkage();
1100d12b4a33SRafael Espindola     return false;
1101dbb0bd1aSRafael Espindola   }
1102dbb0bd1aSRafael Espindola 
1103d12b4a33SRafael Espindola   if (DestIsDeclaration) {
1104dbb0bd1aSRafael Espindola     // If Dest is external but Src is not:
1105d12b4a33SRafael Espindola     LinkFromSrc = true;
1106d12b4a33SRafael Espindola     return false;
1107d12b4a33SRafael Espindola   }
1108dbb0bd1aSRafael Espindola 
11090910605aSRafael Espindola   if (Src.hasCommonLinkage()) {
1110d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) {
1111d12b4a33SRafael Espindola       LinkFromSrc = true;
11120910605aSRafael Espindola       return false;
1113d12b4a33SRafael Espindola     }
1114d12b4a33SRafael Espindola 
1115d12b4a33SRafael Espindola     if (!Dest.hasCommonLinkage()) {
1116d12b4a33SRafael Espindola       LinkFromSrc = false;
1117d12b4a33SRafael Espindola       return false;
1118d12b4a33SRafael Espindola     }
11190910605aSRafael Espindola 
1120a28d91d8SMehdi Amini     const DataLayout &DL = Dest.getParent()->getDataLayout();
11210910605aSRafael Espindola     uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType());
11220910605aSRafael Espindola     uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType());
1123d12b4a33SRafael Espindola     LinkFromSrc = SrcSize > DestSize;
1124d12b4a33SRafael Espindola     return false;
11250910605aSRafael Espindola   }
11260910605aSRafael Espindola 
1127dbb0bd1aSRafael Espindola   if (Src.isWeakForLinker()) {
1128dbb0bd1aSRafael Espindola     assert(!Dest.hasExternalWeakLinkage());
1129dbb0bd1aSRafael Espindola     assert(!Dest.hasAvailableExternallyLinkage());
11300910605aSRafael Espindola 
1131d12b4a33SRafael Espindola     if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) {
1132d12b4a33SRafael Espindola       LinkFromSrc = true;
1133d12b4a33SRafael Espindola       return false;
1134d12b4a33SRafael Espindola     }
1135dbb0bd1aSRafael Espindola 
1136d12b4a33SRafael Espindola     LinkFromSrc = false;
11370910605aSRafael Espindola     return false;
1138dbb0bd1aSRafael Espindola   }
1139dbb0bd1aSRafael Espindola 
1140dbb0bd1aSRafael Espindola   if (Dest.isWeakForLinker()) {
1141dbb0bd1aSRafael Espindola     assert(Src.hasExternalLinkage());
1142d12b4a33SRafael Espindola     LinkFromSrc = true;
1143d12b4a33SRafael Espindola     return false;
1144dbb0bd1aSRafael Espindola   }
1145dbb0bd1aSRafael Espindola 
1146dbb0bd1aSRafael Espindola   assert(!Src.hasExternalWeakLinkage());
1147dbb0bd1aSRafael Espindola   assert(!Dest.hasExternalWeakLinkage());
1148dbb0bd1aSRafael Espindola   assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() &&
1149dbb0bd1aSRafael Espindola          "Unexpected linkage type!");
1150dbb0bd1aSRafael Espindola   return emitError("Linking globals named '" + Src.getName() +
1151dbb0bd1aSRafael Espindola                    "': symbol multiply defined!");
1152dbb0bd1aSRafael Espindola }
1153dbb0bd1aSRafael Espindola 
115418c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings.  For example,
115518c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
115618c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same
115718c89411SRafael Espindola /// LLVMContext.
1158b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() {
1159c8a476eeSRafael Espindola   for (GlobalValue &SGV : SrcM->globals()) {
1160c8a476eeSRafael Espindola     GlobalValue *DGV = getLinkedToGlobal(&SGV);
1161c8a476eeSRafael Espindola     if (!DGV)
1162c8a476eeSRafael Espindola       continue;
1163b1ed91f3SChris Lattner 
1164c8a476eeSRafael Espindola     if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
1165c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1166b1ed91f3SChris Lattner       continue;
11675c310be0SDevang Patel     }
11685c310be0SDevang Patel 
1169b1ed91f3SChris Lattner     // Unify the element type of appending arrays.
1170b1ed91f3SChris Lattner     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
1171c8a476eeSRafael Espindola     ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
1172b1ed91f3SChris Lattner     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
1173b1ed91f3SChris Lattner   }
117434fc5a0eSChris Lattner 
1175c8a476eeSRafael Espindola   for (GlobalValue &SGV : *SrcM) {
1176c8a476eeSRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1177c8a476eeSRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1178b1ed91f3SChris Lattner   }
1179e79f4c77SAnton Korobeynikov 
1180e96d7eb8SRafael Espindola   for (GlobalValue &SGV : SrcM->aliases()) {
1181e96d7eb8SRafael Espindola     if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
1182e96d7eb8SRafael Espindola       TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
1183e96d7eb8SRafael Espindola   }
1184e96d7eb8SRafael Espindola 
1185d48b7783SBill Wendling   // Incorporate types by name, scanning all the types in the source module.
1186d48b7783SBill Wendling   // At this point, the destination module may have a type "%foo = { i32 }" for
11872b3f61afSBill Wendling   // example.  When the source module got loaded into the same LLVMContext, if
11882b3f61afSBill Wendling   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
11892fa1e43aSRafael Espindola   std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
11902fa1e43aSRafael Espindola   for (StructType *ST : Types) {
11914d4c9387SRafael Espindola     if (!ST->hasName())
11924d4c9387SRafael Espindola       continue;
11932b3f61afSBill Wendling 
11942b3f61afSBill Wendling     // Check to see if there is a dot in the name followed by a digit.
1195d48b7783SBill Wendling     size_t DotPos = ST->getName().rfind('.');
1196d48b7783SBill Wendling     if (DotPos == 0 || DotPos == StringRef::npos ||
119783c74e9fSGuy Benyei         ST->getName().back() == '.' ||
119883c74e9fSGuy Benyei         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
1199d48b7783SBill Wendling       continue;
12002b3f61afSBill Wendling 
12012b3f61afSBill Wendling     // Check to see if the destination module has a struct with the prefix name.
1202973b3612SRafael Espindola     StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos));
1203973b3612SRafael Espindola     if (!DST)
1204973b3612SRafael Espindola       continue;
1205973b3612SRafael Espindola 
12062b3f61afSBill Wendling     // Don't use it if this actually came from the source module. They're in
12078737480dSBill Wendling     // the same LLVMContext after all. Also don't use it unless the type is
12088737480dSBill Wendling     // actually used in the destination module. This can happen in situations
12098737480dSBill Wendling     // like this:
12108737480dSBill Wendling     //
12118737480dSBill Wendling     //      Module A                         Module B
12128737480dSBill Wendling     //      --------                         --------
12138737480dSBill Wendling     //   %Z = type { %A }                %B = type { %C.1 }
12148737480dSBill Wendling     //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
12158737480dSBill Wendling     //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
12168737480dSBill Wendling     //   %C = type { i8* }               %B.3 = type { %C.1 }
12178737480dSBill Wendling     //
12188737480dSBill Wendling     // When we link Module B with Module A, the '%B' in Module B is
12198737480dSBill Wendling     // used. However, that would then use '%C.1'. But when we process '%C.1',
12208737480dSBill Wendling     // we prefer to take the '%C' version. So we are then left with both
12218737480dSBill Wendling     // '%C.1' and '%C' being used for the same types. This leads to some
12228737480dSBill Wendling     // variables using one type and some using the other.
122331ad468dSRafael Espindola     if (TypeMap.DstStructTypesSet.hasType(DST))
12242b3f61afSBill Wendling       TypeMap.addTypeMapping(DST, ST);
12252b3f61afSBill Wendling   }
12262b3f61afSBill Wendling 
1227b1ed91f3SChris Lattner   // Now that we have discovered all of the type equivalences, get a body for
1228b1ed91f3SChris Lattner   // any 'opaque' types in the dest module that are now resolved.
1229b1ed91f3SChris Lattner   TypeMap.linkDefinedTypeBodies();
1230b1ed91f3SChris Lattner }
1231c08e7a00SChris Lattner 
123209d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) {
123309d84addSDuncan P. N. Exon Smith   ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType());
123409d84addSDuncan P. N. Exon Smith   StructType *OldTy = cast<StructType>(ATy->getElementType());
123509d84addSDuncan P. N. Exon Smith   assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements");
123609d84addSDuncan P. N. Exon Smith 
123709d84addSDuncan P. N. Exon Smith   // Get the upgraded 3 element type.
123809d84addSDuncan P. N. Exon Smith   PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo();
123909d84addSDuncan P. N. Exon Smith   Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1),
124009d84addSDuncan P. N. Exon Smith                   VoidPtrTy};
124109d84addSDuncan P. N. Exon Smith   StructType *NewTy = StructType::get(GV->getContext(), Tys, false);
124209d84addSDuncan P. N. Exon Smith 
124309d84addSDuncan P. N. Exon Smith   // Build new constants with a null third field filled in.
124409d84addSDuncan P. N. Exon Smith   Constant *OldInitC = GV->getInitializer();
124509d84addSDuncan P. N. Exon Smith   ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC);
124609d84addSDuncan P. N. Exon Smith   if (!OldInit && !isa<ConstantAggregateZero>(OldInitC))
124709d84addSDuncan P. N. Exon Smith     // Invalid initializer; give up.
124809d84addSDuncan P. N. Exon Smith     return;
124909d84addSDuncan P. N. Exon Smith   std::vector<Constant *> Initializers;
125009d84addSDuncan P. N. Exon Smith   if (OldInit && OldInit->getNumOperands()) {
125109d84addSDuncan P. N. Exon Smith     Value *Null = Constant::getNullValue(VoidPtrTy);
125209d84addSDuncan P. N. Exon Smith     for (Use &U : OldInit->operands()) {
125309d84addSDuncan P. N. Exon Smith       ConstantStruct *Init = cast<ConstantStruct>(U.get());
125409d84addSDuncan P. N. Exon Smith       Initializers.push_back(ConstantStruct::get(
125509d84addSDuncan P. N. Exon Smith           NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr));
125609d84addSDuncan P. N. Exon Smith     }
125709d84addSDuncan P. N. Exon Smith   }
125809d84addSDuncan P. N. Exon Smith   assert(Initializers.size() == ATy->getNumElements() &&
125909d84addSDuncan P. N. Exon Smith          "Failed to copy all array elements");
126009d84addSDuncan P. N. Exon Smith 
126109d84addSDuncan P. N. Exon Smith   // Replace the old GV with a new one.
126209d84addSDuncan P. N. Exon Smith   ATy = ArrayType::get(NewTy, Initializers.size());
126309d84addSDuncan P. N. Exon Smith   Constant *NewInit = ConstantArray::get(ATy, Initializers);
126409d84addSDuncan P. N. Exon Smith   GlobalVariable *NewGV = new GlobalVariable(
126509d84addSDuncan P. N. Exon Smith       *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "",
126609d84addSDuncan P. N. Exon Smith       GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(),
126709d84addSDuncan P. N. Exon Smith       GV->isExternallyInitialized());
126809d84addSDuncan P. N. Exon Smith   NewGV->copyAttributesFrom(GV);
126909d84addSDuncan P. N. Exon Smith   NewGV->takeName(GV);
127009d84addSDuncan P. N. Exon Smith   assert(GV->use_empty() && "program cannot use initializer list");
127109d84addSDuncan P. N. Exon Smith   GV->eraseFromParent();
127209d84addSDuncan P. N. Exon Smith }
127309d84addSDuncan P. N. Exon Smith 
127409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) {
127509d84addSDuncan P. N. Exon Smith   // Look for the global arrays.
127609d84addSDuncan P. N. Exon Smith   auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name));
127709d84addSDuncan P. N. Exon Smith   if (!DstGV)
127809d84addSDuncan P. N. Exon Smith     return;
127909d84addSDuncan P. N. Exon Smith   auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name));
128009d84addSDuncan P. N. Exon Smith   if (!SrcGV)
128109d84addSDuncan P. N. Exon Smith     return;
128209d84addSDuncan P. N. Exon Smith 
128309d84addSDuncan P. N. Exon Smith   // Check if the types already match.
128409d84addSDuncan P. N. Exon Smith   auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
128509d84addSDuncan P. N. Exon Smith   auto *SrcTy =
128609d84addSDuncan P. N. Exon Smith       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
128709d84addSDuncan P. N. Exon Smith   if (DstTy == SrcTy)
128809d84addSDuncan P. N. Exon Smith     return;
128909d84addSDuncan P. N. Exon Smith 
129009d84addSDuncan P. N. Exon Smith   // Grab the element types.  We can only upgrade an array of a two-field
129109d84addSDuncan P. N. Exon Smith   // struct.  Only bother if the other one has three-fields.
129209d84addSDuncan P. N. Exon Smith   auto *DstEltTy = cast<StructType>(DstTy->getElementType());
129309d84addSDuncan P. N. Exon Smith   auto *SrcEltTy = cast<StructType>(SrcTy->getElementType());
129409d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) {
129509d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(DstGV);
129609d84addSDuncan P. N. Exon Smith     return;
129709d84addSDuncan P. N. Exon Smith   }
129809d84addSDuncan P. N. Exon Smith   if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2)
129909d84addSDuncan P. N. Exon Smith     upgradeGlobalArray(SrcGV);
130009d84addSDuncan P. N. Exon Smith 
130109d84addSDuncan P. N. Exon Smith   // We can't upgrade any other differences.
130209d84addSDuncan P. N. Exon Smith }
130309d84addSDuncan P. N. Exon Smith 
130409d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() {
130509d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_ctors");
130609d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobalArray("llvm.global_dtors");
130709d84addSDuncan P. N. Exon Smith }
130809d84addSDuncan P. N. Exon Smith 
130918c89411SRafael Espindola /// If there were any appending global variables, link them together now.
131018c89411SRafael Espindola /// Return true on error.
1311b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
13123e8bc6a8SRafael Espindola                                          const GlobalVariable *SrcGV) {
1313b1ed91f3SChris Lattner   ArrayType *SrcTy =
1314b1ed91f3SChris Lattner       cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
1315c945c8d2SRafael Espindola   Type *EltTy = SrcTy->getElementType();
1316c945c8d2SRafael Espindola 
1317c945c8d2SRafael Espindola   uint64_t NewSize = SrcTy->getNumElements();
1318c945c8d2SRafael Espindola   if (DstGV) {
1319c945c8d2SRafael Espindola     ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
1320c945c8d2SRafael Espindola     NewSize += DstTy->getNumElements();
1321c945c8d2SRafael Espindola 
1322c945c8d2SRafael Espindola     if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
1323c945c8d2SRafael Espindola       return emitError(
1324c945c8d2SRafael Espindola           "Linking globals named '" + SrcGV->getName() +
1325c945c8d2SRafael Espindola           "': can only link appending global with another appending global!");
1326b1ed91f3SChris Lattner 
1327b1ed91f3SChris Lattner     // Check to see that they two arrays agree on type.
1328c945c8d2SRafael Espindola     if (EltTy != DstTy->getElementType())
1329b1ed91f3SChris Lattner       return emitError("Appending variables with different element types!");
1330b1ed91f3SChris Lattner     if (DstGV->isConstant() != SrcGV->isConstant())
1331b1ed91f3SChris Lattner       return emitError("Appending variables linked with different const'ness!");
1332b1ed91f3SChris Lattner 
1333b1ed91f3SChris Lattner     if (DstGV->getAlignment() != SrcGV->getAlignment())
1334b1ed91f3SChris Lattner       return emitError(
1335b1ed91f3SChris Lattner           "Appending variables with different alignment need to be linked!");
1336b1ed91f3SChris Lattner 
1337b1ed91f3SChris Lattner     if (DstGV->getVisibility() != SrcGV->getVisibility())
1338b1ed91f3SChris Lattner       return emitError(
1339b1ed91f3SChris Lattner           "Appending variables with different visibility need to be linked!");
1340b1ed91f3SChris Lattner 
1341fac3a018SRafael Espindola     if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
1342fac3a018SRafael Espindola       return emitError(
1343fac3a018SRafael Espindola           "Appending variables with different unnamed_addr need to be linked!");
1344fac3a018SRafael Espindola 
134564c1e180SRafael Espindola     if (StringRef(DstGV->getSection()) != SrcGV->getSection())
1346b1ed91f3SChris Lattner       return emitError(
1347b1ed91f3SChris Lattner           "Appending variables with different section name need to be linked!");
1348c945c8d2SRafael Espindola   }
1349b1ed91f3SChris Lattner 
1350b1ed91f3SChris Lattner   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
1351b1ed91f3SChris Lattner 
1352b1ed91f3SChris Lattner   // Create the new global variable.
1353c945c8d2SRafael Espindola   GlobalVariable *NG = new GlobalVariable(
1354c945c8d2SRafael Espindola       *DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
1355c945c8d2SRafael Espindola       /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
1356c945c8d2SRafael Espindola       SrcGV->getType()->getAddressSpace());
1357b1ed91f3SChris Lattner 
1358b1ed91f3SChris Lattner   // Propagate alignment, visibility and section info.
1359c945c8d2SRafael Espindola   copyGVAttributes(NG, SrcGV);
1360b1ed91f3SChris Lattner 
1361b1ed91f3SChris Lattner   AppendingVarInfo AVI;
1362b1ed91f3SChris Lattner   AVI.NewGV = NG;
1363c945c8d2SRafael Espindola   AVI.DstInit = DstGV ? DstGV->getInitializer() : nullptr;
1364b1ed91f3SChris Lattner   AVI.SrcInit = SrcGV->getInitializer();
1365b1ed91f3SChris Lattner   AppendingVars.push_back(AVI);
1366b1ed91f3SChris Lattner 
1367b1ed91f3SChris Lattner   // Replace any uses of the two global variables with uses of the new
1368b1ed91f3SChris Lattner   // global.
1369b1ed91f3SChris Lattner   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
1370b1ed91f3SChris Lattner 
1371c945c8d2SRafael Espindola   if (DstGV) {
1372b1ed91f3SChris Lattner     DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1373b1ed91f3SChris Lattner     DstGV->eraseFromParent();
1374c945c8d2SRafael Espindola   }
1375b1ed91f3SChris Lattner 
1376cbb91408STanya Lattner   // Track the source variable so we don't try to link it.
1377cbb91408STanya Lattner   DoNotLinkFromSource.insert(SrcGV);
1378cbb91408STanya Lattner 
1379b1ed91f3SChris Lattner   return false;
1380b1ed91f3SChris Lattner }
1381b1ed91f3SChris Lattner 
1382778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
1383b1ed91f3SChris Lattner   GlobalValue *DGV = getLinkedToGlobal(SGV);
1384b1ed91f3SChris Lattner 
1385778fcc77SRafael Espindola   // Handle the ultra special appending linkage case first.
1386c7ed52f2STeresa Johnson   assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1387c7ed52f2STeresa Johnson   if (SGV->hasAppendingLinkage() && isPerformingImport()) {
1388c7ed52f2STeresa Johnson     // Don't want to append to global_ctors list, for example, when we
1389c7ed52f2STeresa Johnson     // are importing for ThinLTO, otherwise the global ctors and dtors
1390c7ed52f2STeresa Johnson     // get executed multiple times for local variables (the latter causing
1391c7ed52f2STeresa Johnson     // double frees).
1392c7ed52f2STeresa Johnson     DoNotLinkFromSource.insert(SGV);
1393c7ed52f2STeresa Johnson     return false;
1394c7ed52f2STeresa Johnson   }
1395c945c8d2SRafael Espindola   if (SGV->hasAppendingLinkage())
1396c945c8d2SRafael Espindola     return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1397778fcc77SRafael Espindola                                  cast<GlobalVariable>(SGV));
1398778fcc77SRafael Espindola 
1399778fcc77SRafael Espindola   bool LinkFromSrc = true;
1400778fcc77SRafael Espindola   Comdat *C = nullptr;
1401778fcc77SRafael Espindola   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
1402778fcc77SRafael Espindola 
1403dad0a645SDavid Majnemer   if (const Comdat *SC = SGV->getComdat()) {
1404dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1405dad0a645SDavid Majnemer     std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
1406778fcc77SRafael Espindola     C = DstM->getOrInsertComdat(SC->getName());
1407778fcc77SRafael Espindola     C->setSelectionKind(SK);
14082d5fb8caSTeresa Johnson     ComdatMembers[SC].push_back(SGV);
1409778fcc77SRafael Espindola   } else if (DGV) {
1410778fcc77SRafael Espindola     if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
1411fc61de39SChris Lattner       return true;
1412dad0a645SDavid Majnemer   }
141334fc5a0eSChris Lattner 
1414dad0a645SDavid Majnemer   if (!LinkFromSrc) {
1415cbb91408STanya Lattner     // Track the source global so that we don't attempt to copy it over when
1416cbb91408STanya Lattner     // processing global initializers.
1417cbb91408STanya Lattner     DoNotLinkFromSource.insert(SGV);
1418cbb91408STanya Lattner 
1419778fcc77SRafael Espindola     if (DGV)
1420778fcc77SRafael Espindola       // Make sure to remember this mapping.
1421778fcc77SRafael Espindola       ValueMap[SGV] =
1422778fcc77SRafael Espindola           ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType()));
1423778fcc77SRafael Espindola   }
1424778fcc77SRafael Espindola 
1425c7ed52f2STeresa Johnson   if (DGV)
1426778fcc77SRafael Espindola     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
1427778fcc77SRafael Espindola 
1428778fcc77SRafael Espindola   if (!LinkFromSrc && !DGV)
1429dad0a645SDavid Majnemer     return false;
1430778fcc77SRafael Espindola 
1431778fcc77SRafael Espindola   GlobalValue *NewGV;
143226c29511SRafael Espindola   if (!LinkFromSrc) {
143326c29511SRafael Espindola     NewGV = DGV;
1434c7ed52f2STeresa Johnson     // When linking from source we setVisibility from copyGlobalValueProto.
1435c7ed52f2STeresa Johnson     setVisibility(NewGV, SGV, DGV);
143626c29511SRafael Espindola   } else {
1437ef23711eSRafael Espindola     // If the GV is to be lazily linked, don't create it just yet.
1438ef23711eSRafael Espindola     // The ValueMaterializerTy will deal with creating it if it's used.
1439c7ed52f2STeresa Johnson     if (!DGV && !shouldOverrideFromSrc() && SGV != ImportFunction &&
1440e868123dSDuncan P. N. Exon Smith         (SGV->hasLocalLinkage() || SGV->hasLinkOnceLinkage() ||
1441ef23711eSRafael Espindola          SGV->hasAvailableExternallyLinkage())) {
1442ef23711eSRafael Espindola       DoNotLinkFromSource.insert(SGV);
1443ef23711eSRafael Espindola       return false;
144426c29511SRafael Espindola     }
1445778fcc77SRafael Espindola 
1446020d4fb1SArtem Belevich     // When we only want to link in unresolved dependencies, blacklist
1447020d4fb1SArtem Belevich     // the symbol unless unless DestM has a matching declaration (DGV).
1448020d4fb1SArtem Belevich     if (shouldLinkOnlyNeeded() && !(DGV && DGV->isDeclaration())) {
1449020d4fb1SArtem Belevich       DoNotLinkFromSource.insert(SGV);
1450020d4fb1SArtem Belevich       return false;
1451020d4fb1SArtem Belevich     }
1452020d4fb1SArtem Belevich 
1453c7ed52f2STeresa Johnson     NewGV = copyGlobalValueProto(TypeMap, SGV, DGV);
14543cd8161cSTeresa Johnson 
14553cd8161cSTeresa Johnson     if (isPerformingImport() && !doImportAsDefinition(SGV))
14563cd8161cSTeresa Johnson       DoNotLinkFromSource.insert(SGV);
1457ef23711eSRafael Espindola   }
1458778fcc77SRafael Espindola 
1459778fcc77SRafael Espindola   NewGV->setUnnamedAddr(HasUnnamedAddr);
1460778fcc77SRafael Espindola 
1461778fcc77SRafael Espindola   if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
1462778fcc77SRafael Espindola     if (C)
1463778fcc77SRafael Espindola       NewGO->setComdat(C);
1464439835a6SRafael Espindola 
1465439835a6SRafael Espindola     if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
1466439835a6SRafael Espindola       NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
1467778fcc77SRafael Espindola   }
1468778fcc77SRafael Espindola 
1469879aeb77SRafael Espindola   if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
1470879aeb77SRafael Espindola     auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
1471879aeb77SRafael Espindola     auto *SGVar = dyn_cast<GlobalVariable>(SGV);
1472879aeb77SRafael Espindola     if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
1473879aeb77SRafael Espindola         (!DGVar->isConstant() || !SGVar->isConstant()))
1474879aeb77SRafael Espindola       NewGVar->setConstant(false);
1475879aeb77SRafael Espindola   }
1476879aeb77SRafael Espindola 
1477778fcc77SRafael Espindola   // Make sure to remember this mapping.
1478778fcc77SRafael Espindola   if (NewGV != DGV) {
1479778fcc77SRafael Espindola     if (DGV) {
1480ad9d0ca8SRafael Espindola       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1481778fcc77SRafael Espindola       DGV->eraseFromParent();
1482778fcc77SRafael Espindola     }
1483778fcc77SRafael Espindola     ValueMap[SGV] = NewGV;
1484dad0a645SDavid Majnemer   }
14854e27567aSRafael Espindola 
1486fd38af2dSChandler Carruth   return false;
14874e27567aSRafael Espindola }
14884e27567aSRafael Espindola 
14893e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C,
14903e8bc6a8SRafael Espindola                              SmallVectorImpl<Constant *> &Dest) {
14916705883aSChris Lattner   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
149200245f42SChris Lattner 
14936705883aSChris Lattner   for (unsigned i = 0; i != NumElements; ++i)
14946705883aSChris Lattner     Dest.push_back(C->getAggregateElement(i));
149500245f42SChris Lattner }
149600245f42SChris Lattner 
14979f30fac4SRafael Espindola void ModuleLinker::linkAppendingVarInit(AppendingVarInfo &AVI) {
1498b1ed91f3SChris Lattner   // Merge the initializer.
1499d31dc048SRafael Espindola   SmallVector<Constant *, 16> DstElements;
1500c945c8d2SRafael Espindola   if (AVI.DstInit)
1501d31dc048SRafael Espindola     getArrayElements(AVI.DstInit, DstElements);
1502b1ed91f3SChris Lattner 
1503d31dc048SRafael Espindola   SmallVector<Constant *, 16> SrcElements;
1504d31dc048SRafael Espindola   getArrayElements(AVI.SrcInit, SrcElements);
150500245f42SChris Lattner 
1506b1ed91f3SChris Lattner   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
1507d31dc048SRafael Espindola 
1508d31dc048SRafael Espindola   StringRef Name = AVI.NewGV->getName();
1509d31dc048SRafael Espindola   bool IsNewStructor =
1510d31dc048SRafael Espindola       (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") &&
1511d31dc048SRafael Espindola       cast<StructType>(NewType->getElementType())->getNumElements() == 3;
1512d31dc048SRafael Espindola 
1513d31dc048SRafael Espindola   for (auto *V : SrcElements) {
1514d31dc048SRafael Espindola     if (IsNewStructor) {
1515*c98b20b0SRafael Espindola       auto *Key =
1516*c98b20b0SRafael Espindola           dyn_cast<GlobalValue>(V->getAggregateElement(2)->stripPointerCasts());
1517d31dc048SRafael Espindola       if (DoNotLinkFromSource.count(Key))
1518d31dc048SRafael Espindola         continue;
1519d31dc048SRafael Espindola     }
1520d31dc048SRafael Espindola     DstElements.push_back(
15214fb46cb8SDuncan P. N. Exon Smith         MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1522d31dc048SRafael Espindola   }
15239f30fac4SRafael Espindola   if (DstElements.size() != NewType->getNumElements()) {
1524d31dc048SRafael Espindola     NewType = ArrayType::get(NewType->getElementType(), DstElements.size());
15259f30fac4SRafael Espindola     GlobalVariable *Old = AVI.NewGV;
15269f30fac4SRafael Espindola     GlobalVariable *NG = new GlobalVariable(
15279f30fac4SRafael Espindola         *DstM, NewType, Old->isConstant(), Old->getLinkage(), /*init*/ nullptr,
15289f30fac4SRafael Espindola         /*name*/ "", Old, Old->getThreadLocalMode(),
15299f30fac4SRafael Espindola         Old->getType()->getAddressSpace());
15309f30fac4SRafael Espindola     copyGVAttributes(NG, Old);
15319f30fac4SRafael Espindola     AVI.NewGV->replaceAllUsesWith(
15329f30fac4SRafael Espindola         ConstantExpr::getBitCast(NG, AVI.NewGV->getType()));
15339f30fac4SRafael Espindola     AVI.NewGV->eraseFromParent();
15349f30fac4SRafael Espindola     AVI.NewGV = NG;
1535d31dc048SRafael Espindola   }
1536d31dc048SRafael Espindola 
1537d31dc048SRafael Espindola   AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements));
1538b1ed91f3SChris Lattner }
1539b1ed91f3SChris Lattner 
154018c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be
154118c89411SRafael Espindola /// referenced are in Dest.
1542ef23711eSRafael Espindola void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1543b1ed91f3SChris Lattner   // Figure out what the initializer looks like in the dest module.
15444fb46cb8SDuncan P. N. Exon Smith   Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
15454fb46cb8SDuncan P. N. Exon Smith                               RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1546b1ed91f3SChris Lattner }
1547b1ed91f3SChris Lattner 
154818c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references
154918c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and
155018c89411SRafael Espindola /// that Src is not.
1551ef23711eSRafael Espindola bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
1552ef23711eSRafael Espindola   assert(Dst.isDeclaration() && !Src.isDeclaration());
1553361e513dSReid Spencer 
155440d7ebedSRafael Espindola   // Materialize if needed.
15553519da82SRafael Espindola   if (std::error_code EC = Src.materialize())
155640d7ebedSRafael Espindola     return emitError(EC.message());
155740d7ebedSRafael Espindola 
1558869d1ce8SRafael Espindola   // Link in the prefix data.
15593519da82SRafael Espindola   if (Src.hasPrefixData())
15604fb46cb8SDuncan P. N. Exon Smith     Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
15614fb46cb8SDuncan P. N. Exon Smith                                RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
1562869d1ce8SRafael Espindola 
1563869d1ce8SRafael Espindola   // Link in the prologue data.
15643519da82SRafael Espindola   if (Src.hasPrologueData())
15654fb46cb8SDuncan P. N. Exon Smith     Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
15664fb46cb8SDuncan P. N. Exon Smith                                  RF_MoveDistinctMDs, &TypeMap,
15674fb46cb8SDuncan P. N. Exon Smith                                  &ValMaterializer));
1568869d1ce8SRafael Espindola 
15697fddeccbSDavid Majnemer   // Link in the personality function.
15707fddeccbSDavid Majnemer   if (Src.hasPersonalityFn())
15714fb46cb8SDuncan P. N. Exon Smith     Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
15724fb46cb8SDuncan P. N. Exon Smith                                   RF_MoveDistinctMDs, &TypeMap,
15734fb46cb8SDuncan P. N. Exon Smith                                   &ValMaterializer));
15747fddeccbSDavid Majnemer 
15757391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
1576ef23711eSRafael Espindola   Function::arg_iterator DI = Dst.arg_begin();
15773519da82SRafael Espindola   for (Argument &Arg : Src.args()) {
1578a314d1acSRafael Espindola     DI->setName(Arg.getName());  // Copy the name over.
1579361e513dSReid Spencer 
1580b1ed91f3SChris Lattner     // Add a mapping to our mapping.
15819934b26bSDuncan P. N. Exon Smith     ValueMap[&Arg] = &*DI;
1582a314d1acSRafael Espindola     ++DI;
1583361e513dSReid Spencer   }
1584361e513dSReid Spencer 
1585c8d987b1SDuncan P. N. Exon Smith   // Copy over the metadata attachments.
1586c8d987b1SDuncan P. N. Exon Smith   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1587c8d987b1SDuncan P. N. Exon Smith   Src.getAllMetadata(MDs);
1588c8d987b1SDuncan P. N. Exon Smith   for (const auto &I : MDs)
15894fb46cb8SDuncan P. N. Exon Smith     Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
15904fb46cb8SDuncan P. N. Exon Smith                                          &TypeMap, &ValMaterializer));
1591c8d987b1SDuncan P. N. Exon Smith 
15922f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
1593ef23711eSRafael Espindola   Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1594361e513dSReid Spencer 
1595361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1596361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1597361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
159843f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1599ef23711eSRafael Espindola   for (BasicBlock &BB : Dst)
1600a314d1acSRafael Espindola     for (Instruction &I : BB)
16014fb46cb8SDuncan P. N. Exon Smith       RemapInstruction(&I, ValueMap,
16024fb46cb8SDuncan P. N. Exon Smith                        RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
16039f8eff31SRafael Espindola                        &ValMaterializer);
1604cbb91408STanya Lattner 
16057391dde1SChris Lattner   // There is no need to map the arguments anymore.
16063519da82SRafael Espindola   for (Argument &Arg : Src.args())
1607a314d1acSRafael Espindola     ValueMap.erase(&Arg);
1608cbb91408STanya Lattner 
160997cb5657SEric Christopher   Src.dematerialize();
161040d7ebedSRafael Espindola   return false;
1611361e513dSReid Spencer }
1612361e513dSReid Spencer 
1613ef23711eSRafael Espindola void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1614ef23711eSRafael Espindola   Constant *Aliasee = Src.getAliasee();
16154fb46cb8SDuncan P. N. Exon Smith   Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
16164fb46cb8SDuncan P. N. Exon Smith                            &ValMaterializer);
1617ef23711eSRafael Espindola   Dst.setAliasee(Val);
16182c4a34aeSDavid Chisnall }
1619ef23711eSRafael Espindola 
1620ef23711eSRafael Espindola bool ModuleLinker::linkGlobalValueBody(GlobalValue &Src) {
1621ef23711eSRafael Espindola   Value *Dst = ValueMap[&Src];
1622ef23711eSRafael Espindola   assert(Dst);
16232d5fb8caSTeresa Johnson   if (const Comdat *SC = Src.getComdat()) {
16242d5fb8caSTeresa Johnson     // To ensure that we don't generate an incomplete comdat group,
16252d5fb8caSTeresa Johnson     // we must materialize and map in any other members that are not
16262d5fb8caSTeresa Johnson     // yet materialized in Dst, which also ensures their definitions
16272d5fb8caSTeresa Johnson     // are linked in. Otherwise, linkonce and other lazy linked GVs will
16282d5fb8caSTeresa Johnson     // not be materialized if they aren't referenced.
16292d5fb8caSTeresa Johnson     for (auto *SGV : ComdatMembers[SC]) {
163019b52383SRafael Espindola       auto *DGV = cast_or_null<GlobalValue>(ValueMap[SGV]);
163119b52383SRafael Espindola       if (DGV && !DGV->isDeclaration())
16322d5fb8caSTeresa Johnson         continue;
163319b52383SRafael Espindola       MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
16342d5fb8caSTeresa Johnson     }
16352d5fb8caSTeresa Johnson   }
1636020d4fb1SArtem Belevich   if (shouldInternalizeLinkedSymbols())
1637020d4fb1SArtem Belevich     if (auto *DGV = dyn_cast<GlobalValue>(Dst))
1638020d4fb1SArtem Belevich       DGV->setLinkage(GlobalValue::InternalLinkage);
1639ef23711eSRafael Espindola   if (auto *F = dyn_cast<Function>(&Src))
1640ef23711eSRafael Espindola     return linkFunctionBody(cast<Function>(*Dst), *F);
1641ef23711eSRafael Espindola   if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1642ef23711eSRafael Espindola     linkGlobalInit(cast<GlobalVariable>(*Dst), *GVar);
1643ef23711eSRafael Espindola     return false;
1644b1ed91f3SChris Lattner   }
1645ef23711eSRafael Espindola   linkAliasBody(cast<GlobalAlias>(*Dst), cast<GlobalAlias>(Src));
1646ef23711eSRafael Espindola   return false;
1647cbb91408STanya Lattner }
1648b1ed91f3SChris Lattner 
164918c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module.
1650b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() {
165166f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
16523bf3f1f5SYaron Keren   for (const NamedMDNode &NMD : SrcM->named_metadata()) {
165366f02413SBill Wendling     // Don't link module flags here. Do them separately.
16543bf3f1f5SYaron Keren     if (&NMD == SrcModFlags)
16553bf3f1f5SYaron Keren       continue;
16563bf3f1f5SYaron Keren     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(NMD.getName());
1657b1ed91f3SChris Lattner     // Add Src elements into Dest node.
16583bf3f1f5SYaron Keren     for (const MDNode *op : NMD.operands())
165983d03ddbSTeresa Johnson       DestNMD->addOperand(MapMetadata(
166083d03ddbSTeresa Johnson           op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues,
16614fb46cb8SDuncan P. N. Exon Smith           &TypeMap, &ValMaterializer));
1662b1ed91f3SChris Lattner   }
1663b1ed91f3SChris Lattner }
1664b1ed91f3SChris Lattner 
166518c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module.
166666f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() {
16670ec72bbcSDaniel Dunbar   // If the source module has no module flags, we are done.
166866f02413SBill Wendling   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
166966f02413SBill Wendling   if (!SrcModFlags) return false;
167066f02413SBill Wendling 
167166f02413SBill Wendling   // If the destination module doesn't have module flags yet, then just copy
167266f02413SBill Wendling   // over the source module's flags.
16730ec72bbcSDaniel Dunbar   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
167466f02413SBill Wendling   if (DstModFlags->getNumOperands() == 0) {
167566f02413SBill Wendling     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
167666f02413SBill Wendling       DstModFlags->addOperand(SrcModFlags->getOperand(I));
167766f02413SBill Wendling 
167866f02413SBill Wendling     return false;
167966f02413SBill Wendling   }
168066f02413SBill Wendling 
16810ec72bbcSDaniel Dunbar   // First build a map of the existing module flags and requirements.
1682df55d8baSDuncan P. N. Exon Smith   DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
16830ec72bbcSDaniel Dunbar   SmallSetVector<MDNode*, 16> Requirements;
16840ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1685de36e804SDuncan P. N. Exon Smith     MDNode *Op = DstModFlags->getOperand(I);
16865bf8fef5SDuncan P. N. Exon Smith     ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
16870ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(Op->getOperand(1));
16880ec72bbcSDaniel Dunbar 
16890ec72bbcSDaniel Dunbar     if (Behavior->getZExtValue() == Module::Require) {
16900ec72bbcSDaniel Dunbar       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
16910ec72bbcSDaniel Dunbar     } else {
1692df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(Op, I);
16930ec72bbcSDaniel Dunbar     }
16940ec72bbcSDaniel Dunbar   }
16950ec72bbcSDaniel Dunbar 
16960ec72bbcSDaniel Dunbar   // Merge in the flags from the source module, and also collect its set of
16970ec72bbcSDaniel Dunbar   // requirements.
169866f02413SBill Wendling   bool HasErr = false;
16990ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1700de36e804SDuncan P. N. Exon Smith     MDNode *SrcOp = SrcModFlags->getOperand(I);
17015bf8fef5SDuncan P. N. Exon Smith     ConstantInt *SrcBehavior =
17025bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
17030ec72bbcSDaniel Dunbar     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1704df55d8baSDuncan P. N. Exon Smith     MDNode *DstOp;
1705df55d8baSDuncan P. N. Exon Smith     unsigned DstIndex;
1706df55d8baSDuncan P. N. Exon Smith     std::tie(DstOp, DstIndex) = Flags.lookup(ID);
17070ec72bbcSDaniel Dunbar     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
170866f02413SBill Wendling 
17090ec72bbcSDaniel Dunbar     // If this is a requirement, add it and continue.
17100ec72bbcSDaniel Dunbar     if (SrcBehaviorValue == Module::Require) {
17110ec72bbcSDaniel Dunbar       // If the destination module does not already have this requirement, add
17120ec72bbcSDaniel Dunbar       // it.
17130ec72bbcSDaniel Dunbar       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
17140ec72bbcSDaniel Dunbar         DstModFlags->addOperand(SrcOp);
17150ec72bbcSDaniel Dunbar       }
17160ec72bbcSDaniel Dunbar       continue;
17170ec72bbcSDaniel Dunbar     }
171866f02413SBill Wendling 
17190ec72bbcSDaniel Dunbar     // If there is no existing flag with this ID, just add it.
17200ec72bbcSDaniel Dunbar     if (!DstOp) {
1721df55d8baSDuncan P. N. Exon Smith       Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
17220ec72bbcSDaniel Dunbar       DstModFlags->addOperand(SrcOp);
17230ec72bbcSDaniel Dunbar       continue;
17240ec72bbcSDaniel Dunbar     }
172566f02413SBill Wendling 
17260ec72bbcSDaniel Dunbar     // Otherwise, perform a merge.
17275bf8fef5SDuncan P. N. Exon Smith     ConstantInt *DstBehavior =
17285bf8fef5SDuncan P. N. Exon Smith         mdconst::extract<ConstantInt>(DstOp->getOperand(0));
17290ec72bbcSDaniel Dunbar     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
17300ec72bbcSDaniel Dunbar 
17310ec72bbcSDaniel Dunbar     // If either flag has override behavior, handle it first.
17320ec72bbcSDaniel Dunbar     if (DstBehaviorValue == Module::Override) {
17330ec72bbcSDaniel Dunbar       // Diagnose inconsistent flags which both have override behavior.
17340ec72bbcSDaniel Dunbar       if (SrcBehaviorValue == Module::Override &&
17350ec72bbcSDaniel Dunbar           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
17360ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
17370ec72bbcSDaniel Dunbar                             "': IDs have conflicting override values");
17380ec72bbcSDaniel Dunbar       }
17390ec72bbcSDaniel Dunbar       continue;
17400ec72bbcSDaniel Dunbar     } else if (SrcBehaviorValue == Module::Override) {
17410ec72bbcSDaniel Dunbar       // Update the destination flag to that of the source.
1742df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, SrcOp);
1743df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = SrcOp;
17440ec72bbcSDaniel Dunbar       continue;
17450ec72bbcSDaniel Dunbar     }
17460ec72bbcSDaniel Dunbar 
17470ec72bbcSDaniel Dunbar     // Diagnose inconsistent merge behavior types.
17480ec72bbcSDaniel Dunbar     if (SrcBehaviorValue != DstBehaviorValue) {
17490ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + ID->getString() +
175066f02413SBill Wendling                           "': IDs have conflicting behaviors");
17510ec72bbcSDaniel Dunbar       continue;
175266f02413SBill Wendling     }
175366f02413SBill Wendling 
1754df55d8baSDuncan P. N. Exon Smith     auto replaceDstValue = [&](MDNode *New) {
1755df55d8baSDuncan P. N. Exon Smith       Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1756df55d8baSDuncan P. N. Exon Smith       MDNode *Flag = MDNode::get(DstM->getContext(), FlagOps);
1757df55d8baSDuncan P. N. Exon Smith       DstModFlags->setOperand(DstIndex, Flag);
1758df55d8baSDuncan P. N. Exon Smith       Flags[ID].first = Flag;
1759df55d8baSDuncan P. N. Exon Smith     };
1760df55d8baSDuncan P. N. Exon Smith 
17610ec72bbcSDaniel Dunbar     // Perform the merge for standard behavior types.
17620ec72bbcSDaniel Dunbar     switch (SrcBehaviorValue) {
17630ec72bbcSDaniel Dunbar     case Module::Require:
17642a30d788SCraig Topper     case Module::Override: llvm_unreachable("not possible");
17650ec72bbcSDaniel Dunbar     case Module::Error: {
17660ec72bbcSDaniel Dunbar       // Emit an error if the values differ.
17670ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
17680ec72bbcSDaniel Dunbar         HasErr |= emitError("linking module flags '" + ID->getString() +
17690ec72bbcSDaniel Dunbar                             "': IDs have conflicting values");
177066f02413SBill Wendling       }
17710ec72bbcSDaniel Dunbar       continue;
177266f02413SBill Wendling     }
17730ec72bbcSDaniel Dunbar     case Module::Warning: {
17740ec72bbcSDaniel Dunbar       // Emit a warning if the values differ.
17750ec72bbcSDaniel Dunbar       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1776d12b4a33SRafael Espindola         emitWarning("linking module flags '" + ID->getString() +
1777d12b4a33SRafael Espindola                     "': IDs have conflicting values");
1778e17f3708SEli Bendersky       }
17790ec72bbcSDaniel Dunbar       continue;
17800ec72bbcSDaniel Dunbar     }
1781d77d9fb0SDaniel Dunbar     case Module::Append: {
1782d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1783d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17845bf8fef5SDuncan P. N. Exon Smith       SmallVector<Metadata *, 8> MDs;
17855bf8fef5SDuncan P. N. Exon Smith       MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
17866cd780ffSBenjamin Kramer       MDs.append(DstValue->op_begin(), DstValue->op_end());
17876cd780ffSBenjamin Kramer       MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1788df55d8baSDuncan P. N. Exon Smith 
1789df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(), MDs));
1790d77d9fb0SDaniel Dunbar       break;
1791d77d9fb0SDaniel Dunbar     }
1792d77d9fb0SDaniel Dunbar     case Module::AppendUnique: {
17935bf8fef5SDuncan P. N. Exon Smith       SmallSetVector<Metadata *, 16> Elts;
1794d77d9fb0SDaniel Dunbar       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1795d77d9fb0SDaniel Dunbar       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
17966cd780ffSBenjamin Kramer       Elts.insert(DstValue->op_begin(), DstValue->op_end());
17976cd780ffSBenjamin Kramer       Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1798df55d8baSDuncan P. N. Exon Smith 
1799df55d8baSDuncan P. N. Exon Smith       replaceDstValue(MDNode::get(DstM->getContext(),
18005bf8fef5SDuncan P. N. Exon Smith                                   makeArrayRef(Elts.begin(), Elts.end())));
1801d77d9fb0SDaniel Dunbar       break;
1802d77d9fb0SDaniel Dunbar     }
180366f02413SBill Wendling     }
180466f02413SBill Wendling   }
180566f02413SBill Wendling 
18060ec72bbcSDaniel Dunbar   // Check all of the requirements.
18070ec72bbcSDaniel Dunbar   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
18080ec72bbcSDaniel Dunbar     MDNode *Requirement = Requirements[I];
18090ec72bbcSDaniel Dunbar     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
18105bf8fef5SDuncan P. N. Exon Smith     Metadata *ReqValue = Requirement->getOperand(1);
18110ec72bbcSDaniel Dunbar 
1812df55d8baSDuncan P. N. Exon Smith     MDNode *Op = Flags[Flag].first;
18130ec72bbcSDaniel Dunbar     if (!Op || Op->getOperand(2) != ReqValue) {
18140ec72bbcSDaniel Dunbar       HasErr |= emitError("linking module flags '" + Flag->getString() +
18159273b539SBill Wendling                           "': does not have the required value");
18160ec72bbcSDaniel Dunbar       continue;
181766f02413SBill Wendling     }
181866f02413SBill Wendling   }
181966f02413SBill Wendling 
182066f02413SBill Wendling   return HasErr;
182166f02413SBill Wendling }
182266f02413SBill Wendling 
1823c43df518SAkira Hatanaka // This function returns true if the triples match.
1824c43df518SAkira Hatanaka static bool triplesMatch(const Triple &T0, const Triple &T1) {
1825c43df518SAkira Hatanaka   // If vendor is apple, ignore the version number.
1826c43df518SAkira Hatanaka   if (T0.getVendor() == Triple::Apple)
1827c43df518SAkira Hatanaka     return T0.getArch() == T1.getArch() &&
1828c43df518SAkira Hatanaka            T0.getSubArch() == T1.getSubArch() &&
1829c43df518SAkira Hatanaka            T0.getVendor() == T1.getVendor() &&
1830c43df518SAkira Hatanaka            T0.getOS() == T1.getOS();
1831c43df518SAkira Hatanaka 
1832c43df518SAkira Hatanaka   return T0 == T1;
1833c43df518SAkira Hatanaka }
1834c43df518SAkira Hatanaka 
1835c43df518SAkira Hatanaka // This function returns the merged triple.
1836c43df518SAkira Hatanaka static std::string mergeTriples(const Triple &SrcTriple, const Triple &DstTriple) {
1837c43df518SAkira Hatanaka   // If vendor is apple, pick the triple with the larger version number.
1838c43df518SAkira Hatanaka   if (SrcTriple.getVendor() == Triple::Apple)
1839c43df518SAkira Hatanaka     if (DstTriple.isOSVersionLT(SrcTriple))
1840c43df518SAkira Hatanaka       return SrcTriple.str();
1841c43df518SAkira Hatanaka 
1842c43df518SAkira Hatanaka   return DstTriple.str();
1843c43df518SAkira Hatanaka }
1844c43df518SAkira Hatanaka 
1845b1ed91f3SChris Lattner bool ModuleLinker::run() {
184666f02413SBill Wendling   assert(DstM && "Null destination module");
184766f02413SBill Wendling   assert(SrcM && "Null source module");
1848b1ed91f3SChris Lattner 
1849b1ed91f3SChris Lattner   // Inherit the target data from the source module if the destination module
1850b1ed91f3SChris Lattner   // doesn't have one already.
185146a43556SMehdi Amini   if (DstM->getDataLayout().isDefault())
1852b1ed91f3SChris Lattner     DstM->setDataLayout(SrcM->getDataLayout());
1853b1ed91f3SChris Lattner 
185446a43556SMehdi Amini   if (SrcM->getDataLayout() != DstM->getDataLayout()) {
1855d12b4a33SRafael Espindola     emitWarning("Linking two modules of different data layouts: '" +
1856d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1857d12b4a33SRafael Espindola                 SrcM->getDataLayoutStr() + "' whereas '" +
1858d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1859d12b4a33SRafael Espindola                 DstM->getDataLayoutStr() + "'\n");
1860e17f3708SEli Bendersky   }
1861c43df518SAkira Hatanaka 
1862c43df518SAkira Hatanaka   // Copy the target triple from the source to dest if the dest's is empty.
1863c43df518SAkira Hatanaka   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1864c43df518SAkira Hatanaka     DstM->setTargetTriple(SrcM->getTargetTriple());
1865c43df518SAkira Hatanaka 
1866c43df518SAkira Hatanaka   Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM->getTargetTriple());
1867c43df518SAkira Hatanaka 
1868c43df518SAkira Hatanaka   if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
1869d12b4a33SRafael Espindola     emitWarning("Linking two modules of different target triples: " +
1870d12b4a33SRafael Espindola                 SrcM->getModuleIdentifier() + "' is '" +
1871d12b4a33SRafael Espindola                 SrcM->getTargetTriple() + "' whereas '" +
1872d12b4a33SRafael Espindola                 DstM->getModuleIdentifier() + "' is '" +
1873d12b4a33SRafael Espindola                 DstM->getTargetTriple() + "'\n");
1874c43df518SAkira Hatanaka 
1875c43df518SAkira Hatanaka   DstM->setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1876b1ed91f3SChris Lattner 
1877b1ed91f3SChris Lattner   // Append the module inline asm string.
1878b1ed91f3SChris Lattner   if (!SrcM->getModuleInlineAsm().empty()) {
1879b1ed91f3SChris Lattner     if (DstM->getModuleInlineAsm().empty())
1880b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1881b1ed91f3SChris Lattner     else
1882b1ed91f3SChris Lattner       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1883b1ed91f3SChris Lattner                                SrcM->getModuleInlineAsm());
1884b1ed91f3SChris Lattner   }
1885b1ed91f3SChris Lattner 
1886b1ed91f3SChris Lattner   // Loop over all of the linked values to compute type mappings.
1887b1ed91f3SChris Lattner   computeTypeMapping();
1888b1ed91f3SChris Lattner 
1889dad0a645SDavid Majnemer   ComdatsChosen.clear();
18905106ce78SDavid Blaikie   for (const auto &SMEC : SrcM->getComdatSymbolTable()) {
1891dad0a645SDavid Majnemer     const Comdat &C = SMEC.getValue();
1892dad0a645SDavid Majnemer     if (ComdatsChosen.count(&C))
1893dad0a645SDavid Majnemer       continue;
1894dad0a645SDavid Majnemer     Comdat::SelectionKind SK;
1895dad0a645SDavid Majnemer     bool LinkFromSrc;
1896dad0a645SDavid Majnemer     if (getComdatResult(&C, SK, LinkFromSrc))
1897dad0a645SDavid Majnemer       return true;
1898dad0a645SDavid Majnemer     ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc);
1899dad0a645SDavid Majnemer   }
1900dad0a645SDavid Majnemer 
190109d84addSDuncan P. N. Exon Smith   // Upgrade mismatched global arrays.
190209d84addSDuncan P. N. Exon Smith   upgradeMismatchedGlobals();
190309d84addSDuncan P. N. Exon Smith 
1904b1ed91f3SChris Lattner   // Insert all of the globals in src into the DstM module... without linking
1905b1ed91f3SChris Lattner   // initializers (which could refer to functions not yet mapped over).
19063bf3f1f5SYaron Keren   for (GlobalVariable &GV : SrcM->globals())
19073bf3f1f5SYaron Keren     if (linkGlobalValueProto(&GV))
1908b1ed91f3SChris Lattner       return true;
1909b1ed91f3SChris Lattner 
1910b1ed91f3SChris Lattner   // Link the functions together between the two modules, without doing function
1911b1ed91f3SChris Lattner   // bodies... this just adds external function prototypes to the DstM
1912b1ed91f3SChris Lattner   // function...  We do this so that when we begin processing function bodies,
1913b1ed91f3SChris Lattner   // all of the global values that may be referenced are available in our
1914b1ed91f3SChris Lattner   // ValueMap.
19153bf3f1f5SYaron Keren   for (Function &F :*SrcM)
19163bf3f1f5SYaron Keren     if (linkGlobalValueProto(&F))
1917b1ed91f3SChris Lattner       return true;
1918b1ed91f3SChris Lattner 
1919b1ed91f3SChris Lattner   // If there were any aliases, link them now.
19203bf3f1f5SYaron Keren   for (GlobalAlias &GA : SrcM->aliases())
19213bf3f1f5SYaron Keren     if (linkGlobalValueProto(&GA))
1922b1ed91f3SChris Lattner       return true;
1923b1ed91f3SChris Lattner 
19249f30fac4SRafael Espindola   for (AppendingVarInfo &AppendingVar : AppendingVars)
19253bf3f1f5SYaron Keren     linkAppendingVarInit(AppendingVar);
1926b1ed91f3SChris Lattner 
1927beadd56aSRafael Espindola   for (const auto &Entry : DstM->getComdatSymbolTable()) {
1928beadd56aSRafael Espindola     const Comdat &C = Entry.getValue();
1929beadd56aSRafael Espindola     if (C.getSelectionKind() == Comdat::Any)
1930beadd56aSRafael Espindola       continue;
1931beadd56aSRafael Espindola     const GlobalValue *GV = SrcM->getNamedValue(C.getName());
1932ea45d834SPeter Collingbourne     if (GV)
19334fb46cb8SDuncan P. N. Exon Smith       MapValue(GV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
1934beadd56aSRafael Espindola   }
1935beadd56aSRafael Espindola 
1936b1ed91f3SChris Lattner   // Link in the function bodies that are defined in the source module into
1937b1ed91f3SChris Lattner   // DstM.
1938f97d0cbeSRafael Espindola   for (Function &SF : *SrcM) {
1939d4bcefc7SRafael Espindola     // Skip if no body (function is external).
1940f97d0cbeSRafael Espindola     if (SF.isDeclaration())
1941d4bcefc7SRafael Espindola       continue;
1942d4bcefc7SRafael Espindola 
1943f97d0cbeSRafael Espindola     // Skip if not linking from source.
1944f97d0cbeSRafael Espindola     if (DoNotLinkFromSource.count(&SF))
1945f97d0cbeSRafael Espindola       continue;
1946f97d0cbeSRafael Espindola 
1947ef23711eSRafael Espindola     if (linkGlobalValueBody(SF))
194840d7ebedSRafael Espindola       return true;
1949b1ed91f3SChris Lattner   }
1950b1ed91f3SChris Lattner 
1951b1ed91f3SChris Lattner   // Resolve all uses of aliases with aliasees.
1952ef23711eSRafael Espindola   for (GlobalAlias &Src : SrcM->aliases()) {
1953ef23711eSRafael Espindola     if (DoNotLinkFromSource.count(&Src))
1954ef23711eSRafael Espindola       continue;
1955ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1956ef23711eSRafael Espindola   }
1957b1ed91f3SChris Lattner 
195891686d6dSBill Wendling   // Update the initializers in the DstM module now that all globals that may
195991686d6dSBill Wendling   // be referenced are in DstM.
1960ef23711eSRafael Espindola   for (GlobalVariable &Src : SrcM->globals()) {
1961ef23711eSRafael Espindola     // Only process initialized GV's or ones not already in dest.
1962ef23711eSRafael Espindola     if (!Src.hasInitializer() || DoNotLinkFromSource.count(&Src))
1963ef23711eSRafael Espindola       continue;
1964ef23711eSRafael Espindola     linkGlobalValueBody(Src);
1965ef23711eSRafael Espindola   }
196691686d6dSBill Wendling 
19671063293aSTeresa Johnson   // Note that we are done linking global value bodies. This prevents
19681063293aSTeresa Johnson   // metadata linking from creating new references.
19691063293aSTeresa Johnson   DoneLinkingBodies = true;
19701063293aSTeresa Johnson 
1971189b2526STeresa Johnson   // Remap all of the named MDNodes in Src into the DstM module. We do this
1972189b2526STeresa Johnson   // after linking GlobalValues so that MDNodes that reference GlobalValues
1973189b2526STeresa Johnson   // are properly remapped.
1974189b2526STeresa Johnson   linkNamedMDNodes();
1975189b2526STeresa Johnson 
1976189b2526STeresa Johnson   // Merge the module flags into the DstM module.
1977189b2526STeresa Johnson   if (linkModuleFlagsMetadata())
1978189b2526STeresa Johnson     return true;
1979189b2526STeresa Johnson 
19802609888fSAnton Korobeynikov   return false;
19812609888fSAnton Korobeynikov }
1982361e513dSReid Spencer 
198331ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
198431ad468dSRafael Espindola     : ETypes(E), IsPacked(P) {}
198531ad468dSRafael Espindola 
198631ad468dSRafael Espindola Linker::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
198731ad468dSRafael Espindola     : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
198831ad468dSRafael Espindola 
198931ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
199031ad468dSRafael Espindola   if (IsPacked != That.IsPacked)
199131ad468dSRafael Espindola     return false;
199231ad468dSRafael Espindola   if (ETypes != That.ETypes)
199331ad468dSRafael Espindola     return false;
199431ad468dSRafael Espindola   return true;
199531ad468dSRafael Espindola }
199631ad468dSRafael Espindola 
199731ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
199831ad468dSRafael Espindola   return !this->operator==(That);
199931ad468dSRafael Espindola }
200031ad468dSRafael Espindola 
200131ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getEmptyKey() {
200231ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getEmptyKey();
200331ad468dSRafael Espindola }
200431ad468dSRafael Espindola 
200531ad468dSRafael Espindola StructType *Linker::StructTypeKeyInfo::getTombstoneKey() {
200631ad468dSRafael Espindola   return DenseMapInfo<StructType *>::getTombstoneKey();
200731ad468dSRafael Espindola }
200831ad468dSRafael Espindola 
200931ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
201031ad468dSRafael Espindola   return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
201131ad468dSRafael Espindola                       Key.IsPacked);
201231ad468dSRafael Espindola }
201331ad468dSRafael Espindola 
201431ad468dSRafael Espindola unsigned Linker::StructTypeKeyInfo::getHashValue(const StructType *ST) {
201531ad468dSRafael Espindola   return getHashValue(KeyTy(ST));
201631ad468dSRafael Espindola }
201731ad468dSRafael Espindola 
201831ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
201931ad468dSRafael Espindola                                         const StructType *RHS) {
202031ad468dSRafael Espindola   if (RHS == getEmptyKey() || RHS == getTombstoneKey())
202131ad468dSRafael Espindola     return false;
202231ad468dSRafael Espindola   return LHS == KeyTy(RHS);
202331ad468dSRafael Espindola }
202431ad468dSRafael Espindola 
202531ad468dSRafael Espindola bool Linker::StructTypeKeyInfo::isEqual(const StructType *LHS,
202631ad468dSRafael Espindola                                         const StructType *RHS) {
202731ad468dSRafael Espindola   if (RHS == getEmptyKey())
202831ad468dSRafael Espindola     return LHS == getEmptyKey();
202931ad468dSRafael Espindola 
203031ad468dSRafael Espindola   if (RHS == getTombstoneKey())
203131ad468dSRafael Espindola     return LHS == getTombstoneKey();
203231ad468dSRafael Espindola 
203331ad468dSRafael Espindola   return KeyTy(LHS) == KeyTy(RHS);
203431ad468dSRafael Espindola }
203531ad468dSRafael Espindola 
203631ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
203731ad468dSRafael Espindola   assert(!Ty->isOpaque());
20383280a5d9SBenjamin Kramer   NonOpaqueStructTypes.insert(Ty);
203931ad468dSRafael Espindola }
204031ad468dSRafael Espindola 
2041a5b9e1cfSRafael Espindola void Linker::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
2042a5b9e1cfSRafael Espindola   assert(!Ty->isOpaque());
2043a5b9e1cfSRafael Espindola   NonOpaqueStructTypes.insert(Ty);
2044a5b9e1cfSRafael Espindola   bool Removed = OpaqueStructTypes.erase(Ty);
2045a5b9e1cfSRafael Espindola   (void)Removed;
2046a5b9e1cfSRafael Espindola   assert(Removed);
2047a5b9e1cfSRafael Espindola }
2048a5b9e1cfSRafael Espindola 
204931ad468dSRafael Espindola void Linker::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
205031ad468dSRafael Espindola   assert(Ty->isOpaque());
205131ad468dSRafael Espindola   OpaqueStructTypes.insert(Ty);
205231ad468dSRafael Espindola }
205331ad468dSRafael Espindola 
205431ad468dSRafael Espindola StructType *
205531ad468dSRafael Espindola Linker::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
205631ad468dSRafael Espindola                                                bool IsPacked) {
205731ad468dSRafael Espindola   Linker::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
205831ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find_as(Key);
205931ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
206031ad468dSRafael Espindola     return nullptr;
20613280a5d9SBenjamin Kramer   return *I;
206231ad468dSRafael Espindola }
206331ad468dSRafael Espindola 
206431ad468dSRafael Espindola bool Linker::IdentifiedStructTypeSet::hasType(StructType *Ty) {
206531ad468dSRafael Espindola   if (Ty->isOpaque())
206631ad468dSRafael Espindola     return OpaqueStructTypes.count(Ty);
206731ad468dSRafael Espindola   auto I = NonOpaqueStructTypes.find(Ty);
206831ad468dSRafael Espindola   if (I == NonOpaqueStructTypes.end())
206931ad468dSRafael Espindola     return false;
20703280a5d9SBenjamin Kramer   return *I == Ty;
207131ad468dSRafael Espindola }
207231ad468dSRafael Espindola 
20735cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
20745cb9c82aSRafael Espindola   this->Composite = M;
20755cb9c82aSRafael Espindola   this->DiagnosticHandler = DiagnosticHandler;
2076a4e85e3dSRafael Espindola 
2077a4e85e3dSRafael Espindola   TypeFinder StructTypes;
2078a4e85e3dSRafael Espindola   StructTypes.run(*M, true);
207931ad468dSRafael Espindola   for (StructType *Ty : StructTypes) {
208031ad468dSRafael Espindola     if (Ty->isOpaque())
208131ad468dSRafael Espindola       IdentifiedStructTypes.addOpaque(Ty);
208231ad468dSRafael Espindola     else
208331ad468dSRafael Espindola       IdentifiedStructTypes.addNonOpaque(Ty);
208431ad468dSRafael Espindola   }
2085aa9918aaSRafael Espindola }
20863df61b7bSRafael Espindola 
20875cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) {
20885cb9c82aSRafael Espindola   init(M, DiagnosticHandler);
20895cb9c82aSRafael Espindola }
20905cb9c82aSRafael Espindola 
20915cb9c82aSRafael Espindola Linker::Linker(Module *M) {
20925cb9c82aSRafael Espindola   init(M, [this](const DiagnosticInfo &DI) {
20935cb9c82aSRafael Espindola     Composite->getContext().diagnose(DI);
20945cb9c82aSRafael Espindola   });
20955cb9c82aSRafael Espindola }
20965cb9c82aSRafael Espindola 
209791e6f6e1SBill Wendling void Linker::deleteModule() {
209891e6f6e1SBill Wendling   delete Composite;
20992617dcceSCraig Topper   Composite = nullptr;
210091e6f6e1SBill Wendling }
210191e6f6e1SBill Wendling 
21028220e8a8SMehdi Amini bool Linker::linkInModule(Module *Src, unsigned Flags,
21038220e8a8SMehdi Amini                           const FunctionInfoIndex *Index,
2104c7ed52f2STeresa Johnson                           Function *FuncToImport) {
2105a4e85e3dSRafael Espindola   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src,
2106c7ed52f2STeresa Johnson                          DiagnosticHandler, Flags, Index, FuncToImport);
2107dab999d5SManman Ren   bool RetCode = TheLinker.run();
2108dab999d5SManman Ren   Composite->dropTriviallyDeadConstantArrays();
2109dab999d5SManman Ren   return RetCode;
21103df61b7bSRafael Espindola }
21113df61b7bSRafael Espindola 
21126487ce95SManman Ren void Linker::setModule(Module *Dst) {
21136487ce95SManman Ren   init(Dst, DiagnosticHandler);
21146487ce95SManman Ren }
21156487ce95SManman Ren 
2116b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2117b1ed91f3SChris Lattner // LinkModules entrypoint.
2118b1ed91f3SChris Lattner //===----------------------------------------------------------------------===//
2119b1ed91f3SChris Lattner 
212018c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module
212118c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs,
212218c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem.
212318c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be
212418c89411SRafael Espindola /// relied on to be consistent.
21259f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src,
2126020d4fb1SArtem Belevich                          DiagnosticHandlerFunction DiagnosticHandler,
2127020d4fb1SArtem Belevich                          unsigned Flags) {
21284160f5d3SRafael Espindola   Linker L(Dest, DiagnosticHandler);
2129020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
21304160f5d3SRafael Espindola }
21314160f5d3SRafael Espindola 
2132020d4fb1SArtem Belevich bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Flags) {
2133287f18b4SRafael Espindola   Linker L(Dest);
2134020d4fb1SArtem Belevich   return L.linkInModule(Src, Flags);
2135361e513dSReid Spencer }
2136a3aeb980SBill Wendling 
2137a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2138a3aeb980SBill Wendling // C API.
2139a3aeb980SBill Wendling //===----------------------------------------------------------------------===//
2140a3aeb980SBill Wendling 
2141a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
2142a57d588cSJuergen Ributzka                          LLVMLinkerMode Unused, char **OutMessages) {
214398ab63ceSRafael Espindola   Module *D = unwrap(Dest);
214498ab63ceSRafael Espindola   std::string Message;
21454160f5d3SRafael Espindola   raw_string_ostream Stream(Message);
21464160f5d3SRafael Espindola   DiagnosticPrinterRawOStream DP(Stream);
21474160f5d3SRafael Espindola 
21484160f5d3SRafael Espindola   LLVMBool Result = Linker::LinkModules(
21499f8eff31SRafael Espindola       D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); });
215098ab63ceSRafael Espindola 
2151ff715e2dSEli Bendersky   if (OutMessages && Result) {
2152ff715e2dSEli Bendersky     Stream.flush();
215398ab63ceSRafael Espindola     *OutMessages = strdup(Message.c_str());
2154ff715e2dSEli Bendersky   }
2155a3aeb980SBill Wendling   return Result;
2156a3aeb980SBill Wendling }
2157