159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7361e513dSReid Spencer // 8361e513dSReid Spencer //===----------------------------------------------------------------------===// 9361e513dSReid Spencer // 10361e513dSReid Spencer // This file implements the LLVM module linker. 11361e513dSReid Spencer // 12361e513dSReid Spencer //===----------------------------------------------------------------------===// 13361e513dSReid Spencer 146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h" 15ed0881b2SChandler Carruth #include "llvm-c/Linker.h" 1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h" 1766f02413SBill Wendling #include "llvm/ADT/SetVector.h" 180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h" 199fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h" 21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h" 22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h" 239fb823bbSChandler Carruth #include "llvm/IR/Module.h" 24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h" 25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h" 26b6af2f36SBill Wendling #include "llvm/Support/Debug.h" 27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h" 28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h" 29981af002SWill Dietz #include <cctype> 3082d6ff6bSDavid Majnemer #include <tuple> 31361e513dSReid Spencer using namespace llvm; 32361e513dSReid Spencer 33e17f3708SEli Bendersky 34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 35b1ed91f3SChris Lattner // TypeMap implementation. 36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 37b1ed91f3SChris Lattner 38b1ed91f3SChris Lattner namespace { 39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType *, 32> TypeSet; 40aa9918aaSRafael Espindola 41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper { 4218c89411SRafael Espindola /// This is a mapping from a source type to a destination type to use. 43b1ed91f3SChris Lattner DenseMap<Type*, Type*> MappedTypes; 44b1ed91f3SChris Lattner 4518c89411SRafael Espindola /// When checking to see if two subgraphs are isomorphic, we speculatively 4618c89411SRafael Espindola /// add types to MappedTypes, but keep track of them here in case we need to 4718c89411SRafael Espindola /// roll back. 48b1ed91f3SChris Lattner SmallVector<Type*, 16> SpeculativeTypes; 49b1ed91f3SChris Lattner 5018c89411SRafael Espindola /// This is a list of non-opaque structs in the source module that are mapped 5118c89411SRafael Espindola /// to an opaque struct in the destination module. 525e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 535e3bd972SChris Lattner 5418c89411SRafael Espindola /// This is the set of opaque types in the destination modules who are 5518c89411SRafael Espindola /// getting a body from the source module. 565e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 57d48b7783SBill Wendling 588c2cc416SBill Wendling public: 59aa9918aaSRafael Espindola TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 60aa9918aaSRafael Espindola 61aa9918aaSRafael Espindola TypeSet &DstStructTypesSet; 6218c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6318c89411SRafael Espindola /// equivalent to the specified type in the source module. 64b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 65b1ed91f3SChris Lattner 66b1ed91f3SChris Lattner /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest 67b1ed91f3SChris Lattner /// module from a type definition in the source module. 68b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 69b1ed91f3SChris Lattner 7018c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 71b1ed91f3SChris Lattner /// source module. 72b1ed91f3SChris Lattner Type *get(Type *SrcTy); 73b1ed91f3SChris Lattner 74b1ed91f3SChris Lattner FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));} 75b1ed91f3SChris Lattner 7618c89411SRafael Espindola /// Dump out the type map for debugging purposes. 77b6af2f36SBill Wendling void dump() const { 78b6af2f36SBill Wendling for (DenseMap<Type*, Type*>::const_iterator 79b6af2f36SBill Wendling I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) { 80b6af2f36SBill Wendling dbgs() << "TypeMap: "; 81c0087f36SJustin Bogner I->first->print(dbgs()); 82b6af2f36SBill Wendling dbgs() << " => "; 83c0087f36SJustin Bogner I->second->print(dbgs()); 84b6af2f36SBill Wendling dbgs() << '\n'; 85b6af2f36SBill Wendling } 86b6af2f36SBill Wendling } 87b6af2f36SBill Wendling 88b1ed91f3SChris Lattner private: 89b1ed91f3SChris Lattner Type *getImpl(Type *T); 9018c89411SRafael Espindola /// Implement the ValueMapTypeRemapper interface. 918548299aSCraig Topper Type *remapType(Type *SrcTy) override { 92b1ed91f3SChris Lattner return get(SrcTy); 93b1ed91f3SChris Lattner } 94b1ed91f3SChris Lattner 95b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 96b1ed91f3SChris Lattner }; 97b1ed91f3SChris Lattner } 98b1ed91f3SChris Lattner 99b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 100b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 101b1ed91f3SChris Lattner if (Entry) return; 102b1ed91f3SChris Lattner 103b1ed91f3SChris Lattner if (DstTy == SrcTy) { 104b1ed91f3SChris Lattner Entry = DstTy; 105b1ed91f3SChris Lattner return; 106b1ed91f3SChris Lattner } 107b1ed91f3SChris Lattner 108b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 109b1ed91f3SChris Lattner // mapping between them if so. 110d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy, SrcTy)) { 111b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 112b1ed91f3SChris Lattner // any speculative mappings we've established. 113b1ed91f3SChris Lattner for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i) 114b1ed91f3SChris Lattner MappedTypes.erase(SpeculativeTypes[i]); 115d48b7783SBill Wendling } 116b1ed91f3SChris Lattner SpeculativeTypes.clear(); 117b1ed91f3SChris Lattner } 118b1ed91f3SChris Lattner 11918c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 12018c89411SRafael Espindola /// false if they are not. 121b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 122b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 123b1ed91f3SChris Lattner if (DstTy->getTypeID() != SrcTy->getTypeID()) return false; 124b1ed91f3SChris Lattner 125b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 126b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 127b1ed91f3SChris Lattner if (Entry) 128b1ed91f3SChris Lattner return Entry == DstTy; 129b1ed91f3SChris Lattner 130b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 131b1ed91f3SChris Lattner // non-speculatively. 132b1ed91f3SChris Lattner if (DstTy == SrcTy) { 133b1ed91f3SChris Lattner Entry = DstTy; 134361e513dSReid Spencer return true; 135361e513dSReid Spencer } 136361e513dSReid Spencer 137b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 138361e513dSReid Spencer 139b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 140b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 141b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 142b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 143b1ed91f3SChris Lattner Entry = DstTy; 144b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 145b1ed91f3SChris Lattner return true; 146361e513dSReid Spencer } 147b1ed91f3SChris Lattner 1485e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1495e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 1505e3bd972SChris Lattner // the dest, but fill it in later. This doesn't need to be speculative. If 1515e3bd972SChris Lattner // this is the second (different) type that we're trying to map onto the 1525e3bd972SChris Lattner // same opaque type then we fail. 153b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1545e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 1555e3bd972SChris Lattner if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy))) 1565e3bd972SChris Lattner return false; 1575e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 158b1ed91f3SChris Lattner Entry = DstTy; 159b1ed91f3SChris Lattner return true; 160b1ed91f3SChris Lattner } 161b1ed91f3SChris Lattner } 162b1ed91f3SChris Lattner 163b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 164b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 165b1ed91f3SChris Lattner return false; 166b1ed91f3SChris Lattner 167b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 168b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 169b1ed91f3SChris Lattner return false; // bitwidth disagrees. 170b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 171b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 172b1ed91f3SChris Lattner return false; 173eaf9b762SChris Lattner 174b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 175b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 176b1ed91f3SChris Lattner return false; 177b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 178b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 17944f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 180b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 181b1ed91f3SChris Lattner return false; 182b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 183b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 184b1ed91f3SChris Lattner return false; 185b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1865fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 187361e513dSReid Spencer return false; 188361e513dSReid Spencer } 189361e513dSReid Spencer 190b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 191b1ed91f3SChris Lattner // check the subelements. 192b1ed91f3SChris Lattner Entry = DstTy; 193b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 194eee6f995SChris Lattner 195d48b7783SBill Wendling for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i) 196d48b7783SBill Wendling if (!areTypesIsomorphic(DstTy->getContainedType(i), 197d48b7783SBill Wendling SrcTy->getContainedType(i))) 198b1ed91f3SChris Lattner return false; 199eee6f995SChris Lattner 200b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 201eee6f995SChris Lattner return true; 202eee6f995SChris Lattner } 203eee6f995SChris Lattner 20418c89411SRafael Espindola /// Produce a body for an opaque type in the dest module from a type definition 20518c89411SRafael Espindola /// in the source module. 206b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 207b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 208b1ed91f3SChris Lattner SmallString<16> TmpName; 209eee6f995SChris Lattner 210b1ed91f3SChris Lattner // Note that processing entries in this loop (calling 'get') can add new 2115e3bd972SChris Lattner // entries to the SrcDefinitionsToResolve vector. 2125e3bd972SChris Lattner while (!SrcDefinitionsToResolve.empty()) { 2135e3bd972SChris Lattner StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val(); 214b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 215eee6f995SChris Lattner 216b1ed91f3SChris Lattner // TypeMap is a many-to-one mapping, if there were multiple types that 217b1ed91f3SChris Lattner // provide a body for DstSTy then previous iterations of this loop may have 218b1ed91f3SChris Lattner // already handled it. Just ignore this case. 219b1ed91f3SChris Lattner if (!DstSTy->isOpaque()) continue; 220b1ed91f3SChris Lattner assert(!SrcSTy->isOpaque() && "Not resolving a definition?"); 221b1ed91f3SChris Lattner 222b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 223b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 224b1ed91f3SChris Lattner for (unsigned i = 0, e = Elements.size(); i != e; ++i) 225b1ed91f3SChris Lattner Elements[i] = getImpl(SrcSTy->getElementType(i)); 226b1ed91f3SChris Lattner 227b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 228b1ed91f3SChris Lattner 229b1ed91f3SChris Lattner // If DstSTy has no name or has a longer name than STy, then viciously steal 230b1ed91f3SChris Lattner // STy's name. 231b1ed91f3SChris Lattner if (!SrcSTy->hasName()) continue; 232b1ed91f3SChris Lattner StringRef SrcName = SrcSTy->getName(); 233b1ed91f3SChris Lattner 234b1ed91f3SChris Lattner if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) { 235b1ed91f3SChris Lattner TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end()); 236b1ed91f3SChris Lattner SrcSTy->setName(""); 237b1ed91f3SChris Lattner DstSTy->setName(TmpName.str()); 238b1ed91f3SChris Lattner TmpName.clear(); 239b1ed91f3SChris Lattner } 240b1ed91f3SChris Lattner } 2415e3bd972SChris Lattner 2425e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 243eee6f995SChris Lattner } 244eee6f995SChris Lattner 245b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 246b1ed91f3SChris Lattner Type *Result = getImpl(Ty); 247b1ed91f3SChris Lattner 248b1ed91f3SChris Lattner // If this caused a reference to any struct type, resolve it before returning. 2495e3bd972SChris Lattner if (!SrcDefinitionsToResolve.empty()) 250b1ed91f3SChris Lattner linkDefinedTypeBodies(); 251b1ed91f3SChris Lattner return Result; 252eee6f995SChris Lattner } 253eee6f995SChris Lattner 25418c89411SRafael Espindola /// This is the recursive version of get(). 255b1ed91f3SChris Lattner Type *TypeMapTy::getImpl(Type *Ty) { 256b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 257b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 258b1ed91f3SChris Lattner if (*Entry) return *Entry; 259b1ed91f3SChris Lattner 260b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 261b1ed91f3SChris Lattner // then rebuild the type from inside out. 26244f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 263b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 264b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 265b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 266b1ed91f3SChris Lattner return *Entry = Ty; 267b1ed91f3SChris Lattner 268b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 269b1ed91f3SChris Lattner bool AnyChange = false; 270b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 271b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 272b1ed91f3SChris Lattner for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) { 273b1ed91f3SChris Lattner ElementTypes[i] = getImpl(Ty->getContainedType(i)); 274b1ed91f3SChris Lattner AnyChange |= ElementTypes[i] != Ty->getContainedType(i); 275eee6f995SChris Lattner } 276b1ed91f3SChris Lattner 277b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 278b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 279b1ed91f3SChris Lattner if (*Entry) return *Entry; 280b1ed91f3SChris Lattner 281b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 282b1ed91f3SChris Lattner // as-is. 283b1ed91f3SChris Lattner if (!AnyChange) 284b1ed91f3SChris Lattner return *Entry = Ty; 285b1ed91f3SChris Lattner 286b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 287b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 288a2886c21SCraig Topper default: llvm_unreachable("unknown derived type to remap"); 289b1ed91f3SChris Lattner case Type::ArrayTyID: 290b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 291b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 292b1ed91f3SChris Lattner case Type::VectorTyID: 293b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 294b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 295b1ed91f3SChris Lattner case Type::PointerTyID: 296b1ed91f3SChris Lattner return *Entry = PointerType::get(ElementTypes[0], 297b1ed91f3SChris Lattner cast<PointerType>(Ty)->getAddressSpace()); 298b1ed91f3SChris Lattner case Type::FunctionTyID: 299b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 300717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 301b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 302b1ed91f3SChris Lattner case Type::StructTyID: 303b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 304b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 305b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 306b1ed91f3SChris Lattner } 307b1ed91f3SChris Lattner } 308b1ed91f3SChris Lattner 309b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 310b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 311b1ed91f3SChris Lattner // module has something like: 312b1ed91f3SChris Lattner // %T = type {%T*, i32} 313b1ed91f3SChris Lattner // @GV = global %T* null 314b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 315b1ed91f3SChris Lattner // 316b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 317b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 318b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 319b1ed91f3SChris Lattner // %A = type { i32 } 320b1ed91f3SChris Lattner // and the source module has something like 321b1ed91f3SChris Lattner // %A' = type { i32 } 322b1ed91f3SChris Lattner // %B = type { %A'* } 323b1ed91f3SChris Lattner // @GV = global %B* null 324b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 325b1ed91f3SChris Lattner // pristine "%B" name from the source module. 326b1ed91f3SChris Lattner // 327b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 328b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 329b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 330b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 331b1ed91f3SChris Lattner // it and always rebuild a type here. 332b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 333b1ed91f3SChris Lattner 334b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 335aa9918aaSRafael Espindola if (STy->isOpaque()) { 336aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 337aa9918aaSRafael Espindola // identified structs in the destination module. 338aa9918aaSRafael Espindola DstStructTypesSet.insert(STy); 339b1ed91f3SChris Lattner return *Entry = STy; 340aa9918aaSRafael Espindola } 341b1ed91f3SChris Lattner 342b1ed91f3SChris Lattner // Otherwise we create a new type and resolve its body later. This will be 343b1ed91f3SChris Lattner // resolved by the top level of get(). 3445e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(STy); 3455e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 346aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 347aa9918aaSRafael Espindola // identified structs in the destination module. 348aa9918aaSRafael Espindola DstStructTypesSet.insert(DTy); 3495e3bd972SChris Lattner DstResolvedOpaqueTypes.insert(DTy); 3505e3bd972SChris Lattner return *Entry = DTy; 351b1ed91f3SChris Lattner } 352b1ed91f3SChris Lattner 353b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 354b1ed91f3SChris Lattner // ModuleLinker implementation. 355b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 356b1ed91f3SChris Lattner 357b1ed91f3SChris Lattner namespace { 358f6f121e2SJames Molloy class ModuleLinker; 359f6f121e2SJames Molloy 36018c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 36118c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 36218c89411SRafael Espindola /// few get used. 363f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 364f6f121e2SJames Molloy TypeMapTy &TypeMap; 365f6f121e2SJames Molloy Module *DstM; 366f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions; 367f6f121e2SJames Molloy public: 368f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 369f6f121e2SJames Molloy std::vector<Function*> &LazilyLinkFunctions) : 370f6f121e2SJames Molloy ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 371f6f121e2SJames Molloy LazilyLinkFunctions(LazilyLinkFunctions) { 372f6f121e2SJames Molloy } 373f6f121e2SJames Molloy 3748548299aSCraig Topper Value *materializeValueFor(Value *V) override; 375f6f121e2SJames Molloy }; 376f6f121e2SJames Molloy 377d12b4a33SRafael Espindola namespace { 378d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 379d12b4a33SRafael Espindola const Twine &Msg; 380d12b4a33SRafael Espindola 381d12b4a33SRafael Espindola public: 382d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 383d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 384d12b4a33SRafael Espindola }; 385d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 386d12b4a33SRafael Espindola const Twine &Msg) 387d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 388d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 389d12b4a33SRafael Espindola } 390d12b4a33SRafael Espindola 39118c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the 39218c89411SRafael Espindola /// entrypoint for this file. 393b1ed91f3SChris Lattner class ModuleLinker { 394b1ed91f3SChris Lattner Module *DstM, *SrcM; 395b1ed91f3SChris Lattner 396b1ed91f3SChris Lattner TypeMapTy TypeMap; 397f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 398b1ed91f3SChris Lattner 39918c89411SRafael Espindola /// Mapping of values from what they used to be in Src, to what they are now 40018c89411SRafael Espindola /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 40118c89411SRafael Espindola /// due to the use of Value handles which the Linker doesn't actually need, 40218c89411SRafael Espindola /// but this allows us to reuse the ValueMapper code. 403b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 404b1ed91f3SChris Lattner 405b1ed91f3SChris Lattner struct AppendingVarInfo { 406b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 407*3e8bc6a8SRafael Espindola const Constant *DstInit; // Old initializer from dest module. 408*3e8bc6a8SRafael Espindola const Constant *SrcInit; // Old initializer from src module. 409b1ed91f3SChris Lattner }; 410b1ed91f3SChris Lattner 411b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 412b1ed91f3SChris Lattner 413cbb91408STanya Lattner // Set of items not to link in from source. 414cbb91408STanya Lattner SmallPtrSet<const Value*, 16> DoNotLinkFromSource; 415cbb91408STanya Lattner 4160a48b877STanya Lattner // Vector of functions to lazily link in. 417fa228782SBill Wendling std::vector<Function*> LazilyLinkFunctions; 4180a48b877STanya Lattner 4194160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 4204160f5d3SRafael Espindola 421b1ed91f3SChris Lattner public: 4229f8eff31SRafael Espindola ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, 4234160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 424f6f121e2SJames Molloy : DstM(dstM), SrcM(srcM), TypeMap(Set), 4259f8eff31SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), 4264160f5d3SRafael Espindola DiagnosticHandler(DiagnosticHandler) {} 427b1ed91f3SChris Lattner 428b1ed91f3SChris Lattner bool run(); 429b1ed91f3SChris Lattner 430b1ed91f3SChris Lattner private: 431d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 432d12b4a33SRafael Espindola const GlobalValue &Src); 433dbb0bd1aSRafael Espindola 434d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 435b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 4364160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 437b1ed91f3SChris Lattner return true; 438b1ed91f3SChris Lattner } 439b1ed91f3SChris Lattner 440d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 4414160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 442d12b4a33SRafael Espindola } 443d12b4a33SRafael Espindola 444dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 445dad0a645SDavid Majnemer const GlobalVariable *&GVar); 446dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 447dad0a645SDavid Majnemer Comdat::SelectionKind Src, 448dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 449dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 450dad0a645SDavid Majnemer bool &LinkFromSrc); 451dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 452dad0a645SDavid Majnemer ComdatsChosen; 453dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 454dad0a645SDavid Majnemer bool &LinkFromSrc); 455dad0a645SDavid Majnemer 45618c89411SRafael Espindola /// This analyzes the two global values and determines what the result will 45718c89411SRafael Espindola /// look like in the destination module. 458b1ed91f3SChris Lattner bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 45923f8d64bSRafael Espindola GlobalValue::LinkageTypes <, 46023f8d64bSRafael Espindola GlobalValue::VisibilityTypes &Vis, 46123f8d64bSRafael Espindola bool &LinkFromSrc); 462b1ed91f3SChris Lattner 46318c89411SRafael Espindola /// Given a global in the source module, return the global in the 46418c89411SRafael Espindola /// destination module that is being linked to, if any. 465*3e8bc6a8SRafael Espindola GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 466b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 467b1ed91f3SChris Lattner // there is no name match-up going on. 468b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4692617dcceSCraig Topper return nullptr; 470b1ed91f3SChris Lattner 471b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 472b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 4732617dcceSCraig Topper if (!DGV) return nullptr; 474b1ed91f3SChris Lattner 475b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 476b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 477b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4782617dcceSCraig Topper return nullptr; 479b1ed91f3SChris Lattner 480b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 481b1ed91f3SChris Lattner return DGV; 482b1ed91f3SChris Lattner } 483b1ed91f3SChris Lattner 484b1ed91f3SChris Lattner void computeTypeMapping(); 485b1ed91f3SChris Lattner 48609d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 48709d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 48809d84addSDuncan P. N. Exon Smith 489*3e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 490*3e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 491*3e8bc6a8SRafael Espindola bool linkGlobalProto(const GlobalVariable *SrcGV); 492b1ed91f3SChris Lattner bool linkFunctionProto(Function *SrcF); 493b1ed91f3SChris Lattner bool linkAliasProto(GlobalAlias *SrcA); 49466f02413SBill Wendling bool linkModuleFlagsMetadata(); 495b1ed91f3SChris Lattner 496b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 497b1ed91f3SChris Lattner void linkGlobalInits(); 498b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 499b1ed91f3SChris Lattner void linkAliasBodies(); 500b1ed91f3SChris Lattner void linkNamedMDNodes(); 501eee6f995SChris Lattner }; 502d48b7783SBill Wendling } 503d48b7783SBill Wendling 50418c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 50518c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 50618c89411SRafael Espindola /// to force this back. 507b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 508b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 509b1ed91f3SChris Lattner // there is nothing for us to do. 510b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 511b1ed91f3SChris Lattner return; 512b1ed91f3SChris Lattner 513b1ed91f3SChris Lattner Module *M = GV->getParent(); 514361e513dSReid Spencer 515361e513dSReid Spencer // If there is a conflict, rename the conflict. 516b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5172a8d2e0eSChris Lattner GV->takeName(ConflictGV); 518361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 519b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5202a8d2e0eSChris Lattner } else { 5212a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5223aaaa0b2SReid Spencer } 5233aaaa0b2SReid Spencer } 5243aaaa0b2SReid Spencer 52518c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 52618c89411SRafael Espindola /// from the SrcGV to the DestGV. 527b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 528dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 52999e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 530a7d9c69cSRafael Espindola unsigned Alignment; 53199e05cf1SRafael Espindola if (DestGO) 53299e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 533a7d9c69cSRafael Espindola 534dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 535a7d9c69cSRafael Espindola 53699e05cf1SRafael Espindola if (DestGO) 53799e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 538b1ed91f3SChris Lattner 539b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 540361e513dSReid Spencer } 541361e513dSReid Spencer 54223f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 54323f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 54423f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 54523f8d64bSRafael Espindola return false; 54623f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 54723f8d64bSRafael Espindola return true; 54823f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 54923f8d64bSRafael Espindola return false; 55023f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 55123f8d64bSRafael Espindola return true; 55223f8d64bSRafael Espindola return false; 55323f8d64bSRafael Espindola } 55423f8d64bSRafael Espindola 555f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 556f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 557f6f121e2SJames Molloy if (!SF) 5582617dcceSCraig Topper return nullptr; 559f6f121e2SJames Molloy 560f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 561f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 562f6f121e2SJames Molloy copyGVAttributes(DF, SF); 563f6f121e2SJames Molloy 5643931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5653931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5663931c28bSRafael Espindola DF->setComdat(DC); 5673931c28bSRafael Espindola } 5683931c28bSRafael Espindola 569f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 570f6f121e2SJames Molloy return DF; 571f6f121e2SJames Molloy } 572f6f121e2SJames Molloy 573dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 574dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 575dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 576dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 577dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 578dad0a645SDavid Majnemer if (!GVal) 579dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 580dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 581dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 582dad0a645SDavid Majnemer } 583dad0a645SDavid Majnemer 584dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 585dad0a645SDavid Majnemer if (!GVar) 586dad0a645SDavid Majnemer return emitError( 587dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 588dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 589dad0a645SDavid Majnemer 590dad0a645SDavid Majnemer return false; 591dad0a645SDavid Majnemer } 592dad0a645SDavid Majnemer 593dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 594dad0a645SDavid Majnemer Comdat::SelectionKind Src, 595dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 596dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 597dad0a645SDavid Majnemer bool &LinkFromSrc) { 598dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 599dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 600dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 601dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 602dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 603dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 604dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 605dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 606dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 607dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 608dad0a645SDavid Majnemer else 609dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 610dad0a645SDavid Majnemer } else if (Src == Dst) { 611dad0a645SDavid Majnemer Result = Dst; 612dad0a645SDavid Majnemer } else { 613dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 614dad0a645SDavid Majnemer "': invalid selection kinds!"); 615dad0a645SDavid Majnemer } 616dad0a645SDavid Majnemer 617dad0a645SDavid Majnemer switch (Result) { 618dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 619dad0a645SDavid Majnemer // Go with Dst. 620dad0a645SDavid Majnemer LinkFromSrc = false; 621dad0a645SDavid Majnemer break; 622dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 623dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 624dad0a645SDavid Majnemer "': noduplicates has been violated!"); 625dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 626dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 627dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 628dad0a645SDavid Majnemer const GlobalVariable *DstGV; 629dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 630dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 631dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 632dad0a645SDavid Majnemer return true; 633dad0a645SDavid Majnemer 634dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 635dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 636dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 637dad0a645SDavid Majnemer return emitError( 638dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 639dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 640dad0a645SDavid Majnemer } 641dad0a645SDavid Majnemer uint64_t DstSize = 642dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 643dad0a645SDavid Majnemer uint64_t SrcSize = 644dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 645dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 646dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 647dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 648dad0a645SDavid Majnemer "': ExactMatch violated!"); 649dad0a645SDavid Majnemer LinkFromSrc = false; 650dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 651dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 652dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 653dad0a645SDavid Majnemer if (SrcSize != DstSize) 654dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 655dad0a645SDavid Majnemer "': SameSize violated!"); 656dad0a645SDavid Majnemer LinkFromSrc = false; 657dad0a645SDavid Majnemer } else { 658dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 659dad0a645SDavid Majnemer } 660dad0a645SDavid Majnemer break; 661dad0a645SDavid Majnemer } 662dad0a645SDavid Majnemer } 663dad0a645SDavid Majnemer 664dad0a645SDavid Majnemer return false; 665dad0a645SDavid Majnemer } 666dad0a645SDavid Majnemer 667dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 668dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 669dad0a645SDavid Majnemer bool &LinkFromSrc) { 670b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 671dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 672dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 673dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6742ef3f299SRafael Espindola 675b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 676b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 677b16196a3SRafael Espindola LinkFromSrc = true; 678b16196a3SRafael Espindola Result = SSK; 6792ef3f299SRafael Espindola return false; 680b16196a3SRafael Espindola } 6812ef3f299SRafael Espindola 682dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 683dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6842ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6852ef3f299SRafael Espindola LinkFromSrc); 686dad0a645SDavid Majnemer } 687f6f121e2SJames Molloy 688d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 689d12b4a33SRafael Espindola const GlobalValue &Dest, 690dbb0bd1aSRafael Espindola const GlobalValue &Src) { 691d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 692d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 693dbb0bd1aSRafael Espindola 694dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 695dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 696dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 697d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 698dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 699d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 700d12b4a33SRafael Espindola return false; 701d12b4a33SRafael Espindola } 702dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 703d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 704d12b4a33SRafael Espindola return false; 705dbb0bd1aSRafael Espindola } 706dbb0bd1aSRafael Espindola 707d12b4a33SRafael Espindola if (DestIsDeclaration) { 708dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 709d12b4a33SRafael Espindola LinkFromSrc = true; 710d12b4a33SRafael Espindola return false; 711d12b4a33SRafael Espindola } 712dbb0bd1aSRafael Espindola 7130910605aSRafael Espindola if (Src.hasCommonLinkage()) { 714d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 715d12b4a33SRafael Espindola LinkFromSrc = true; 7160910605aSRafael Espindola return false; 717d12b4a33SRafael Espindola } 718d12b4a33SRafael Espindola 719d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 720d12b4a33SRafael Espindola LinkFromSrc = false; 721d12b4a33SRafael Espindola return false; 722d12b4a33SRafael Espindola } 7230910605aSRafael Espindola 7240ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7250ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7260ae225b6SRafael Espindola 7270910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7280910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 729d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 730d12b4a33SRafael Espindola return false; 7310910605aSRafael Espindola } 7320910605aSRafael Espindola 733dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 734dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 735dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7360910605aSRafael Espindola 737d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 738d12b4a33SRafael Espindola LinkFromSrc = true; 739d12b4a33SRafael Espindola return false; 740d12b4a33SRafael Espindola } 741dbb0bd1aSRafael Espindola 742d12b4a33SRafael Espindola LinkFromSrc = false; 7430910605aSRafael Espindola return false; 744dbb0bd1aSRafael Espindola } 745dbb0bd1aSRafael Espindola 746dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 747dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 748d12b4a33SRafael Espindola LinkFromSrc = true; 749d12b4a33SRafael Espindola return false; 750dbb0bd1aSRafael Espindola } 751dbb0bd1aSRafael Espindola 752dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 753dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 754dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 755dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 756dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 757dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 758dbb0bd1aSRafael Espindola } 759dbb0bd1aSRafael Espindola 76083a7ddbcSRafael Espindola /// This analyzes the two global values and determines what the result will look 76183a7ddbcSRafael Espindola /// like in the destination module. In particular, it computes the resultant 76283a7ddbcSRafael Espindola /// linkage type and visibility, computes whether the global in the source 76383a7ddbcSRafael Espindola /// should be copied over to the destination (replacing the existing one), and 76483a7ddbcSRafael Espindola /// computes whether this linkage is an error or not. 765b1ed91f3SChris Lattner bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src, 766b1ed91f3SChris Lattner GlobalValue::LinkageTypes <, 76723f8d64bSRafael Espindola GlobalValue::VisibilityTypes &Vis, 768b1ed91f3SChris Lattner bool &LinkFromSrc) { 769b1ed91f3SChris Lattner assert(Dest && "Must have two globals being queried"); 770b1ed91f3SChris Lattner assert(!Src->hasLocalLinkage() && 771fc61de39SChris Lattner "If Src has internal linkage, Dest shouldn't be set!"); 772b1ed91f3SChris Lattner 773d12b4a33SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *Dest, *Src)) 774dbb0bd1aSRafael Espindola return true; 775b1ed91f3SChris Lattner 776dbb0bd1aSRafael Espindola if (LinkFromSrc) 777d61d39ecSAnton Korobeynikov LT = Src->getLinkage(); 778dbb0bd1aSRafael Espindola else 779c83c8d4eSRafael Espindola LT = Dest->getLinkage(); 78031fc4f95SAnton Korobeynikov 78123f8d64bSRafael Espindola // Compute the visibility. We follow the rules in the System V Application 78223f8d64bSRafael Espindola // Binary Interface. 783b2becfdbSDuncan P. N. Exon Smith assert(!GlobalValue::isLocalLinkage(LT) && 784b2becfdbSDuncan P. N. Exon Smith "Symbols with local linkage should not be merged"); 78523f8d64bSRafael Espindola Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ? 78623f8d64bSRafael Espindola Dest->getVisibility() : Src->getVisibility(); 787fc61de39SChris Lattner return false; 788fc61de39SChris Lattner } 789361e513dSReid Spencer 79018c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 79118c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 79218c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 79318c89411SRafael Espindola /// LLVMContext. 794b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 795b1ed91f3SChris Lattner // Incorporate globals. 796b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 797b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 798b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(I); 7992617dcceSCraig Topper if (!DGV) continue; 800b1ed91f3SChris Lattner 801b1ed91f3SChris Lattner if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) { 802b1ed91f3SChris Lattner TypeMap.addTypeMapping(DGV->getType(), I->getType()); 803b1ed91f3SChris Lattner continue; 8045c310be0SDevang Patel } 8055c310be0SDevang Patel 806b1ed91f3SChris Lattner // Unify the element type of appending arrays. 807b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 808b1ed91f3SChris Lattner ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType()); 809b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 810b1ed91f3SChris Lattner } 81134fc5a0eSChris Lattner 812b1ed91f3SChris Lattner // Incorporate functions. 813b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) { 814b1ed91f3SChris Lattner if (GlobalValue *DGV = getLinkedToGlobal(I)) 815b1ed91f3SChris Lattner TypeMap.addTypeMapping(DGV->getType(), I->getType()); 816b1ed91f3SChris Lattner } 817e79f4c77SAnton Korobeynikov 818d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 819d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 8202b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 8212b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 8228555a37cSBill Wendling TypeFinder SrcStructTypes; 8238555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 8242b3f61afSBill Wendling SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 8252b3f61afSBill Wendling SrcStructTypes.end()); 8262b3f61afSBill Wendling 8272b3f61afSBill Wendling for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 8282b3f61afSBill Wendling StructType *ST = SrcStructTypes[i]; 8292b3f61afSBill Wendling if (!ST->hasName()) continue; 8302b3f61afSBill Wendling 8312b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 832d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 833d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 83483c74e9fSGuy Benyei ST->getName().back() == '.' || 83583c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 836d48b7783SBill Wendling continue; 8372b3f61afSBill Wendling 8382b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 839d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 8402b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8418737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8428737480dSBill Wendling // actually used in the destination module. This can happen in situations 8438737480dSBill Wendling // like this: 8448737480dSBill Wendling // 8458737480dSBill Wendling // Module A Module B 8468737480dSBill Wendling // -------- -------- 8478737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8488737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8498737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8508737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8518737480dSBill Wendling // 8528737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8538737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8548737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8558737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8568737480dSBill Wendling // variables using one type and some using the other. 857aa9918aaSRafael Espindola if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST)) 8582b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8592b3f61afSBill Wendling } 8602b3f61afSBill Wendling 861b1ed91f3SChris Lattner // Don't bother incorporating aliases, they aren't generally typed well. 862361e513dSReid Spencer 863b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 864b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 865b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 866b1ed91f3SChris Lattner } 867c08e7a00SChris Lattner 86809d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 86909d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 87009d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 87109d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 87209d84addSDuncan P. N. Exon Smith 87309d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 87409d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 87509d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 87609d84addSDuncan P. N. Exon Smith VoidPtrTy}; 87709d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 87809d84addSDuncan P. N. Exon Smith 87909d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 88009d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 88109d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 88209d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 88309d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 88409d84addSDuncan P. N. Exon Smith return; 88509d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 88609d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 88709d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 88809d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 88909d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 89009d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 89109d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 89209d84addSDuncan P. N. Exon Smith } 89309d84addSDuncan P. N. Exon Smith } 89409d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 89509d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 89609d84addSDuncan P. N. Exon Smith 89709d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 89809d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 89909d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 90009d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 90109d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 90209d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 90309d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 90409d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 90509d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 90609d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 90709d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 90809d84addSDuncan P. N. Exon Smith } 90909d84addSDuncan P. N. Exon Smith 91009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 91109d84addSDuncan P. N. Exon Smith // Look for the global arrays. 91209d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 91309d84addSDuncan P. N. Exon Smith if (!DstGV) 91409d84addSDuncan P. N. Exon Smith return; 91509d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 91609d84addSDuncan P. N. Exon Smith if (!SrcGV) 91709d84addSDuncan P. N. Exon Smith return; 91809d84addSDuncan P. N. Exon Smith 91909d84addSDuncan P. N. Exon Smith // Check if the types already match. 92009d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 92109d84addSDuncan P. N. Exon Smith auto *SrcTy = 92209d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 92309d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 92409d84addSDuncan P. N. Exon Smith return; 92509d84addSDuncan P. N. Exon Smith 92609d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 92709d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 92809d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 92909d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 93009d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 93109d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 93209d84addSDuncan P. N. Exon Smith return; 93309d84addSDuncan P. N. Exon Smith } 93409d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 93509d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 93609d84addSDuncan P. N. Exon Smith 93709d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 93809d84addSDuncan P. N. Exon Smith } 93909d84addSDuncan P. N. Exon Smith 94009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 94109d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 94209d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 94309d84addSDuncan P. N. Exon Smith } 94409d84addSDuncan P. N. Exon Smith 94518c89411SRafael Espindola /// If there were any appending global variables, link them together now. 94618c89411SRafael Espindola /// Return true on error. 947b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 948*3e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 949d48b7783SBill Wendling 950b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 951b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 952b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 953361e513dSReid Spencer 954b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 955b1ed91f3SChris Lattner ArrayType *SrcTy = 956b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 957b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 958b1ed91f3SChris Lattner 959b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 960b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 961b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 962b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 963b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 964b1ed91f3SChris Lattner 965b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 966b1ed91f3SChris Lattner return emitError( 967b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 968b1ed91f3SChris Lattner 969b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 970b1ed91f3SChris Lattner return emitError( 971b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 972b1ed91f3SChris Lattner 973fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 974fac3a018SRafael Espindola return emitError( 975fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 976fac3a018SRafael Espindola 97764c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 978b1ed91f3SChris Lattner return emitError( 979b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 980b1ed91f3SChris Lattner 981b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 982b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 983b1ed91f3SChris Lattner 984b1ed91f3SChris Lattner // Create the new global variable. 985b1ed91f3SChris Lattner GlobalVariable *NG = 986b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9872617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 988cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 989b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 990b1ed91f3SChris Lattner 991b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 992b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 993b1ed91f3SChris Lattner 994b1ed91f3SChris Lattner AppendingVarInfo AVI; 995b1ed91f3SChris Lattner AVI.NewGV = NG; 996b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 997b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 998b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 999b1ed91f3SChris Lattner 1000b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 1001b1ed91f3SChris Lattner // global. 1002b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 1003b1ed91f3SChris Lattner 1004b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 1005b1ed91f3SChris Lattner DstGV->eraseFromParent(); 1006b1ed91f3SChris Lattner 1007cbb91408STanya Lattner // Track the source variable so we don't try to link it. 1008cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 1009cbb91408STanya Lattner 1010b1ed91f3SChris Lattner return false; 1011b1ed91f3SChris Lattner } 1012b1ed91f3SChris Lattner 101318c89411SRafael Espindola /// Loop through the global variables in the src module and merge them into the 101418c89411SRafael Espindola /// dest module. 1015*3e8bc6a8SRafael Espindola bool ModuleLinker::linkGlobalProto(const GlobalVariable *SGV) { 1016b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 101723f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 1018d4885daeSRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 1019fe3842cdSRafael Espindola unsigned Alignment = SGV->getAlignment(); 1020b1ed91f3SChris Lattner 1021dad0a645SDavid Majnemer bool LinkFromSrc = false; 1022dad0a645SDavid Majnemer Comdat *DC = nullptr; 1023dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 1024dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1025dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1026dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1027dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1028dad0a645SDavid Majnemer } 1029dad0a645SDavid Majnemer 1030b1ed91f3SChris Lattner if (DGV) { 1031dad0a645SDavid Majnemer if (!DC) { 1032b1ed91f3SChris Lattner // Concatenation of appending linkage variables is magic and handled later. 1033b1ed91f3SChris Lattner if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage()) 1034b1ed91f3SChris Lattner return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV); 1035b1ed91f3SChris Lattner 1036b1ed91f3SChris Lattner // Determine whether linkage of these two globals follows the source 1037b1ed91f3SChris Lattner // module's definition or the destination module's definition. 10381b9633d7SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 103923f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 104023f8d64bSRafael Espindola if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc)) 1041fc61de39SChris Lattner return true; 104223f8d64bSRafael Espindola NewVisibility = NV; 1043fd9a9415SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1044fe3842cdSRafael Espindola if (DGV->hasCommonLinkage() && SGV->hasCommonLinkage()) 1045fe3842cdSRafael Espindola Alignment = std::max(Alignment, DGV->getAlignment()); 1046fe3842cdSRafael Espindola else if (!LinkFromSrc) 1047fe3842cdSRafael Espindola Alignment = DGV->getAlignment(); 1048361e513dSReid Spencer 1049b1ed91f3SChris Lattner // If we're not linking from the source, then keep the definition that we 1050b1ed91f3SChris Lattner // have. 1051b1ed91f3SChris Lattner if (!LinkFromSrc) { 105234fc5a0eSChris Lattner // Special case for const propagation. 1053fe3842cdSRafael Espindola if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) { 1054fe3842cdSRafael Espindola DGVar->setAlignment(Alignment); 1055fe3842cdSRafael Espindola 1056d1e64b1eSRafael Espindola if (DGVar->isDeclaration() && !SGV->isConstant()) 1057d1e64b1eSRafael Espindola DGVar->setConstant(false); 1058fe3842cdSRafael Espindola } 105934fc5a0eSChris Lattner 1060d4885daeSRafael Espindola // Set calculated linkage, visibility and unnamed_addr. 106134fc5a0eSChris Lattner DGV->setLinkage(NewLinkage); 106223f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 1063d4885daeSRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1064dad0a645SDavid Majnemer } 1065dad0a645SDavid Majnemer } 106634fc5a0eSChris Lattner 1067dad0a645SDavid Majnemer if (!LinkFromSrc) { 1068b1ed91f3SChris Lattner // Make sure to remember this mapping. 1069b1ed91f3SChris Lattner ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType())); 1070b1ed91f3SChris Lattner 1071cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 1072cbb91408STanya Lattner // processing global initializers. 1073cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1074cbb91408STanya Lattner 1075b1ed91f3SChris Lattner return false; 1076361e513dSReid Spencer } 1077b1ed91f3SChris Lattner } 1078b1ed91f3SChris Lattner 1079dad0a645SDavid Majnemer // If the Comdat this variable was inside of wasn't selected, skip it. 1080dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1081dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SGV); 1082dad0a645SDavid Majnemer return false; 1083dad0a645SDavid Majnemer } 1084dad0a645SDavid Majnemer 1085b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1086b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1087b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1088b1ed91f3SChris Lattner GlobalVariable *NewDGV = 1089b1ed91f3SChris Lattner new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()), 10902617dcceSCraig Topper SGV->isConstant(), SGV->getLinkage(), /*init*/nullptr, 10912617dcceSCraig Topper SGV->getName(), /*insertbefore*/nullptr, 1092cbe34b4cSHans Wennborg SGV->getThreadLocalMode(), 1093b1ed91f3SChris Lattner SGV->getType()->getAddressSpace()); 1094b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 1095b6af2f36SBill Wendling copyGVAttributes(NewDGV, SGV); 1096fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 109723f8d64bSRafael Espindola if (NewVisibility) 109823f8d64bSRafael Espindola NewDGV->setVisibility(*NewVisibility); 1099d4885daeSRafael Espindola NewDGV->setUnnamedAddr(HasUnnamedAddr); 1100b1ed91f3SChris Lattner 1101dad0a645SDavid Majnemer if (DC) 1102dad0a645SDavid Majnemer NewDGV->setComdat(DC); 1103dad0a645SDavid Majnemer 1104b1ed91f3SChris Lattner if (DGV) { 1105b1ed91f3SChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType())); 1106b1ed91f3SChris Lattner DGV->eraseFromParent(); 1107b1ed91f3SChris Lattner } 1108b1ed91f3SChris Lattner 1109b1ed91f3SChris Lattner // Make sure to remember this mapping. 1110b1ed91f3SChris Lattner ValueMap[SGV] = NewDGV; 1111361e513dSReid Spencer return false; 1112361e513dSReid Spencer } 1113361e513dSReid Spencer 111418c89411SRafael Espindola /// Link the function in the source module into the destination module if 111518c89411SRafael Espindola /// needed, setting up mapping information. 1116b1ed91f3SChris Lattner bool ModuleLinker::linkFunctionProto(Function *SF) { 1117b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SF); 111823f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 1119fd9a9415SRafael Espindola bool HasUnnamedAddr = SF->hasUnnamedAddr(); 1120dac5fa94SAnton Korobeynikov 11210ead7a50SChris Lattner bool LinkFromSrc = false; 1122dad0a645SDavid Majnemer Comdat *DC = nullptr; 1123dad0a645SDavid Majnemer if (const Comdat *SC = SF->getComdat()) { 1124dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1125dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1126dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1127dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1128dad0a645SDavid Majnemer } 1129dad0a645SDavid Majnemer 1130dad0a645SDavid Majnemer if (DGV) { 1131dad0a645SDavid Majnemer if (!DC) { 1132dad0a645SDavid Majnemer GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 113323f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 113423f8d64bSRafael Espindola if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc)) 11350ead7a50SChris Lattner return true; 113623f8d64bSRafael Espindola NewVisibility = NV; 1137fd9a9415SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 11380ead7a50SChris Lattner 1139b1ed91f3SChris Lattner if (!LinkFromSrc) { 11400ead7a50SChris Lattner // Set calculated linkage 11410ead7a50SChris Lattner DGV->setLinkage(NewLinkage); 114223f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 1143fd9a9415SRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1144dad0a645SDavid Majnemer } 1145dad0a645SDavid Majnemer } 114677e8ac4dSChris Lattner 1147dad0a645SDavid Majnemer if (!LinkFromSrc) { 11480ead7a50SChris Lattner // Make sure to remember this mapping. 1149b1ed91f3SChris Lattner ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType())); 1150b1ed91f3SChris Lattner 1151cbb91408STanya Lattner // Track the function from the source module so we don't attempt to remap 1152cbb91408STanya Lattner // it. 1153cbb91408STanya Lattner DoNotLinkFromSource.insert(SF); 1154cbb91408STanya Lattner 1155b1ed91f3SChris Lattner return false; 1156361e513dSReid Spencer } 1157b1ed91f3SChris Lattner } 1158b1ed91f3SChris Lattner 1159f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1160f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1161f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1162f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1163f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1164f6f121e2SJames Molloy return false; 1165f6f121e2SJames Molloy } 1166f6f121e2SJames Molloy 1167dad0a645SDavid Majnemer // If the Comdat this function was inside of wasn't selected, skip it. 1168dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1169dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SF); 1170dad0a645SDavid Majnemer return false; 1171dad0a645SDavid Majnemer } 1172dad0a645SDavid Majnemer 1173b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1174b1ed91f3SChris Lattner // bring SF over. 1175b1ed91f3SChris Lattner Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()), 1176b1ed91f3SChris Lattner SF->getLinkage(), SF->getName(), DstM); 1177b6af2f36SBill Wendling copyGVAttributes(NewDF, SF); 117823f8d64bSRafael Espindola if (NewVisibility) 117923f8d64bSRafael Espindola NewDF->setVisibility(*NewVisibility); 1180fd9a9415SRafael Espindola NewDF->setUnnamedAddr(HasUnnamedAddr); 1181b1ed91f3SChris Lattner 1182dad0a645SDavid Majnemer if (DC) 1183dad0a645SDavid Majnemer NewDF->setComdat(DC); 1184dad0a645SDavid Majnemer 1185b1ed91f3SChris Lattner if (DGV) { 1186b1ed91f3SChris Lattner // Any uses of DF need to change to NewDF, with cast. 1187b1ed91f3SChris Lattner DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType())); 1188b1ed91f3SChris Lattner DGV->eraseFromParent(); 1189b1ed91f3SChris Lattner } 1190b1ed91f3SChris Lattner 1191b1ed91f3SChris Lattner ValueMap[SF] = NewDF; 1192361e513dSReid Spencer return false; 1193361e513dSReid Spencer } 1194361e513dSReid Spencer 119518c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 1196b1ed91f3SChris Lattner bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) { 1197b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGA); 119823f8d64bSRafael Espindola llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility; 119942a4c9f9SRafael Espindola bool HasUnnamedAddr = SGA->hasUnnamedAddr(); 1200b1ed91f3SChris Lattner 1201dad0a645SDavid Majnemer bool LinkFromSrc = false; 1202dad0a645SDavid Majnemer Comdat *DC = nullptr; 1203dad0a645SDavid Majnemer if (const Comdat *SC = SGA->getComdat()) { 1204dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1205dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 1206dad0a645SDavid Majnemer DC = DstM->getOrInsertComdat(SC->getName()); 1207dad0a645SDavid Majnemer DC->setSelectionKind(SK); 1208dad0a645SDavid Majnemer } 1209dad0a645SDavid Majnemer 1210b1ed91f3SChris Lattner if (DGV) { 1211dad0a645SDavid Majnemer if (!DC) { 1212b1ed91f3SChris Lattner GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage; 121323f8d64bSRafael Espindola GlobalValue::VisibilityTypes NV; 121423f8d64bSRafael Espindola if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc)) 1215b1ed91f3SChris Lattner return true; 121623f8d64bSRafael Espindola NewVisibility = NV; 121742a4c9f9SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1218b1ed91f3SChris Lattner 1219b1ed91f3SChris Lattner if (!LinkFromSrc) { 1220b1ed91f3SChris Lattner // Set calculated linkage. 1221b1ed91f3SChris Lattner DGV->setLinkage(NewLinkage); 122223f8d64bSRafael Espindola DGV->setVisibility(*NewVisibility); 122342a4c9f9SRafael Espindola DGV->setUnnamedAddr(HasUnnamedAddr); 1224dad0a645SDavid Majnemer } 1225dad0a645SDavid Majnemer } 1226b1ed91f3SChris Lattner 1227dad0a645SDavid Majnemer if (!LinkFromSrc) { 1228b1ed91f3SChris Lattner // Make sure to remember this mapping. 1229b1ed91f3SChris Lattner ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType())); 1230b1ed91f3SChris Lattner 1231cbb91408STanya Lattner // Track the alias from the source module so we don't attempt to remap it. 1232cbb91408STanya Lattner DoNotLinkFromSource.insert(SGA); 1233cbb91408STanya Lattner 1234b1ed91f3SChris Lattner return false; 1235b1ed91f3SChris Lattner } 1236b1ed91f3SChris Lattner } 1237b1ed91f3SChris Lattner 1238dad0a645SDavid Majnemer // If the Comdat this alias was inside of wasn't selected, skip it. 1239dad0a645SDavid Majnemer if (DC && !DGV && !LinkFromSrc) { 1240dad0a645SDavid Majnemer DoNotLinkFromSource.insert(SGA); 1241dad0a645SDavid Majnemer return false; 1242dad0a645SDavid Majnemer } 1243dad0a645SDavid Majnemer 1244b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1245b1ed91f3SChris Lattner // bring over SGA. 12464fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1247f1bedd37SRafael Espindola auto *NewDA = 1248f1bedd37SRafael Espindola GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 124983705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1250b6af2f36SBill Wendling copyGVAttributes(NewDA, SGA); 125123f8d64bSRafael Espindola if (NewVisibility) 125223f8d64bSRafael Espindola NewDA->setVisibility(*NewVisibility); 125342a4c9f9SRafael Espindola NewDA->setUnnamedAddr(HasUnnamedAddr); 1254b1ed91f3SChris Lattner 125564c1e180SRafael Espindola if (DGV) { 125664c1e180SRafael Espindola // Any uses of DGV need to change to NewDA, with cast. 125764c1e180SRafael Espindola DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType())); 125864c1e180SRafael Espindola DGV->eraseFromParent(); 125964c1e180SRafael Espindola } 1260b1ed91f3SChris Lattner 1261b1ed91f3SChris Lattner ValueMap[SGA] = NewDA; 1262b1ed91f3SChris Lattner return false; 1263b1ed91f3SChris Lattner } 1264b1ed91f3SChris Lattner 1265*3e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 1266*3e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 12676705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 126800245f42SChris Lattner 12696705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 12706705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 127100245f42SChris Lattner } 127200245f42SChris Lattner 1273b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1274b1ed91f3SChris Lattner // Merge the initializer. 1275d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1276d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1277b1ed91f3SChris Lattner 1278d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1279d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 128000245f42SChris Lattner 1281b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1282d31dc048SRafael Espindola 1283d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1284d31dc048SRafael Espindola bool IsNewStructor = 1285d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1286d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1287d31dc048SRafael Espindola 1288d31dc048SRafael Espindola for (auto *V : SrcElements) { 1289d31dc048SRafael Espindola if (IsNewStructor) { 1290d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1291d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1292d31dc048SRafael Espindola continue; 1293d31dc048SRafael Espindola } 1294d31dc048SRafael Espindola DstElements.push_back( 1295d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1296d31dc048SRafael Espindola } 1297d31dc048SRafael Espindola if (IsNewStructor) { 1298d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1299d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1300d31dc048SRafael Espindola } 1301d31dc048SRafael Espindola 1302d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1303b1ed91f3SChris Lattner } 1304b1ed91f3SChris Lattner 130518c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 130618c89411SRafael Espindola /// referenced are in Dest. 1307b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1308b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1309b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1310b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1311cbb91408STanya Lattner 1312cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1313cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1314b1ed91f3SChris Lattner 1315b1ed91f3SChris Lattner // Grab destination global variable. 1316b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1317b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1318b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1319f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1320b1ed91f3SChris Lattner } 1321b1ed91f3SChris Lattner } 1322b1ed91f3SChris Lattner 132318c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 132418c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 132518c89411SRafael Espindola /// that Src is not. 1326b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1327b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1328361e513dSReid Spencer 13297391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1330b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1331531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1332361e513dSReid Spencer I != E; ++I, ++DI) { 1333b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1334361e513dSReid Spencer 1335b1ed91f3SChris Lattner // Add a mapping to our mapping. 133666a6271cSAnton Korobeynikov ValueMap[I] = DI; 1337361e513dSReid Spencer } 1338361e513dSReid Spencer 13392f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1340b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1341361e513dSReid Spencer 1342361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1343361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1344361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 134543f8d164SChris Lattner // functions and patch them up to point to the local versions. 1346b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 134743f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 13489f8eff31SRafael Espindola RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 13499f8eff31SRafael Espindola &ValMaterializer); 1350cbb91408STanya Lattner 13517391dde1SChris Lattner // There is no need to map the arguments anymore. 135244ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 135344ab8aefSChris Lattner I != E; ++I) 13543aaaa0b2SReid Spencer ValueMap.erase(I); 1355cbb91408STanya Lattner 1356361e513dSReid Spencer } 1357361e513dSReid Spencer 135818c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module. 1359b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1360b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1361cbb91408STanya Lattner I != E; ++I) { 1362cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1363cbb91408STanya Lattner continue; 1364b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1365b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 13666b238633SRafael Espindola Constant *Val = 13676b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 136864c1e180SRafael Espindola DA->setAliasee(Val); 13692c4a34aeSDavid Chisnall } 1370b1ed91f3SChris Lattner } 1371cbb91408STanya Lattner } 1372b1ed91f3SChris Lattner 137318c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1374b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 137566f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1376b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1377b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 137866f02413SBill Wendling // Don't link module flags here. Do them separately. 137966f02413SBill Wendling if (&*I == SrcModFlags) continue; 1380b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1381b1ed91f3SChris Lattner // Add Src elements into Dest node. 1382b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1383b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1384f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1385b1ed91f3SChris Lattner } 1386b1ed91f3SChris Lattner } 1387b1ed91f3SChris Lattner 138818c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 138966f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 13900ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 139166f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 139266f02413SBill Wendling if (!SrcModFlags) return false; 139366f02413SBill Wendling 139466f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 139566f02413SBill Wendling // over the source module's flags. 13960ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 139766f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 139866f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 139966f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 140066f02413SBill Wendling 140166f02413SBill Wendling return false; 140266f02413SBill Wendling } 140366f02413SBill Wendling 14040ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 14050ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 14060ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 14070ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 14080ec72bbcSDaniel Dunbar MDNode *Op = DstModFlags->getOperand(I); 14090ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 14100ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 14110ec72bbcSDaniel Dunbar 14120ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 14130ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 14140ec72bbcSDaniel Dunbar } else { 14150ec72bbcSDaniel Dunbar Flags[ID] = Op; 14160ec72bbcSDaniel Dunbar } 14170ec72bbcSDaniel Dunbar } 14180ec72bbcSDaniel Dunbar 14190ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 14200ec72bbcSDaniel Dunbar // requirements. 142166f02413SBill Wendling bool HasErr = false; 14220ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 14230ec72bbcSDaniel Dunbar MDNode *SrcOp = SrcModFlags->getOperand(I); 14240ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 14250ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 14260ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 14270ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 142866f02413SBill Wendling 14290ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 14300ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 14310ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 14320ec72bbcSDaniel Dunbar // it. 14330ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 14340ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 14350ec72bbcSDaniel Dunbar } 14360ec72bbcSDaniel Dunbar continue; 14370ec72bbcSDaniel Dunbar } 143866f02413SBill Wendling 14390ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 14400ec72bbcSDaniel Dunbar if (!DstOp) { 14410ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 14420ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 14430ec72bbcSDaniel Dunbar continue; 14440ec72bbcSDaniel Dunbar } 144566f02413SBill Wendling 14460ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 14470ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 14480ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 14490ec72bbcSDaniel Dunbar 14500ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 14510ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 14520ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 14530ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 14540ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 14550ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 14560ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 14570ec72bbcSDaniel Dunbar } 14580ec72bbcSDaniel Dunbar continue; 14590ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 14600ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 14610ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 14620ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 14630ec72bbcSDaniel Dunbar continue; 14640ec72bbcSDaniel Dunbar } 14650ec72bbcSDaniel Dunbar 14660ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 14670ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 14680ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 146966f02413SBill Wendling "': IDs have conflicting behaviors"); 14700ec72bbcSDaniel Dunbar continue; 147166f02413SBill Wendling } 147266f02413SBill Wendling 14730ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 14740ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 14750ec72bbcSDaniel Dunbar case Module::Require: 14762a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 14770ec72bbcSDaniel Dunbar case Module::Error: { 14780ec72bbcSDaniel Dunbar // Emit an error if the values differ. 14790ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 14800ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 14810ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 148266f02413SBill Wendling } 14830ec72bbcSDaniel Dunbar continue; 148466f02413SBill Wendling } 14850ec72bbcSDaniel Dunbar case Module::Warning: { 14860ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 14870ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1488d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1489d12b4a33SRafael Espindola "': IDs have conflicting values"); 1490e17f3708SEli Bendersky } 14910ec72bbcSDaniel Dunbar continue; 14920ec72bbcSDaniel Dunbar } 1493d77d9fb0SDaniel Dunbar case Module::Append: { 1494d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1495d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1496d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1497d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1498d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1499d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1500d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1501d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1502d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1503d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1504d77d9fb0SDaniel Dunbar NumOps))); 1505d77d9fb0SDaniel Dunbar delete[] Values; 1506d77d9fb0SDaniel Dunbar break; 1507d77d9fb0SDaniel Dunbar } 1508d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1509d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1510d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1511d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1512d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1513d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1514d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1515d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1516d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1517d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1518d77d9fb0SDaniel Dunbar Elts.end()))); 1519d77d9fb0SDaniel Dunbar break; 1520d77d9fb0SDaniel Dunbar } 152166f02413SBill Wendling } 152266f02413SBill Wendling } 152366f02413SBill Wendling 15240ec72bbcSDaniel Dunbar // Check all of the requirements. 15250ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 15260ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 15270ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 15280ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 15290ec72bbcSDaniel Dunbar 15300ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 15310ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 15320ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 15339273b539SBill Wendling "': does not have the required value"); 15340ec72bbcSDaniel Dunbar continue; 153566f02413SBill Wendling } 153666f02413SBill Wendling } 153766f02413SBill Wendling 153866f02413SBill Wendling return HasErr; 153966f02413SBill Wendling } 154066f02413SBill Wendling 1541b1ed91f3SChris Lattner bool ModuleLinker::run() { 154266f02413SBill Wendling assert(DstM && "Null destination module"); 154366f02413SBill Wendling assert(SrcM && "Null source module"); 1544b1ed91f3SChris Lattner 1545b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1546b1ed91f3SChris Lattner // doesn't have one already. 1547f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1548b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1549b1ed91f3SChris Lattner 1550b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1551b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1552b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1553b1ed91f3SChris Lattner 1554f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1555ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1556d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1557d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1558d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1559d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1560d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1561e17f3708SEli Bendersky } 1562b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1563b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1564d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1565d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1566d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1567d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1568d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1569e17f3708SEli Bendersky } 1570b1ed91f3SChris Lattner 1571b1ed91f3SChris Lattner // Append the module inline asm string. 1572b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1573b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1574b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1575b1ed91f3SChris Lattner else 1576b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1577b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1578b1ed91f3SChris Lattner } 1579b1ed91f3SChris Lattner 1580b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1581b1ed91f3SChris Lattner computeTypeMapping(); 1582b1ed91f3SChris Lattner 1583dad0a645SDavid Majnemer ComdatsChosen.clear(); 1584dad0a645SDavid Majnemer for (const StringMapEntry<llvm::Comdat> &SMEC : SrcM->getComdatSymbolTable()) { 1585dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1586dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1587dad0a645SDavid Majnemer continue; 1588dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1589dad0a645SDavid Majnemer bool LinkFromSrc; 1590dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1591dad0a645SDavid Majnemer return true; 1592dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1593dad0a645SDavid Majnemer } 1594dad0a645SDavid Majnemer 159509d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 159609d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 159709d84addSDuncan P. N. Exon Smith 1598b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1599b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1600b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1601b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1602b1ed91f3SChris Lattner if (linkGlobalProto(I)) 1603b1ed91f3SChris Lattner return true; 1604b1ed91f3SChris Lattner 1605b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1606b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1607b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1608b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1609b1ed91f3SChris Lattner // ValueMap. 1610b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1611b1ed91f3SChris Lattner if (linkFunctionProto(I)) 1612b1ed91f3SChris Lattner return true; 1613b1ed91f3SChris Lattner 1614b1ed91f3SChris Lattner // If there were any aliases, link them now. 1615b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1616b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1617b1ed91f3SChris Lattner if (linkAliasProto(I)) 1618b1ed91f3SChris Lattner return true; 1619b1ed91f3SChris Lattner 1620b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1621b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1622b1ed91f3SChris Lattner 1623b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1624b1ed91f3SChris Lattner // DstM. 1625b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1626ea166d44STanya Lattner // Skip if not linking from source. 1627ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1628ea166d44STanya Lattner 16293fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 16303fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 16313fa50f9bSPeter Collingbourne // Link in the prefix data. 16323fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 16333fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 16343fa50f9bSPeter Collingbourne } 16353fa50f9bSPeter Collingbourne 1636d4bcefc7SRafael Espindola // Materialize if needed. 1637d4bcefc7SRafael Espindola if (SF->isMaterializable()) { 1638d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1639d12b4a33SRafael Espindola return emitError(EC.message()); 16405a52e6dcSRafael Espindola } 1641b1ed91f3SChris Lattner 1642d4bcefc7SRafael Espindola // Skip if no body (function is external). 1643d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1644d4bcefc7SRafael Espindola continue; 1645d4bcefc7SRafael Espindola 16463fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 164700623787SBill Wendling SF->Dematerialize(); 1648b1ed91f3SChris Lattner } 1649b1ed91f3SChris Lattner 1650b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1651b1ed91f3SChris Lattner linkAliasBodies(); 1652b1ed91f3SChris Lattner 165366f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 16546ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 16556ddbb2e2SDevang Patel // are properly remapped. 16566ddbb2e2SDevang Patel linkNamedMDNodes(); 16576ddbb2e2SDevang Patel 165866f02413SBill Wendling // Merge the module flags into the DstM module. 165966f02413SBill Wendling if (linkModuleFlagsMetadata()) 166066f02413SBill Wendling return true; 166166f02413SBill Wendling 166291686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 166391686d6dSBill Wendling // be referenced are in DstM. 166491686d6dSBill Wendling linkGlobalInits(); 166591686d6dSBill Wendling 16660a48b877STanya Lattner // Process vector of lazily linked in functions. 16670a48b877STanya Lattner bool LinkedInAnyFunctions; 16680a48b877STanya Lattner do { 16690a48b877STanya Lattner LinkedInAnyFunctions = false; 16700a48b877STanya Lattner 1671fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 16720a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1673f6f121e2SJames Molloy Function *SF = *I; 1674f6f121e2SJames Molloy if (!SF) 16750a48b877STanya Lattner continue; 16760a48b877STanya Lattner 1677fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 16783fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 16793fa50f9bSPeter Collingbourne // Link in the prefix data. 16803fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 16813fa50f9bSPeter Collingbourne ValueMap, 16823fa50f9bSPeter Collingbourne RF_None, 16833fa50f9bSPeter Collingbourne &TypeMap, 16843fa50f9bSPeter Collingbourne &ValMaterializer)); 16853fa50f9bSPeter Collingbourne } 16860a48b877STanya Lattner 1687d4bcefc7SRafael Espindola // Materialize if needed. 1688d4bcefc7SRafael Espindola if (SF->isMaterializable()) { 1689d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1690d12b4a33SRafael Espindola return emitError(EC.message()); 16915a52e6dcSRafael Espindola } 16920a48b877STanya Lattner 1693d4bcefc7SRafael Espindola // Skip if no body (function is external). 1694d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1695d4bcefc7SRafael Espindola continue; 1696d4bcefc7SRafael Espindola 1697f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1698f6f121e2SJames Molloy // invalidate I. 1699f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1700f6f121e2SJames Molloy 17010a48b877STanya Lattner // Link in function body. 17020a48b877STanya Lattner linkFunctionBody(DF, SF); 170300623787SBill Wendling SF->Dematerialize(); 17040a48b877STanya Lattner 17050a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 17060a48b877STanya Lattner // since we linked in a function. 17070a48b877STanya Lattner LinkedInAnyFunctions = true; 1708f6f121e2SJames Molloy break; 17090a48b877STanya Lattner } 17100a48b877STanya Lattner } while (LinkedInAnyFunctions); 17110a48b877STanya Lattner 1712b1ed91f3SChris Lattner // Now that all of the types from the source are used, resolve any structs 1713b1ed91f3SChris Lattner // copied over to the dest that didn't exist there. 1714b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 17152609888fSAnton Korobeynikov 17162609888fSAnton Korobeynikov return false; 17172609888fSAnton Korobeynikov } 1718361e513dSReid Spencer 17194160f5d3SRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) 17204160f5d3SRafael Espindola : Composite(M), DiagnosticHandler(DiagnosticHandler) {} 17214160f5d3SRafael Espindola 17224160f5d3SRafael Espindola Linker::Linker(Module *M) 17234160f5d3SRafael Espindola : Composite(M), DiagnosticHandler([this](const DiagnosticInfo &DI) { 17244160f5d3SRafael Espindola Composite->getContext().diagnose(DI); 17254160f5d3SRafael Espindola }) { 1726aa9918aaSRafael Espindola TypeFinder StructTypes; 1727aa9918aaSRafael Espindola StructTypes.run(*M, true); 1728aa9918aaSRafael Espindola IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1729aa9918aaSRafael Espindola } 17303df61b7bSRafael Espindola 17313df61b7bSRafael Espindola Linker::~Linker() { 17323df61b7bSRafael Espindola } 17333df61b7bSRafael Espindola 173491e6f6e1SBill Wendling void Linker::deleteModule() { 173591e6f6e1SBill Wendling delete Composite; 17362617dcceSCraig Topper Composite = nullptr; 173791e6f6e1SBill Wendling } 173891e6f6e1SBill Wendling 17399f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 17409f8eff31SRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 17419f8eff31SRafael Espindola DiagnosticHandler); 1742d12b4a33SRafael Espindola return TheLinker.run(); 17433df61b7bSRafael Espindola } 17443df61b7bSRafael Espindola 1745b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1746b1ed91f3SChris Lattner // LinkModules entrypoint. 1747b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1748b1ed91f3SChris Lattner 174918c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 175018c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 175118c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 175218c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 175318c89411SRafael Espindola /// relied on to be consistent. 17549f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 17554160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 17564160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 17579f8eff31SRafael Espindola return L.linkInModule(Src); 17584160f5d3SRafael Espindola } 17594160f5d3SRafael Espindola 17609f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1761287f18b4SRafael Espindola Linker L(Dest); 17629f8eff31SRafael Espindola return L.linkInModule(Src); 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) { 177198ab63ceSRafael Espindola Module *D = unwrap(Dest); 177298ab63ceSRafael Espindola std::string Message; 17734160f5d3SRafael Espindola raw_string_ostream Stream(Message); 17744160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 17754160f5d3SRafael Espindola 17764160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 17779f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 177898ab63ceSRafael Espindola 177998ab63ceSRafael Espindola if (OutMessages && Result) 178098ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1781a3aeb980SBill Wendling return Result; 1782a3aeb980SBill Wendling } 1783