159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7361e513dSReid Spencer // 8361e513dSReid Spencer //===----------------------------------------------------------------------===// 9361e513dSReid Spencer // 10361e513dSReid Spencer // This file implements the LLVM module linker. 11361e513dSReid Spencer // 12361e513dSReid Spencer //===----------------------------------------------------------------------===// 13361e513dSReid Spencer 146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h" 15ed0881b2SChandler Carruth #include "llvm-c/Linker.h" 1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h" 1766f02413SBill Wendling #include "llvm/ADT/SetVector.h" 180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h" 199fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 20*d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h" 21*d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h" 22*d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h" 239fb823bbSChandler Carruth #include "llvm/IR/Module.h" 24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h" 25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h" 26b6af2f36SBill Wendling #include "llvm/Support/Debug.h" 27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h" 28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h" 29981af002SWill Dietz #include <cctype> 3082d6ff6bSDavid Majnemer #include <tuple> 31361e513dSReid Spencer using namespace llvm; 32361e513dSReid Spencer 33e17f3708SEli Bendersky 34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 35b1ed91f3SChris Lattner // TypeMap implementation. 36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 37b1ed91f3SChris Lattner 38b1ed91f3SChris Lattner namespace { 39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType*, 32> TypeSet; 40aa9918aaSRafael Espindola 41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper { 42b1ed91f3SChris Lattner /// MappedTypes - This is a mapping from a source type to a destination type 43b1ed91f3SChris Lattner /// to use. 44b1ed91f3SChris Lattner DenseMap<Type*, Type*> MappedTypes; 45b1ed91f3SChris Lattner 46b1ed91f3SChris Lattner /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic, 47b1ed91f3SChris Lattner /// we speculatively add types to MappedTypes, but keep track of them here in 48b1ed91f3SChris Lattner /// case we need to roll back. 49b1ed91f3SChris Lattner SmallVector<Type*, 16> SpeculativeTypes; 50b1ed91f3SChris Lattner 515e3bd972SChris Lattner /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the 525e3bd972SChris Lattner /// source module that are mapped to an opaque struct in the destination 535e3bd972SChris Lattner /// module. 545e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 555e3bd972SChris Lattner 565e3bd972SChris Lattner /// DstResolvedOpaqueTypes - This is the set of opaque types in the 575e3bd972SChris Lattner /// destination modules who are getting a body from the source module. 585e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 59d48b7783SBill Wendling 608c2cc416SBill Wendling public: 61aa9918aaSRafael Espindola TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 62aa9918aaSRafael Espindola 63aa9918aaSRafael Espindola TypeSet &DstStructTypesSet; 64b1ed91f3SChris Lattner /// addTypeMapping - Indicate that the specified type in the destination 65b1ed91f3SChris Lattner /// module is conceptually equivalent to the specified type in the source 66b1ed91f3SChris Lattner /// module. 67b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 68b1ed91f3SChris Lattner 69b1ed91f3SChris Lattner /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 70b1ed91f3SChris Lattner /// module from a type definition in the source module. 71b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 72b1ed91f3SChris Lattner 73b1ed91f3SChris Lattner /// get - Return the mapped type to use for the specified input type from the 74b1ed91f3SChris Lattner /// source module. 75b1ed91f3SChris Lattner Type *get(Type *SrcTy); 76b1ed91f3SChris Lattner 77b1ed91f3SChris Lattner FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));} 78b1ed91f3SChris Lattner 79b6af2f36SBill Wendling /// dump - Dump out the type map for debugging purposes. 80b6af2f36SBill Wendling void dump() const { 81b6af2f36SBill Wendling for (DenseMap<Type*, Type*>::const_iterator 82b6af2f36SBill Wendling I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) { 83b6af2f36SBill Wendling dbgs() << "TypeMap: "; 84c0087f36SJustin Bogner I->first->print(dbgs()); 85b6af2f36SBill Wendling dbgs() << " => "; 86c0087f36SJustin Bogner I->second->print(dbgs()); 87b6af2f36SBill Wendling dbgs() << '\n'; 88b6af2f36SBill Wendling } 89b6af2f36SBill Wendling } 90b6af2f36SBill Wendling 91b1ed91f3SChris Lattner private: 92b1ed91f3SChris Lattner Type *getImpl(Type *T); 93b1ed91f3SChris Lattner /// remapType - Implement the ValueMapTypeRemapper interface. 948548299aSCraig Topper Type *remapType(Type *SrcTy) override { 95b1ed91f3SChris Lattner return get(SrcTy); 96b1ed91f3SChris Lattner } 97b1ed91f3SChris Lattner 98b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 99b1ed91f3SChris Lattner }; 100b1ed91f3SChris Lattner } 101b1ed91f3SChris Lattner 102b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 103b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 104b1ed91f3SChris Lattner if (Entry) return; 105b1ed91f3SChris Lattner 106b1ed91f3SChris Lattner if (DstTy == SrcTy) { 107b1ed91f3SChris Lattner Entry = DstTy; 108b1ed91f3SChris Lattner return; 109b1ed91f3SChris Lattner } 110b1ed91f3SChris Lattner 111b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 112b1ed91f3SChris Lattner // mapping between them if so. 113d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy, SrcTy)) { 114b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 115b1ed91f3SChris Lattner // any speculative mappings we've established. 116b1ed91f3SChris Lattner for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i) 117b1ed91f3SChris Lattner MappedTypes.erase(SpeculativeTypes[i]); 118d48b7783SBill Wendling } 119b1ed91f3SChris Lattner SpeculativeTypes.clear(); 120b1ed91f3SChris Lattner } 121b1ed91f3SChris Lattner 122b1ed91f3SChris Lattner /// areTypesIsomorphic - Recursively walk this pair of types, returning true 123b1ed91f3SChris Lattner /// if they are isomorphic, false if they are not. 124b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 125b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 126b1ed91f3SChris Lattner if (DstTy->getTypeID() != SrcTy->getTypeID()) return false; 127b1ed91f3SChris Lattner 128b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 129b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 130b1ed91f3SChris Lattner if (Entry) 131b1ed91f3SChris Lattner return Entry == DstTy; 132b1ed91f3SChris Lattner 133b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 134b1ed91f3SChris Lattner // non-speculatively. 135b1ed91f3SChris Lattner if (DstTy == SrcTy) { 136b1ed91f3SChris Lattner Entry = DstTy; 137361e513dSReid Spencer return true; 138361e513dSReid Spencer } 139361e513dSReid Spencer 140b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 141361e513dSReid Spencer 142b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 143b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 144b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 145b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 146b1ed91f3SChris Lattner Entry = DstTy; 147b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 148b1ed91f3SChris Lattner return true; 149361e513dSReid Spencer } 150b1ed91f3SChris Lattner 1515e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1525e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 1535e3bd972SChris Lattner // the dest, but fill it in later. This doesn't need to be speculative. If 1545e3bd972SChris Lattner // this is the second (different) type that we're trying to map onto the 1555e3bd972SChris Lattner // same opaque type then we fail. 156b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1575e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 1585e3bd972SChris Lattner if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy))) 1595e3bd972SChris Lattner return false; 1605e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 161b1ed91f3SChris Lattner Entry = DstTy; 162b1ed91f3SChris Lattner return true; 163b1ed91f3SChris Lattner } 164b1ed91f3SChris Lattner } 165b1ed91f3SChris Lattner 166b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 167b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 168b1ed91f3SChris Lattner return false; 169b1ed91f3SChris Lattner 170b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 171b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 172b1ed91f3SChris Lattner return false; // bitwidth disagrees. 173b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 174b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 175b1ed91f3SChris Lattner return false; 176eaf9b762SChris Lattner 177b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 178b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 179b1ed91f3SChris Lattner return false; 180b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 181b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 18244f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 183b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 184b1ed91f3SChris Lattner return false; 185b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 186b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 187b1ed91f3SChris Lattner return false; 188b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1895fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 190361e513dSReid Spencer return false; 191361e513dSReid Spencer } 192361e513dSReid Spencer 193b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 194b1ed91f3SChris Lattner // check the subelements. 195b1ed91f3SChris Lattner Entry = DstTy; 196b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 197eee6f995SChris Lattner 198d48b7783SBill Wendling for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i) 199d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy->getContainedType(i), 200d48b7783SBill Wendling SrcTy->getContainedType(i))) 201b1ed91f3SChris Lattner return false; 202eee6f995SChris Lattner 203b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 204eee6f995SChris Lattner return true; 205eee6f995SChris Lattner } 206eee6f995SChris Lattner 207b1ed91f3SChris Lattner /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 208b1ed91f3SChris Lattner /// module from a type definition in the source module. 209b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 210b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 211b1ed91f3SChris Lattner SmallString<16> TmpName; 212eee6f995SChris Lattner 213b1ed91f3SChris Lattner // Note that processing entries in this loop (calling 'get') can add new 2145e3bd972SChris Lattner // entries to the SrcDefinitionsToResolve vector. 2155e3bd972SChris Lattner while (!SrcDefinitionsToResolve.empty()) { 2165e3bd972SChris Lattner StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val(); 217b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 218eee6f995SChris Lattner 219b1ed91f3SChris Lattner // TypeMap is a many-to-one mapping, if there were multiple types that 220b1ed91f3SChris Lattner // provide a body for DstSTy then previous iterations of this loop may have 221b1ed91f3SChris Lattner // already handled it. Just ignore this case. 222b1ed91f3SChris Lattner if (!DstSTy->isOpaque()) continue; 223b1ed91f3SChris Lattner assert(!SrcSTy->isOpaque() && "Not resolving a definition?"); 224b1ed91f3SChris Lattner 225b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 226b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 227b1ed91f3SChris Lattner for (unsigned i = 0, e = Elements.size(); i != e; ++i) 228b1ed91f3SChris Lattner Elements[i] = getImpl(SrcSTy->getElementType(i)); 229b1ed91f3SChris Lattner 230b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 231b1ed91f3SChris Lattner 232b1ed91f3SChris Lattner // If DstSTy has no name or has a longer name than STy, then viciously steal 233b1ed91f3SChris Lattner // STy's name. 234b1ed91f3SChris Lattner if (!SrcSTy->hasName()) continue; 235b1ed91f3SChris Lattner StringRef SrcName = SrcSTy->getName(); 236b1ed91f3SChris Lattner 237b1ed91f3SChris Lattner if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) { 238b1ed91f3SChris Lattner TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end()); 239b1ed91f3SChris Lattner SrcSTy->setName(""); 240b1ed91f3SChris Lattner DstSTy->setName(TmpName.str()); 241b1ed91f3SChris Lattner TmpName.clear(); 242b1ed91f3SChris Lattner } 243b1ed91f3SChris Lattner } 2445e3bd972SChris Lattner 2455e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 246eee6f995SChris Lattner } 247eee6f995SChris Lattner 248b1ed91f3SChris Lattner /// get - Return the mapped type to use for the specified input type from the 249b1ed91f3SChris Lattner /// source module. 250b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 251b1ed91f3SChris Lattner Type *Result = getImpl(Ty); 252b1ed91f3SChris Lattner 253b1ed91f3SChris Lattner // If this caused a reference to any struct type, resolve it before returning. 2545e3bd972SChris Lattner if (!SrcDefinitionsToResolve.empty()) 255b1ed91f3SChris Lattner linkDefinedTypeBodies(); 256b1ed91f3SChris Lattner return Result; 257eee6f995SChris Lattner } 258eee6f995SChris Lattner 259b1ed91f3SChris Lattner /// getImpl - This is the recursive version of get(). 260b1ed91f3SChris Lattner Type *TypeMapTy::getImpl(Type *Ty) { 261b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 262b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 263b1ed91f3SChris Lattner if (*Entry) return *Entry; 264b1ed91f3SChris Lattner 265b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 266b1ed91f3SChris Lattner // then rebuild the type from inside out. 26744f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 268b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 269b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 270b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 271b1ed91f3SChris Lattner return *Entry = Ty; 272b1ed91f3SChris Lattner 273b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 274b1ed91f3SChris Lattner bool AnyChange = false; 275b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 276b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 277b1ed91f3SChris Lattner for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) { 278b1ed91f3SChris Lattner ElementTypes[i] = getImpl(Ty->getContainedType(i)); 279b1ed91f3SChris Lattner AnyChange |= ElementTypes[i] != Ty->getContainedType(i); 280eee6f995SChris Lattner } 281b1ed91f3SChris Lattner 282b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 283b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 284b1ed91f3SChris Lattner if (*Entry) return *Entry; 285b1ed91f3SChris Lattner 286b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 287b1ed91f3SChris Lattner // as-is. 288b1ed91f3SChris Lattner if (!AnyChange) 289b1ed91f3SChris Lattner return *Entry = Ty; 290b1ed91f3SChris Lattner 291b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 292b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 293a2886c21SCraig Topper default: llvm_unreachable("unknown derived type to remap"); 294b1ed91f3SChris Lattner case Type::ArrayTyID: 295b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 296b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 297b1ed91f3SChris Lattner case Type::VectorTyID: 298b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 299b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 300b1ed91f3SChris Lattner case Type::PointerTyID: 301b1ed91f3SChris Lattner return *Entry = PointerType::get(ElementTypes[0], 302b1ed91f3SChris Lattner cast<PointerType>(Ty)->getAddressSpace()); 303b1ed91f3SChris Lattner case Type::FunctionTyID: 304b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 305717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 306b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 307b1ed91f3SChris Lattner case Type::StructTyID: 308b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 309b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 310b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 311b1ed91f3SChris Lattner } 312b1ed91f3SChris Lattner } 313b1ed91f3SChris Lattner 314b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 315b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 316b1ed91f3SChris Lattner // module has something like: 317b1ed91f3SChris Lattner // %T = type {%T*, i32} 318b1ed91f3SChris Lattner // @GV = global %T* null 319b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 320b1ed91f3SChris Lattner // 321b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 322b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 323b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 324b1ed91f3SChris Lattner // %A = type { i32 } 325b1ed91f3SChris Lattner // and the source module has something like 326b1ed91f3SChris Lattner // %A' = type { i32 } 327b1ed91f3SChris Lattner // %B = type { %A'* } 328b1ed91f3SChris Lattner // @GV = global %B* null 329b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 330b1ed91f3SChris Lattner // pristine "%B" name from the source module. 331b1ed91f3SChris Lattner // 332b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 333b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 334b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 335b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 336b1ed91f3SChris Lattner // it and always rebuild a type here. 337b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 338b1ed91f3SChris Lattner 339b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 340aa9918aaSRafael Espindola if (STy->isOpaque()) { 341aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 342aa9918aaSRafael Espindola // identified structs in the destination module. 343aa9918aaSRafael Espindola DstStructTypesSet.insert(STy); 344b1ed91f3SChris Lattner return *Entry = STy; 345aa9918aaSRafael Espindola } 346b1ed91f3SChris Lattner 347b1ed91f3SChris Lattner // Otherwise we create a new type and resolve its body later. This will be 348b1ed91f3SChris Lattner // resolved by the top level of get(). 3495e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(STy); 3505e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 351aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 352aa9918aaSRafael Espindola // identified structs in the destination module. 353aa9918aaSRafael Espindola DstStructTypesSet.insert(DTy); 3545e3bd972SChris Lattner DstResolvedOpaqueTypes.insert(DTy); 3555e3bd972SChris Lattner return *Entry = DTy; 356b1ed91f3SChris Lattner } 357b1ed91f3SChris Lattner 358b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 359b1ed91f3SChris Lattner // ModuleLinker implementation. 360b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 361b1ed91f3SChris Lattner 362b1ed91f3SChris Lattner namespace { 363f6f121e2SJames Molloy class ModuleLinker; 364f6f121e2SJames Molloy 365f6f121e2SJames Molloy /// ValueMaterializerTy - Creates prototypes for functions that are lazily 366f6f121e2SJames Molloy /// linked on the fly. This speeds up linking for modules with many 367f6f121e2SJames Molloy /// lazily linked functions of which few get used. 368f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 369f6f121e2SJames Molloy TypeMapTy &TypeMap; 370f6f121e2SJames Molloy Module *DstM; 371f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions; 372f6f121e2SJames Molloy public: 373f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 374f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions) : 375f6f121e2SJames Molloy ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 376f6f121e2SJames Molloy LazilyLinkFunctions(LazilyLinkFunctions) { 377f6f121e2SJames Molloy } 378f6f121e2SJames Molloy 3798548299aSCraig Topper Value *materializeValueFor(Value *V) override; 380f6f121e2SJames Molloy }; 381f6f121e2SJames Molloy 382*d12b4a33SRafael Espindola namespace { 383*d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 384*d12b4a33SRafael Espindola const Twine &Msg; 385*d12b4a33SRafael Espindola 386*d12b4a33SRafael Espindola public: 387*d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 388*d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 389*d12b4a33SRafael Espindola }; 390*d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 391*d12b4a33SRafael Espindola const Twine &Msg) 392*d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 393*d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 394*d12b4a33SRafael Espindola } 395*d12b4a33SRafael Espindola 396b1ed91f3SChris Lattner /// ModuleLinker - This is an implementation class for the LinkModules 397b1ed91f3SChris Lattner /// function, which is the entrypoint for this file. 398b1ed91f3SChris Lattner class ModuleLinker { 399b1ed91f3SChris Lattner Module *DstM, *SrcM; 400b1ed91f3SChris Lattner 401b1ed91f3SChris Lattner TypeMapTy TypeMap; 402f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 403b1ed91f3SChris Lattner 404b1ed91f3SChris Lattner /// ValueMap - Mapping of values from what they used to be in Src, to what 405b1ed91f3SChris Lattner /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves 406b1ed91f3SChris Lattner /// some overhead due to the use of Value handles which the Linker doesn't 407b1ed91f3SChris Lattner /// actually need, but this allows us to reuse the ValueMapper code. 408b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 409b1ed91f3SChris Lattner 410b1ed91f3SChris Lattner struct AppendingVarInfo { 411b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 412b1ed91f3SChris Lattner Constant *DstInit; // Old initializer from dest module. 413b1ed91f3SChris Lattner Constant *SrcInit; // Old initializer from src module. 414b1ed91f3SChris Lattner }; 415b1ed91f3SChris Lattner 416b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 417b1ed91f3SChris Lattner 418cbb91408STanya Lattner unsigned Mode; // Mode to treat source module. 419cbb91408STanya Lattner 420cbb91408STanya Lattner // Set of items not to link in from source. 421cbb91408STanya Lattner SmallPtrSet<const Value*, 16> DoNotLinkFromSource; 422cbb91408STanya Lattner 4230a48b877STanya Lattner // Vector of functions to lazily link in. 424fa228782SBill Wendling std::vector<Function*> LazilyLinkFunctions; 4250a48b877STanya Lattner 426b1ed91f3SChris Lattner public: 427*d12b4a33SRafael Espindola ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode) 428f6f121e2SJames Molloy : DstM(dstM), SrcM(srcM), TypeMap(Set), 429*d12b4a33SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), Mode(mode) {} 430b1ed91f3SChris Lattner 431b1ed91f3SChris Lattner bool run(); 432b1ed91f3SChris Lattner 433b1ed91f3SChris Lattner private: 434*d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 435*d12b4a33SRafael Espindola const GlobalValue &Src); 436dbb0bd1aSRafael Espindola 437*d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 438b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 439*d12b4a33SRafael Espindola DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message)); 440b1ed91f3SChris Lattner return true; 441b1ed91f3SChris Lattner } 442b1ed91f3SChris Lattner 443*d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 444*d12b4a33SRafael Espindola DstM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message)); 445*d12b4a33SRafael Espindola } 446*d12b4a33SRafael Espindola 447dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 448dad0a645SDavid Majnemer const GlobalVariable *&GVar); 449dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 450dad0a645SDavid Majnemer Comdat::SelectionKind Src, 451dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 452dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 453dad0a645SDavid Majnemer bool &LinkFromSrc); 454dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 455dad0a645SDavid Majnemer ComdatsChosen; 456dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 457dad0a645SDavid Majnemer bool &LinkFromSrc); 458dad0a645SDavid Majnemer 459b1ed91f3SChris Lattner /// getLinkageResult - This analyzes the two global values and determines 460b1ed91f3SChris Lattner /// what the result will look like in the destination module. 461b1ed91f3SChris Lattner bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 46223f8d64bSRafael Espindola GlobalValue::LinkageTypes <, 46323f8d64bSRafael Espindola GlobalValue::VisibilityTypes &Vis, 46423f8d64bSRafael Espindola bool &LinkFromSrc); 465b1ed91f3SChris Lattner 466b1ed91f3SChris Lattner /// getLinkedToGlobal - Given a global in the source module, return the 467b1ed91f3SChris Lattner /// global in the destination module that is being linked to, if any. 468b1ed91f3SChris Lattner GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) { 469b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 470b1ed91f3SChris Lattner // there is no name match-up going on. 471b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4722617dcceSCraig Topper return nullptr; 473b1ed91f3SChris Lattner 474b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 475b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 4762617dcceSCraig Topper if (!DGV) return nullptr; 477b1ed91f3SChris Lattner 478b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 479b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 480b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4812617dcceSCraig Topper return nullptr; 482b1ed91f3SChris Lattner 483b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 484b1ed91f3SChris Lattner return DGV; 485b1ed91f3SChris Lattner } 486b1ed91f3SChris Lattner 487b1ed91f3SChris Lattner void computeTypeMapping(); 488b1ed91f3SChris Lattner 48909d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 49009d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 49109d84addSDuncan P. N. Exon Smith 492b1ed91f3SChris Lattner bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV); 493b1ed91f3SChris Lattner bool linkGlobalProto(GlobalVariable *SrcGV); 494b1ed91f3SChris Lattner bool linkFunctionProto(Function *SrcF); 495b1ed91f3SChris Lattner bool linkAliasProto(GlobalAlias *SrcA); 49666f02413SBill Wendling bool linkModuleFlagsMetadata(); 497b1ed91f3SChris Lattner 498b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 499b1ed91f3SChris Lattner void linkGlobalInits(); 500b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 501b1ed91f3SChris Lattner void linkAliasBodies(); 502b1ed91f3SChris Lattner void linkNamedMDNodes(); 503eee6f995SChris Lattner }; 504d48b7783SBill Wendling } 505d48b7783SBill Wendling 506b1ed91f3SChris Lattner /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict 50790246aa7SReid Spencer /// in the symbol table. This is good for all clients except for us. Go 50890246aa7SReid Spencer /// through the trouble to force this back. 509b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 510b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 511b1ed91f3SChris Lattner // there is nothing for us to do. 512b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 513b1ed91f3SChris Lattner return; 514b1ed91f3SChris Lattner 515b1ed91f3SChris Lattner Module *M = GV->getParent(); 516361e513dSReid Spencer 517361e513dSReid Spencer // If there is a conflict, rename the conflict. 518b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5192a8d2e0eSChris Lattner GV->takeName(ConflictGV); 520361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 521b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5222a8d2e0eSChris Lattner } else { 5232a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5243aaaa0b2SReid Spencer } 5253aaaa0b2SReid Spencer } 5263aaaa0b2SReid Spencer 527b6af2f36SBill Wendling /// copyGVAttributes - copy additional attributes (those not needed to construct 5283aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV. 529b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 530dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 53199e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 532a7d9c69cSRafael Espindola unsigned Alignment; 53399e05cf1SRafael Espindola if (DestGO) 53499e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 535a7d9c69cSRafael Espindola 536dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 537a7d9c69cSRafael Espindola 53899e05cf1SRafael Espindola if (DestGO) 53999e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 540b1ed91f3SChris Lattner 541b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 542361e513dSReid Spencer } 543361e513dSReid Spencer 54423f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 54523f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 54623f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 54723f8d64bSRafael Espindola return false; 54823f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 54923f8d64bSRafael Espindola return true; 55023f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 55123f8d64bSRafael Espindola return false; 55223f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 55323f8d64bSRafael Espindola return true; 55423f8d64bSRafael Espindola return false; 55523f8d64bSRafael Espindola } 55623f8d64bSRafael Espindola 557f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 558f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 559f6f121e2SJames Molloy if (!SF) 5602617dcceSCraig Topper return nullptr; 561f6f121e2SJames Molloy 562f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 563f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 564f6f121e2SJames Molloy copyGVAttributes(DF, SF); 565f6f121e2SJames Molloy 5663931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5673931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5683931c28bSRafael Espindola DF->setComdat(DC); 5693931c28bSRafael Espindola } 5703931c28bSRafael Espindola 571f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 572f6f121e2SJames Molloy return DF; 573f6f121e2SJames Molloy } 574f6f121e2SJames Molloy 575dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 576dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 577dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 578dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 579dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 580dad0a645SDavid Majnemer if (!GVal) 581dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 582dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 583dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 584dad0a645SDavid Majnemer } 585dad0a645SDavid Majnemer 586dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 587dad0a645SDavid Majnemer if (!GVar) 588dad0a645SDavid Majnemer return emitError( 589dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 590dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 591dad0a645SDavid Majnemer 592dad0a645SDavid Majnemer return false; 593dad0a645SDavid Majnemer } 594dad0a645SDavid Majnemer 595dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 596dad0a645SDavid Majnemer Comdat::SelectionKind Src, 597dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 598dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 599dad0a645SDavid Majnemer bool &LinkFromSrc) { 600dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 601dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 602dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 603dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 604dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 605dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 606dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 607dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 608dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 609dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 610dad0a645SDavid Majnemer else 611dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 612dad0a645SDavid Majnemer } else if (Src == Dst) { 613dad0a645SDavid Majnemer Result = Dst; 614dad0a645SDavid Majnemer } else { 615dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 616dad0a645SDavid Majnemer "': invalid selection kinds!"); 617dad0a645SDavid Majnemer } 618dad0a645SDavid Majnemer 619dad0a645SDavid Majnemer switch (Result) { 620dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 621dad0a645SDavid Majnemer // Go with Dst. 622dad0a645SDavid Majnemer LinkFromSrc = false; 623dad0a645SDavid Majnemer break; 624dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 625dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 626dad0a645SDavid Majnemer "': noduplicates has been violated!"); 627dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 628dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 629dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 630dad0a645SDavid Majnemer const GlobalVariable *DstGV; 631dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 632dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 633dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 634dad0a645SDavid Majnemer return true; 635dad0a645SDavid Majnemer 636dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 637dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 638dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 639dad0a645SDavid Majnemer return emitError( 640dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 641dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 642dad0a645SDavid Majnemer } 643dad0a645SDavid Majnemer uint64_t DstSize = 644dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 645dad0a645SDavid Majnemer uint64_t SrcSize = 646dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 647dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 648dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 649dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 650dad0a645SDavid Majnemer "': ExactMatch violated!"); 651dad0a645SDavid Majnemer LinkFromSrc = false; 652dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 653dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 654dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 655dad0a645SDavid Majnemer if (SrcSize != DstSize) 656dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 657dad0a645SDavid Majnemer "': SameSize violated!"); 658dad0a645SDavid Majnemer LinkFromSrc = false; 659dad0a645SDavid Majnemer } else { 660dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 661dad0a645SDavid Majnemer } 662dad0a645SDavid Majnemer break; 663dad0a645SDavid Majnemer } 664dad0a645SDavid Majnemer } 665dad0a645SDavid Majnemer 666dad0a645SDavid Majnemer return false; 667dad0a645SDavid Majnemer } 668dad0a645SDavid Majnemer 669dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 670dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 671dad0a645SDavid Majnemer bool &LinkFromSrc) { 672b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 673dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 674dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 675dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6762ef3f299SRafael Espindola 677b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 678b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 679b16196a3SRafael Espindola LinkFromSrc = true; 680b16196a3SRafael Espindola Result = SSK; 6812ef3f299SRafael Espindola return false; 682b16196a3SRafael Espindola } 6832ef3f299SRafael Espindola 684dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 685dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6862ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6872ef3f299SRafael Espindola LinkFromSrc); 688dad0a645SDavid Majnemer } 689f6f121e2SJames Molloy 690*d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 691*d12b4a33SRafael Espindola const GlobalValue &Dest, 692dbb0bd1aSRafael Espindola const GlobalValue &Src) { 693d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 694d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 695dbb0bd1aSRafael Espindola 6960910605aSRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 6970910605aSRafael Espindola DataLayout DL(Dest.getParent()); 6980910605aSRafael Espindola 699dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 700dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 701dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 702*d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 703dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 704*d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 705*d12b4a33SRafael Espindola return false; 706*d12b4a33SRafael Espindola } 707dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 708*d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 709*d12b4a33SRafael Espindola return false; 710dbb0bd1aSRafael Espindola } 711dbb0bd1aSRafael Espindola 712*d12b4a33SRafael Espindola if (DestIsDeclaration) { 713dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 714*d12b4a33SRafael Espindola LinkFromSrc = true; 715*d12b4a33SRafael Espindola return false; 716*d12b4a33SRafael Espindola } 717dbb0bd1aSRafael Espindola 7180910605aSRafael Espindola if (Src.hasCommonLinkage()) { 719*d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 720*d12b4a33SRafael Espindola LinkFromSrc = true; 7210910605aSRafael Espindola return false; 722*d12b4a33SRafael Espindola } 723*d12b4a33SRafael Espindola 724*d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 725*d12b4a33SRafael Espindola LinkFromSrc = false; 726*d12b4a33SRafael Espindola return false; 727*d12b4a33SRafael Espindola } 7280910605aSRafael Espindola 7290910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7300910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 731*d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 732*d12b4a33SRafael Espindola return false; 7330910605aSRafael Espindola } 7340910605aSRafael Espindola 735dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 736dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 737dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7380910605aSRafael Espindola 739*d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 740*d12b4a33SRafael Espindola LinkFromSrc = true; 741*d12b4a33SRafael Espindola return false; 742*d12b4a33SRafael Espindola } 743dbb0bd1aSRafael Espindola 744*d12b4a33SRafael Espindola LinkFromSrc = false; 7450910605aSRafael Espindola return false; 746dbb0bd1aSRafael Espindola } 747dbb0bd1aSRafael Espindola 748dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 749dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 750*d12b4a33SRafael Espindola LinkFromSrc = true; 751*d12b4a33SRafael Espindola return false; 752dbb0bd1aSRafael Espindola } 753dbb0bd1aSRafael Espindola 754dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 755dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 756dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 757dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 758dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 759dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 760dbb0bd1aSRafael Espindola } 761dbb0bd1aSRafael Espindola 76283a7ddbcSRafael Espindola /// This analyzes the two global values and determines what the result will look 76383a7ddbcSRafael Espindola /// like in the destination module. In particular, it computes the resultant 76483a7ddbcSRafael Espindola /// linkage type and visibility, computes whether the global in the source 76583a7ddbcSRafael Espindola /// should be copied over to the destination (replacing the existing one), and 76683a7ddbcSRafael Espindola /// computes whether this linkage is an error or not. 767b1ed91f3SChris Lattner bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 768b1ed91f3SChris Lattner GlobalValue::LinkageTypes <, 76923f8d64bSRafael Espindola GlobalValue::VisibilityTypes &Vis, 770b1ed91f3SChris Lattner bool &LinkFromSrc) { 771b1ed91f3SChris Lattner assert(Dest && "Must have two globals being queried"); 772b1ed91f3SChris Lattner assert(!Src->hasLocalLinkage() && 773fc61de39SChris Lattner "If Src has internal linkage, Dest shouldn't be set!"); 774b1ed91f3SChris Lattner 775*d12b4a33SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *Dest, *Src)) 776dbb0bd1aSRafael Espindola return true; 777b1ed91f3SChris Lattner 778dbb0bd1aSRafael Espindola if (LinkFromSrc) 779d61d39ecSAnton Korobeynikov LT = Src->getLinkage(); 780dbb0bd1aSRafael Espindola else 781c83c8d4eSRafael Espindola LT = Dest->getLinkage(); 78231fc4f95SAnton Korobeynikov 78323f8d64bSRafael Espindola // Compute the visibility. We follow the rules in the System V Application 78423f8d64bSRafael Espindola // Binary Interface. 785b2becfdbSDuncan P. N. Exon Smith assert(!GlobalValue::isLocalLinkage(LT) && 786b2becfdbSDuncan P. N. Exon Smith "Symbols with local linkage should not be merged"); 78723f8d64bSRafael Espindola Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ? 78823f8d64bSRafael Espindola Dest->getVisibility() : Src->getVisibility(); 789fc61de39SChris Lattner return false; 790fc61de39SChris Lattner } 791361e513dSReid Spencer 792b1ed91f3SChris Lattner /// computeTypeMapping - Loop over all of the linked values to compute type 793b1ed91f3SChris Lattner /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then 794b1ed91f3SChris Lattner /// we have two struct types 'Foo' but one got renamed when the module was 795b1ed91f3SChris Lattner /// loaded into the same LLVMContext. 796b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 797b1ed91f3SChris Lattner // Incorporate globals. 798b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 799b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 800b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(I); 8012617dcceSCraig Topper if (!DGV) continue; 802b1ed91f3SChris Lattner 803b1ed91f3SChris Lattner if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) { 804b1ed91f3SChris Lattner TypeMap.addTypeMapping(DGV->getType(), I->getType()); 805b1ed91f3SChris Lattner continue; 8065c310be0SDevang Patel } 8075c310be0SDevang Patel 808b1ed91f3SChris Lattner // Unify the element type of appending arrays. 809b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 810b1ed91f3SChris Lattner ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType()); 811b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 812b1ed91f3SChris Lattner } 81334fc5a0eSChris Lattner 814b1ed91f3SChris Lattner // Incorporate functions. 815b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) { 816b1ed91f3SChris Lattner if (GlobalValue *DGV = getLinkedToGlobal(I)) 817b1ed91f3SChris Lattner TypeMap.addTypeMapping(DGV->getType(), I->getType()); 818b1ed91f3SChris Lattner } 819e79f4c77SAnton Korobeynikov 820d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 821d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 8222b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 8232b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 8248555a37cSBill Wendling TypeFinder SrcStructTypes; 8258555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 8262b3f61afSBill Wendling SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 8272b3f61afSBill Wendling SrcStructTypes.end()); 8282b3f61afSBill Wendling 8292b3f61afSBill Wendling for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 8302b3f61afSBill Wendling StructType *ST = SrcStructTypes[i]; 8312b3f61afSBill Wendling if (!ST->hasName()) continue; 8322b3f61afSBill Wendling 8332b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 834d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 835d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 83683c74e9fSGuy Benyei ST->getName().back() == '.' || 83783c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 838d48b7783SBill Wendling continue; 8392b3f61afSBill Wendling 8402b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 841d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 8422b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8438737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8448737480dSBill Wendling // actually used in the destination module. This can happen in situations 8458737480dSBill Wendling // like this: 8468737480dSBill Wendling // 8478737480dSBill Wendling // Module A Module B 8488737480dSBill Wendling // -------- -------- 8498737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8508737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8518737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8528737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8538737480dSBill Wendling // 8548737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8558737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8568737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8578737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8588737480dSBill Wendling // variables using one type and some using the other. 859aa9918aaSRafael Espindola if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST)) 8602b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8612b3f61afSBill Wendling } 8622b3f61afSBill Wendling 863b1ed91f3SChris Lattner // Don't bother incorporating aliases, they aren't generally typed well. 864361e513dSReid Spencer 865b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 866b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 867b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 868b1ed91f3SChris Lattner } 869c08e7a00SChris Lattner 87009d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 87109d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 87209d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 87309d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 87409d84addSDuncan P. N. Exon Smith 87509d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 87609d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 87709d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 87809d84addSDuncan P. N. Exon Smith VoidPtrTy}; 87909d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 88009d84addSDuncan P. N. Exon Smith 88109d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 88209d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 88309d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 88409d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 88509d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 88609d84addSDuncan P. N. Exon Smith return; 88709d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 88809d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 88909d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 89009d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 89109d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 89209d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 89309d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 89409d84addSDuncan P. N. Exon Smith } 89509d84addSDuncan P. N. Exon Smith } 89609d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 89709d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 89809d84addSDuncan P. N. Exon Smith 89909d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 90009d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 90109d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 90209d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 90309d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 90409d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 90509d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 90609d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 90709d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 90809d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 90909d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 91009d84addSDuncan P. N. Exon Smith } 91109d84addSDuncan P. N. Exon Smith 91209d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 91309d84addSDuncan P. N. Exon Smith // Look for the global arrays. 91409d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 91509d84addSDuncan P. N. Exon Smith if (!DstGV) 91609d84addSDuncan P. N. Exon Smith return; 91709d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 91809d84addSDuncan P. N. Exon Smith if (!SrcGV) 91909d84addSDuncan P. N. Exon Smith return; 92009d84addSDuncan P. N. Exon Smith 92109d84addSDuncan P. N. Exon Smith // Check if the types already match. 92209d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 92309d84addSDuncan P. N. Exon Smith auto *SrcTy = 92409d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 92509d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 92609d84addSDuncan P. N. Exon Smith return; 92709d84addSDuncan P. N. Exon Smith 92809d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 92909d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 93009d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 93109d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 93209d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 93309d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 93409d84addSDuncan P. N. Exon Smith return; 93509d84addSDuncan P. N. Exon Smith } 93609d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 93709d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 93809d84addSDuncan P. N. Exon Smith 93909d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 94009d84addSDuncan P. N. Exon Smith } 94109d84addSDuncan P. N. Exon Smith 94209d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 94309d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 94409d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 94509d84addSDuncan P. N. Exon Smith } 94609d84addSDuncan P. N. Exon Smith 947b1ed91f3SChris Lattner /// linkAppendingVarProto - If there were any appending global variables, link 948b1ed91f3SChris Lattner /// them together now. Return true on error. 949b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 950b1ed91f3SChris Lattner GlobalVariable *SrcGV) { 951d48b7783SBill Wendling 952b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 953b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 954b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 955361e513dSReid Spencer 956b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 957b1ed91f3SChris Lattner ArrayType *SrcTy = 958b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 959b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 960b1ed91f3SChris Lattner 961b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 962b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 963b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 964b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 965b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 966b1ed91f3SChris Lattner 967b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 968b1ed91f3SChris Lattner return emitError( 969b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 970b1ed91f3SChris Lattner 971b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 972b1ed91f3SChris Lattner return emitError( 973b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 974b1ed91f3SChris Lattner 975fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 976fac3a018SRafael Espindola return emitError( 977fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 978fac3a018SRafael Espindola 97964c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 980b1ed91f3SChris Lattner return emitError( 981b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 982b1ed91f3SChris Lattner 983b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 984b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 985b1ed91f3SChris Lattner 986b1ed91f3SChris Lattner // Create the new global variable. 987b1ed91f3SChris Lattner GlobalVariable *NG = 988b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9892617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 990cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 991b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 992b1ed91f3SChris Lattner 993b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 994b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 995b1ed91f3SChris Lattner 996b1ed91f3SChris Lattner AppendingVarInfo AVI; 997b1ed91f3SChris Lattner AVI.NewGV = NG; 998b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 999b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 1000b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 1001b1ed91f3SChris Lattner 1002b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 1003b1ed91f3SChris Lattner // global. 1004b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 1005b1ed91f3SChris Lattner 1006b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 1007b1ed91f3SChris Lattner DstGV->eraseFromParent(); 1008b1ed91f3SChris Lattner 1009cbb91408STanya Lattner // Track the source variable so we don't try to link it. 1010cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 1011cbb91408STanya Lattner 1012b1ed91f3SChris Lattner return false; 1013b1ed91f3SChris Lattner } 1014b1ed91f3SChris Lattner 1015b1ed91f3SChris Lattner /// linkGlobalProto - Loop through the global variables in the src module and 1016b1ed91f3SChris Lattner /// merge them into the dest module. 1017b1ed91f3SChris Lattner bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) { 1018b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 101923f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 1020d4885daeSRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 1021fe3842cdSRafael Espindola unsigned Alignment = SGV->getAlignment(); 1022b1ed91f3SChris Lattner 1023dad0a645SDavid Majnemer bool LinkFromSrc = false; 1024dad0a645SDavid Majnemer Comdat *DC = nullptr; 1025dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 1026dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1027dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1028dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1029dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1030dad0a645SDavid Majnemer } 1031dad0a645SDavid Majnemer 1032b1ed91f3SChris Lattner if (DGV) { 1033dad0a645SDavid Majnemer if (!DC) { 1034b1ed91f3SChris Lattner // Concatenation of appending linkage variables is magic and handled later. 1035b1ed91f3SChris Lattner if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage()) 1036b1ed91f3SChris Lattner return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV); 1037b1ed91f3SChris Lattner 1038b1ed91f3SChris Lattner // Determine whether linkage of these two globals follows the source 1039b1ed91f3SChris Lattner // module's definition or the destination module's definition. 10401b9633d7SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 104123f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 104223f8d64bSRafael Espindola if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc)) 1043fc61de39SChris Lattner return true; 104423f8d64bSRafael Espindola NewVisibility = NV; 1045fd9a9415SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1046fe3842cdSRafael Espindola if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage()) 1047fe3842cdSRafael Espindola Alignment = std::max(Alignment, DGV->getAlignment()); 1048fe3842cdSRafael Espindola else if (!LinkFromSrc) 1049fe3842cdSRafael Espindola Alignment = DGV->getAlignment(); 1050361e513dSReid Spencer 1051b1ed91f3SChris Lattner // If we're not linking from the source, then keep the definition that we 1052b1ed91f3SChris Lattner // have. 1053b1ed91f3SChris Lattner if (!LinkFromSrc) { 105434fc5a0eSChris Lattner // Special case for const propagation. 1055fe3842cdSRafael Espindola if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) { 1056fe3842cdSRafael Espindola DGVar->setAlignment(Alignment); 1057fe3842cdSRafael Espindola 1058dad0a645SDavid Majnemer if (DGVar->isDeclaration() && SGV->isConstant() && 1059dad0a645SDavid Majnemer !DGVar->isConstant()) 106034fc5a0eSChris Lattner DGVar->setConstant(true); 1061fe3842cdSRafael Espindola } 106234fc5a0eSChris Lattner 1063d4885daeSRafael Espindola // Set calculated linkage, visibility and unnamed_addr. 106434fc5a0eSChris Lattner DGV->setLinkage(NewLinkage); 106523f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 1066d4885daeSRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1067dad0a645SDavid Majnemer } 1068dad0a645SDavid Majnemer } 106934fc5a0eSChris Lattner 1070dad0a645SDavid Majnemer if (!LinkFromSrc) { 1071b1ed91f3SChris Lattner // Make sure to remember this mapping. 1072b1ed91f3SChris Lattner ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType())); 1073b1ed91f3SChris Lattner 1074cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 1075cbb91408STanya Lattner // processing global initializers. 1076cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1077cbb91408STanya Lattner 1078b1ed91f3SChris Lattner return false; 1079361e513dSReid Spencer } 1080b1ed91f3SChris Lattner } 1081b1ed91f3SChris Lattner 1082dad0a645SDavid Majnemer // If the Comdat this variable was inside of wasn't selected, skip it. 1083dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1084dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SGV); 1085dad0a645SDavid Majnemer return false; 1086dad0a645SDavid Majnemer } 1087dad0a645SDavid Majnemer 1088b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1089b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1090b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1091b1ed91f3SChris Lattner GlobalVariable *NewDGV = 1092b1ed91f3SChris Lattner new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()), 10932617dcceSCraig Topper SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr, 10942617dcceSCraig Topper SGV->getName(), /*insertbefore*/nullptr, 1095cbe34b4cSHans Wennborg SGV->getThreadLocalMode(), 1096b1ed91f3SChris Lattner SGV->getType()->getAddressSpace()); 1097b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 1098b6af2f36SBill Wendling copyGVAttributes(NewDGV, SGV); 1099fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 110023f8d64bSRafael Espindola if (NewVisibility) 110123f8d64bSRafael Espindola NewDGV->setVisibility(*NewVisibility); 1102d4885daeSRafael Espindola NewDGV->setUnnamedAddr(HasUnnamedAddr); 1103b1ed91f3SChris Lattner 1104dad0a645SDavid Majnemer if (DC) 1105dad0a645SDavid Majnemer NewDGV->setComdat(DC); 1106dad0a645SDavid Majnemer 1107b1ed91f3SChris Lattner if (DGV) { 1108b1ed91f3SChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType())); 1109b1ed91f3SChris Lattner DGV->eraseFromParent(); 1110b1ed91f3SChris Lattner } 1111b1ed91f3SChris Lattner 1112b1ed91f3SChris Lattner // Make sure to remember this mapping. 1113b1ed91f3SChris Lattner ValueMap[SGV] = NewDGV; 1114361e513dSReid Spencer return false; 1115361e513dSReid Spencer } 1116361e513dSReid Spencer 1117b1ed91f3SChris Lattner /// linkFunctionProto - Link the function in the source module into the 1118b1ed91f3SChris Lattner /// destination module if needed, setting up mapping information. 1119b1ed91f3SChris Lattner bool ModuleLinker::linkFunctionProto(Function *SF) { 1120b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SF); 112123f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 1122fd9a9415SRafael Espindola bool HasUnnamedAddr = SF->hasUnnamedAddr(); 1123dac5fa94SAnton Korobeynikov 11240ead7a50SChris Lattner bool LinkFromSrc = false; 1125dad0a645SDavid Majnemer Comdat *DC = nullptr; 1126dad0a645SDavid Majnemer if (const Comdat *SC = SF->getComdat()) { 1127dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1128dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1129dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1130dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1131dad0a645SDavid Majnemer } 1132dad0a645SDavid Majnemer 1133dad0a645SDavid Majnemer if (DGV) { 1134dad0a645SDavid Majnemer if (!DC) { 1135dad0a645SDavid Majnemer GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 113623f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 113723f8d64bSRafael Espindola if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc)) 11380ead7a50SChris Lattner return true; 113923f8d64bSRafael Espindola NewVisibility = NV; 1140fd9a9415SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 11410ead7a50SChris Lattner 1142b1ed91f3SChris Lattner if (!LinkFromSrc) { 11430ead7a50SChris Lattner // Set calculated linkage 11440ead7a50SChris Lattner DGV->setLinkage(NewLinkage); 114523f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 1146fd9a9415SRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1147dad0a645SDavid Majnemer } 1148dad0a645SDavid Majnemer } 114977e8ac4dSChris Lattner 1150dad0a645SDavid Majnemer if (!LinkFromSrc) { 11510ead7a50SChris Lattner // Make sure to remember this mapping. 1152b1ed91f3SChris Lattner ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType())); 1153b1ed91f3SChris Lattner 1154cbb91408STanya Lattner // Track the function from the source module so we don't attempt to remap 1155cbb91408STanya Lattner // it. 1156cbb91408STanya Lattner DoNotLinkFromSource.insert(SF); 1157cbb91408STanya Lattner 1158b1ed91f3SChris Lattner return false; 1159361e513dSReid Spencer } 1160b1ed91f3SChris Lattner } 1161b1ed91f3SChris Lattner 1162f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1163f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1164f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1165f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1166f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1167f6f121e2SJames Molloy return false; 1168f6f121e2SJames Molloy } 1169f6f121e2SJames Molloy 1170dad0a645SDavid Majnemer // If the Comdat this function was inside of wasn't selected, skip it. 1171dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1172dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SF); 1173dad0a645SDavid Majnemer return false; 1174dad0a645SDavid Majnemer } 1175dad0a645SDavid Majnemer 1176b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1177b1ed91f3SChris Lattner // bring SF over. 1178b1ed91f3SChris Lattner Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()), 1179b1ed91f3SChris Lattner SF->getLinkage(), SF->getName(), DstM); 1180b6af2f36SBill Wendling copyGVAttributes(NewDF, SF); 118123f8d64bSRafael Espindola if (NewVisibility) 118223f8d64bSRafael Espindola NewDF->setVisibility(*NewVisibility); 1183fd9a9415SRafael Espindola NewDF->setUnnamedAddr(HasUnnamedAddr); 1184b1ed91f3SChris Lattner 1185dad0a645SDavid Majnemer if (DC) 1186dad0a645SDavid Majnemer NewDF->setComdat(DC); 1187dad0a645SDavid Majnemer 1188b1ed91f3SChris Lattner if (DGV) { 1189b1ed91f3SChris Lattner // Any uses of DF need to change to NewDF, with cast. 1190b1ed91f3SChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType())); 1191b1ed91f3SChris Lattner DGV->eraseFromParent(); 1192b1ed91f3SChris Lattner } 1193b1ed91f3SChris Lattner 1194b1ed91f3SChris Lattner ValueMap[SF] = NewDF; 1195361e513dSReid Spencer return false; 1196361e513dSReid Spencer } 1197361e513dSReid Spencer 1198b1ed91f3SChris Lattner /// LinkAliasProto - Set up prototypes for any aliases that come over from the 1199b1ed91f3SChris Lattner /// source module. 1200b1ed91f3SChris Lattner bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) { 1201b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGA); 120223f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 120342a4c9f9SRafael Espindola bool HasUnnamedAddr = SGA->hasUnnamedAddr(); 1204b1ed91f3SChris Lattner 1205dad0a645SDavid Majnemer bool LinkFromSrc = false; 1206dad0a645SDavid Majnemer Comdat *DC = nullptr; 1207dad0a645SDavid Majnemer if (const Comdat *SC = SGA->getComdat()) { 1208dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1209dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1210dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1211dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1212dad0a645SDavid Majnemer } 1213dad0a645SDavid Majnemer 1214b1ed91f3SChris Lattner if (DGV) { 1215dad0a645SDavid Majnemer if (!DC) { 1216b1ed91f3SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 121723f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 121823f8d64bSRafael Espindola if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc)) 1219b1ed91f3SChris Lattner return true; 122023f8d64bSRafael Espindola NewVisibility = NV; 122142a4c9f9SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1222b1ed91f3SChris Lattner 1223b1ed91f3SChris Lattner if (!LinkFromSrc) { 1224b1ed91f3SChris Lattner // Set calculated linkage. 1225b1ed91f3SChris Lattner DGV->setLinkage(NewLinkage); 122623f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 122742a4c9f9SRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1228dad0a645SDavid Majnemer } 1229dad0a645SDavid Majnemer } 1230b1ed91f3SChris Lattner 1231dad0a645SDavid Majnemer if (!LinkFromSrc) { 1232b1ed91f3SChris Lattner // Make sure to remember this mapping. 1233b1ed91f3SChris Lattner ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType())); 1234b1ed91f3SChris Lattner 1235cbb91408STanya Lattner // Track the alias from the source module so we don't attempt to remap it. 1236cbb91408STanya Lattner DoNotLinkFromSource.insert(SGA); 1237cbb91408STanya Lattner 1238b1ed91f3SChris Lattner return false; 1239b1ed91f3SChris Lattner } 1240b1ed91f3SChris Lattner } 1241b1ed91f3SChris Lattner 1242dad0a645SDavid Majnemer // If the Comdat this alias was inside of wasn't selected, skip it. 1243dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1244dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SGA); 1245dad0a645SDavid Majnemer return false; 1246dad0a645SDavid Majnemer } 1247dad0a645SDavid Majnemer 1248b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1249b1ed91f3SChris Lattner // bring over SGA. 12504fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1251f1bedd37SRafael Espindola auto *NewDA = 1252f1bedd37SRafael Espindola GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 125383705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1254b6af2f36SBill Wendling copyGVAttributes(NewDA, SGA); 125523f8d64bSRafael Espindola if (NewVisibility) 125623f8d64bSRafael Espindola NewDA->setVisibility(*NewVisibility); 125742a4c9f9SRafael Espindola NewDA->setUnnamedAddr(HasUnnamedAddr); 1258b1ed91f3SChris Lattner 125964c1e180SRafael Espindola if (DGV) { 126064c1e180SRafael Espindola // Any uses of DGV need to change to NewDA, with cast. 126164c1e180SRafael Espindola DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType())); 126264c1e180SRafael Espindola DGV->eraseFromParent(); 126364c1e180SRafael Espindola } 1264b1ed91f3SChris Lattner 1265b1ed91f3SChris Lattner ValueMap[SGA] = NewDA; 1266b1ed91f3SChris Lattner return false; 1267b1ed91f3SChris Lattner } 1268b1ed91f3SChris Lattner 126900245f42SChris Lattner static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) { 12706705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 127100245f42SChris Lattner 12726705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 12736705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 127400245f42SChris Lattner } 127500245f42SChris Lattner 1276b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1277b1ed91f3SChris Lattner // Merge the initializer. 1278d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1279d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1280b1ed91f3SChris Lattner 1281d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1282d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 128300245f42SChris Lattner 1284b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1285d31dc048SRafael Espindola 1286d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1287d31dc048SRafael Espindola bool IsNewStructor = 1288d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1289d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1290d31dc048SRafael Espindola 1291d31dc048SRafael Espindola for (auto *V : SrcElements) { 1292d31dc048SRafael Espindola if (IsNewStructor) { 1293d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1294d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1295d31dc048SRafael Espindola continue; 1296d31dc048SRafael Espindola } 1297d31dc048SRafael Espindola DstElements.push_back( 1298d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1299d31dc048SRafael Espindola } 1300d31dc048SRafael Espindola if (IsNewStructor) { 1301d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1302d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1303d31dc048SRafael Espindola } 1304d31dc048SRafael Espindola 1305d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1306b1ed91f3SChris Lattner } 1307b1ed91f3SChris Lattner 1308b6af2f36SBill Wendling /// linkGlobalInits - Update the initializers in the Dest module now that all 1309b6af2f36SBill Wendling /// globals that may be referenced are in Dest. 1310b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1311b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1312b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1313b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1314cbb91408STanya Lattner 1315cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1316cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1317b1ed91f3SChris Lattner 1318b1ed91f3SChris Lattner // Grab destination global variable. 1319b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1320b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1321b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1322f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1323b1ed91f3SChris Lattner } 1324b1ed91f3SChris Lattner } 1325b1ed91f3SChris Lattner 1326b6af2f36SBill Wendling /// linkFunctionBody - Copy the source function over into the dest function and 1327b6af2f36SBill Wendling /// fix up references to values. At this point we know that Dest is an external 1328b6af2f36SBill Wendling /// function, and that Src is not. 1329b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1330b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1331361e513dSReid Spencer 13327391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1333b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1334531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1335361e513dSReid Spencer I != E; ++I, ++DI) { 1336b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1337361e513dSReid Spencer 1338b1ed91f3SChris Lattner // Add a mapping to our mapping. 133966a6271cSAnton Korobeynikov ValueMap[I] = DI; 1340361e513dSReid Spencer } 1341361e513dSReid Spencer 1342cbb91408STanya Lattner if (Mode == Linker::DestroySource) { 13432f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1344b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1345361e513dSReid Spencer 1346361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1347361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1348361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 134943f8d164SChris Lattner // functions and patch them up to point to the local versions. 1350b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 135143f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 1352f6f121e2SJames Molloy RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, 1353f6f121e2SJames Molloy &TypeMap, &ValMaterializer); 13547391dde1SChris Lattner 1355cbb91408STanya Lattner } else { 1356cbb91408STanya Lattner // Clone the body of the function into the dest function. 1357cbb91408STanya Lattner SmallVector<ReturnInst*, 8> Returns; // Ignore returns. 13582617dcceSCraig Topper CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", nullptr, 1359f6f121e2SJames Molloy &TypeMap, &ValMaterializer); 1360cbb91408STanya Lattner } 1361cbb91408STanya Lattner 13627391dde1SChris Lattner // There is no need to map the arguments anymore. 136344ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 136444ab8aefSChris Lattner I != E; ++I) 13653aaaa0b2SReid Spencer ValueMap.erase(I); 1366cbb91408STanya Lattner 1367361e513dSReid Spencer } 1368361e513dSReid Spencer 1369b6af2f36SBill Wendling /// linkAliasBodies - Insert all of the aliases in Src into the Dest module. 1370b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1371b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1372cbb91408STanya Lattner I != E; ++I) { 1373cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1374cbb91408STanya Lattner continue; 1375b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1376b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 13776b238633SRafael Espindola Constant *Val = 13786b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 137964c1e180SRafael Espindola DA->setAliasee(Val); 13802c4a34aeSDavid Chisnall } 1381b1ed91f3SChris Lattner } 1382cbb91408STanya Lattner } 1383b1ed91f3SChris Lattner 1384b6af2f36SBill Wendling /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest 1385b1ed91f3SChris Lattner /// module. 1386b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 138766f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1388b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1389b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 139066f02413SBill Wendling // Don't link module flags here. Do them separately. 139166f02413SBill Wendling if (&*I == SrcModFlags) continue; 1392b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1393b1ed91f3SChris Lattner // Add Src elements into Dest node. 1394b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1395b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1396f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1397b1ed91f3SChris Lattner } 1398b1ed91f3SChris Lattner } 1399b1ed91f3SChris Lattner 140066f02413SBill Wendling /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest 140166f02413SBill Wendling /// module. 140266f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 14030ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 140466f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 140566f02413SBill Wendling if (!SrcModFlags) return false; 140666f02413SBill Wendling 140766f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 140866f02413SBill Wendling // over the source module's flags. 14090ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 141066f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 141166f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 141266f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 141366f02413SBill Wendling 141466f02413SBill Wendling return false; 141566f02413SBill Wendling } 141666f02413SBill Wendling 14170ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 14180ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 14190ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 14200ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 14210ec72bbcSDaniel Dunbar MDNode *Op = DstModFlags->getOperand(I); 14220ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 14230ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 14240ec72bbcSDaniel Dunbar 14250ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 14260ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 14270ec72bbcSDaniel Dunbar } else { 14280ec72bbcSDaniel Dunbar Flags[ID] = Op; 14290ec72bbcSDaniel Dunbar } 14300ec72bbcSDaniel Dunbar } 14310ec72bbcSDaniel Dunbar 14320ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 14330ec72bbcSDaniel Dunbar // requirements. 143466f02413SBill Wendling bool HasErr = false; 14350ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 14360ec72bbcSDaniel Dunbar MDNode *SrcOp = SrcModFlags->getOperand(I); 14370ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 14380ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 14390ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 14400ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 144166f02413SBill Wendling 14420ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 14430ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 14440ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 14450ec72bbcSDaniel Dunbar // it. 14460ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 14470ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 14480ec72bbcSDaniel Dunbar } 14490ec72bbcSDaniel Dunbar continue; 14500ec72bbcSDaniel Dunbar } 145166f02413SBill Wendling 14520ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 14530ec72bbcSDaniel Dunbar if (!DstOp) { 14540ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 14550ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 14560ec72bbcSDaniel Dunbar continue; 14570ec72bbcSDaniel Dunbar } 145866f02413SBill Wendling 14590ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 14600ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 14610ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 14620ec72bbcSDaniel Dunbar 14630ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 14640ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 14650ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 14660ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 14670ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 14680ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 14690ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 14700ec72bbcSDaniel Dunbar } 14710ec72bbcSDaniel Dunbar continue; 14720ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 14730ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 14740ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 14750ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 14760ec72bbcSDaniel Dunbar continue; 14770ec72bbcSDaniel Dunbar } 14780ec72bbcSDaniel Dunbar 14790ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 14800ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 14810ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 148266f02413SBill Wendling "': IDs have conflicting behaviors"); 14830ec72bbcSDaniel Dunbar continue; 148466f02413SBill Wendling } 148566f02413SBill Wendling 14860ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 14870ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 14880ec72bbcSDaniel Dunbar case Module::Require: 14892a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 14900ec72bbcSDaniel Dunbar case Module::Error: { 14910ec72bbcSDaniel Dunbar // Emit an error if the values differ. 14920ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 14930ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 14940ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 149566f02413SBill Wendling } 14960ec72bbcSDaniel Dunbar continue; 149766f02413SBill Wendling } 14980ec72bbcSDaniel Dunbar case Module::Warning: { 14990ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 15000ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1501*d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1502*d12b4a33SRafael Espindola "': IDs have conflicting values"); 1503e17f3708SEli Bendersky } 15040ec72bbcSDaniel Dunbar continue; 15050ec72bbcSDaniel Dunbar } 1506d77d9fb0SDaniel Dunbar case Module::Append: { 1507d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1508d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1509d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1510d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1511d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1512d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1513d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1514d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1515d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1516d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1517d77d9fb0SDaniel Dunbar NumOps))); 1518d77d9fb0SDaniel Dunbar delete[] Values; 1519d77d9fb0SDaniel Dunbar break; 1520d77d9fb0SDaniel Dunbar } 1521d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1522d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1523d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1524d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1525d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1526d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1527d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1528d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1529d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1530d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1531d77d9fb0SDaniel Dunbar Elts.end()))); 1532d77d9fb0SDaniel Dunbar break; 1533d77d9fb0SDaniel Dunbar } 153466f02413SBill Wendling } 153566f02413SBill Wendling } 153666f02413SBill Wendling 15370ec72bbcSDaniel Dunbar // Check all of the requirements. 15380ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 15390ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 15400ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 15410ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 15420ec72bbcSDaniel Dunbar 15430ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 15440ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 15450ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 15469273b539SBill Wendling "': does not have the required value"); 15470ec72bbcSDaniel Dunbar continue; 154866f02413SBill Wendling } 154966f02413SBill Wendling } 155066f02413SBill Wendling 155166f02413SBill Wendling return HasErr; 155266f02413SBill Wendling } 155366f02413SBill Wendling 1554b1ed91f3SChris Lattner bool ModuleLinker::run() { 155566f02413SBill Wendling assert(DstM && "Null destination module"); 155666f02413SBill Wendling assert(SrcM && "Null source module"); 1557b1ed91f3SChris Lattner 1558b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1559b1ed91f3SChris Lattner // doesn't have one already. 1560f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1561b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1562b1ed91f3SChris Lattner 1563b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1564b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1565b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1566b1ed91f3SChris Lattner 1567f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1568ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1569*d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1570*d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1571*d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1572*d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1573*d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1574e17f3708SEli Bendersky } 1575b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1576b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1577*d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1578*d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1579*d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1580*d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1581*d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1582e17f3708SEli Bendersky } 1583b1ed91f3SChris Lattner 1584b1ed91f3SChris Lattner // Append the module inline asm string. 1585b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1586b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1587b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1588b1ed91f3SChris Lattner else 1589b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1590b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1591b1ed91f3SChris Lattner } 1592b1ed91f3SChris Lattner 1593b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1594b1ed91f3SChris Lattner computeTypeMapping(); 1595b1ed91f3SChris Lattner 1596dad0a645SDavid Majnemer ComdatsChosen.clear(); 1597dad0a645SDavid Majnemer for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) { 1598dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1599dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1600dad0a645SDavid Majnemer continue; 1601dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1602dad0a645SDavid Majnemer bool LinkFromSrc; 1603dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1604dad0a645SDavid Majnemer return true; 1605dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1606dad0a645SDavid Majnemer } 1607dad0a645SDavid Majnemer 160809d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 160909d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 161009d84addSDuncan P. N. Exon Smith 1611b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1612b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1613b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1614b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1615b1ed91f3SChris Lattner if (linkGlobalProto(I)) 1616b1ed91f3SChris Lattner return true; 1617b1ed91f3SChris Lattner 1618b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1619b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1620b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1621b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1622b1ed91f3SChris Lattner // ValueMap. 1623b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1624b1ed91f3SChris Lattner if (linkFunctionProto(I)) 1625b1ed91f3SChris Lattner return true; 1626b1ed91f3SChris Lattner 1627b1ed91f3SChris Lattner // If there were any aliases, link them now. 1628b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1629b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1630b1ed91f3SChris Lattner if (linkAliasProto(I)) 1631b1ed91f3SChris Lattner return true; 1632b1ed91f3SChris Lattner 1633b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1634b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1635b1ed91f3SChris Lattner 1636b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1637b1ed91f3SChris Lattner // DstM. 1638b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1639ea166d44STanya Lattner // Skip if not linking from source. 1640ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1641ea166d44STanya Lattner 16423fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 16433fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 16443fa50f9bSPeter Collingbourne // Link in the prefix data. 16453fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 16463fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 16473fa50f9bSPeter Collingbourne } 16483fa50f9bSPeter Collingbourne 1649d4bcefc7SRafael Espindola // Materialize if needed. 1650d4bcefc7SRafael Espindola if (SF->isMaterializable()) { 1651*d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1652*d12b4a33SRafael Espindola return emitError(EC.message()); 16535a52e6dcSRafael Espindola } 1654b1ed91f3SChris Lattner 1655d4bcefc7SRafael Espindola // Skip if no body (function is external). 1656d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1657d4bcefc7SRafael Espindola continue; 1658d4bcefc7SRafael Espindola 16593fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 166000623787SBill Wendling SF->Dematerialize(); 1661b1ed91f3SChris Lattner } 1662b1ed91f3SChris Lattner 1663b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1664b1ed91f3SChris Lattner linkAliasBodies(); 1665b1ed91f3SChris Lattner 166666f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 16676ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 16686ddbb2e2SDevang Patel // are properly remapped. 16696ddbb2e2SDevang Patel linkNamedMDNodes(); 16706ddbb2e2SDevang Patel 167166f02413SBill Wendling // Merge the module flags into the DstM module. 167266f02413SBill Wendling if (linkModuleFlagsMetadata()) 167366f02413SBill Wendling return true; 167466f02413SBill Wendling 167591686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 167691686d6dSBill Wendling // be referenced are in DstM. 167791686d6dSBill Wendling linkGlobalInits(); 167891686d6dSBill Wendling 16790a48b877STanya Lattner // Process vector of lazily linked in functions. 16800a48b877STanya Lattner bool LinkedInAnyFunctions; 16810a48b877STanya Lattner do { 16820a48b877STanya Lattner LinkedInAnyFunctions = false; 16830a48b877STanya Lattner 1684fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 16850a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1686f6f121e2SJames Molloy Function *SF = *I; 1687f6f121e2SJames Molloy if (!SF) 16880a48b877STanya Lattner continue; 16890a48b877STanya Lattner 1690fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 16913fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 16923fa50f9bSPeter Collingbourne // Link in the prefix data. 16933fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 16943fa50f9bSPeter Collingbourne ValueMap, 16953fa50f9bSPeter Collingbourne RF_None, 16963fa50f9bSPeter Collingbourne &TypeMap, 16973fa50f9bSPeter Collingbourne &ValMaterializer)); 16983fa50f9bSPeter Collingbourne } 16990a48b877STanya Lattner 1700d4bcefc7SRafael Espindola // Materialize if needed. 1701d4bcefc7SRafael Espindola if (SF->isMaterializable()) { 1702*d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1703*d12b4a33SRafael Espindola return emitError(EC.message()); 17045a52e6dcSRafael Espindola } 17050a48b877STanya Lattner 1706d4bcefc7SRafael Espindola // Skip if no body (function is external). 1707d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1708d4bcefc7SRafael Espindola continue; 1709d4bcefc7SRafael Espindola 1710f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1711f6f121e2SJames Molloy // invalidate I. 1712f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1713f6f121e2SJames Molloy 17140a48b877STanya Lattner // Link in function body. 17150a48b877STanya Lattner linkFunctionBody(DF, SF); 171600623787SBill Wendling SF->Dematerialize(); 17170a48b877STanya Lattner 17180a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 17190a48b877STanya Lattner // since we linked in a function. 17200a48b877STanya Lattner LinkedInAnyFunctions = true; 1721f6f121e2SJames Molloy break; 17220a48b877STanya Lattner } 17230a48b877STanya Lattner } while (LinkedInAnyFunctions); 17240a48b877STanya Lattner 1725b1ed91f3SChris Lattner // Now that all of the types from the source are used, resolve any structs 1726b1ed91f3SChris Lattner // copied over to the dest that didn't exist there. 1727b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 17282609888fSAnton Korobeynikov 17292609888fSAnton Korobeynikov return false; 17302609888fSAnton Korobeynikov } 1731361e513dSReid Spencer 1732*d12b4a33SRafael Espindola Linker::Linker(Module *M) : Composite(M) { 1733aa9918aaSRafael Espindola TypeFinder StructTypes; 1734aa9918aaSRafael Espindola StructTypes.run(*M, true); 1735aa9918aaSRafael Espindola IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1736aa9918aaSRafael Espindola } 17373df61b7bSRafael Espindola 17383df61b7bSRafael Espindola Linker::~Linker() { 17393df61b7bSRafael Espindola } 17403df61b7bSRafael Espindola 174191e6f6e1SBill Wendling void Linker::deleteModule() { 174291e6f6e1SBill Wendling delete Composite; 17432617dcceSCraig Topper Composite = nullptr; 174491e6f6e1SBill Wendling } 174591e6f6e1SBill Wendling 1746*d12b4a33SRafael Espindola bool Linker::linkInModule(Module *Src, unsigned Mode) { 1747*d12b4a33SRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode); 1748*d12b4a33SRafael Espindola return TheLinker.run(); 17493df61b7bSRafael Espindola } 17503df61b7bSRafael Espindola 1751b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1752b1ed91f3SChris Lattner // LinkModules entrypoint. 1753b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1754b1ed91f3SChris Lattner 1755b6af2f36SBill Wendling /// LinkModules - This function links two modules together, with the resulting 1756970cc634SEli Bendersky /// Dest module modified to be the composite of the two input modules. If an 1757b6af2f36SBill Wendling /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate 1758b6af2f36SBill Wendling /// the problem. Upon failure, the Dest module could be in a modified state, 1759b6af2f36SBill Wendling /// and shouldn't be relied on to be consistent. 1760*d12b4a33SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode) { 1761287f18b4SRafael Espindola Linker L(Dest); 1762*d12b4a33SRafael Espindola return L.linkInModule(Src, Mode); 1763361e513dSReid Spencer } 1764a3aeb980SBill Wendling 1765a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1766a3aeb980SBill Wendling // C API. 1767a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1768a3aeb980SBill Wendling 1769a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1770a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 1771*d12b4a33SRafael Espindola LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src), Mode); 1772a3aeb980SBill Wendling return Result; 1773a3aeb980SBill Wendling } 1774