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 50a96f235cSRafael Espindola SmallVector<StructType*, 16> SpeculativeDstOpaqueTypes; 51a96f235cSRafael Espindola 5218c89411SRafael Espindola /// This is a list of non-opaque structs in the source module that are mapped 5318c89411SRafael Espindola /// to an opaque struct in the destination module. 545e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 555e3bd972SChris Lattner 5618c89411SRafael Espindola /// This is the set of opaque types in the destination modules who are 5718c89411SRafael Espindola /// getting a body from the source module. 585e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 59d48b7783SBill Wendling 608c2cc416SBill Wendling public: 61a4e85e3dSRafael Espindola TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 62aa9918aaSRafael Espindola 63a4e85e3dSRafael Espindola TypeSet &DstStructTypesSet; 6418c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6518c89411SRafael Espindola /// equivalent to the specified type in the source module. 66b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 67b1ed91f3SChris Lattner 68d2a13a2eSRafael Espindola /// Produce a body for an opaque type in the dest module from a type 69d2a13a2eSRafael Espindola /// definition in the source module. 70b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 71b1ed91f3SChris Lattner 7218c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 73b1ed91f3SChris Lattner /// source module. 74b1ed91f3SChris Lattner Type *get(Type *SrcTy); 75b1ed91f3SChris Lattner 76290e2cc5SRafael Espindola FunctionType *get(FunctionType *T) { 77290e2cc5SRafael Espindola return cast<FunctionType>(get((Type *)T)); 78290e2cc5SRafael Espindola } 79b1ed91f3SChris Lattner 8018c89411SRafael Espindola /// Dump out the type map for debugging purposes. 81b6af2f36SBill Wendling void dump() const { 828f14471eSRafael Espindola for (auto &Pair : MappedTypes) { 83b6af2f36SBill Wendling dbgs() << "TypeMap: "; 848f14471eSRafael Espindola Pair.first->print(dbgs()); 85b6af2f36SBill Wendling dbgs() << " => "; 868f14471eSRafael Espindola Pair.second->print(dbgs()); 87b6af2f36SBill Wendling dbgs() << '\n'; 88b6af2f36SBill Wendling } 89b6af2f36SBill Wendling } 90b6af2f36SBill Wendling 91b1ed91f3SChris Lattner private: 92290e2cc5SRafael Espindola Type *remapType(Type *SrcTy) override { return get(SrcTy); } 93b1ed91f3SChris Lattner 94b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 95b1ed91f3SChris Lattner }; 96b1ed91f3SChris Lattner } 97b1ed91f3SChris Lattner 98b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 993d097410SRafael Espindola assert(SpeculativeTypes.empty()); 100a96f235cSRafael Espindola assert(SpeculativeDstOpaqueTypes.empty()); 1013d097410SRafael Espindola 102b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 103b1ed91f3SChris Lattner // mapping between them if so. 104c586eaa1SDuncan P. N. Exon Smith if (!areTypesIsomorphic(DstTy, SrcTy)) { 105b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 106b1ed91f3SChris Lattner // any speculative mappings we've established. 1073d097410SRafael Espindola for (Type *Ty : SpeculativeTypes) 1083d097410SRafael Espindola MappedTypes.erase(Ty); 109a96f235cSRafael Espindola 110a96f235cSRafael Espindola SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - 111a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.size()); 112a96f235cSRafael Espindola for (StructType *Ty : SpeculativeDstOpaqueTypes) 113a96f235cSRafael Espindola DstResolvedOpaqueTypes.erase(Ty); 11404a74af7SRafael Espindola } else { 11504a74af7SRafael Espindola for (Type *Ty : SpeculativeTypes) 11604a74af7SRafael Espindola if (auto *STy = dyn_cast<StructType>(Ty)) 11704a74af7SRafael Espindola if (STy->hasName()) 11804a74af7SRafael Espindola STy->setName(""); 119d48b7783SBill Wendling } 120b1ed91f3SChris Lattner SpeculativeTypes.clear(); 121a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.clear(); 122b1ed91f3SChris Lattner } 123b1ed91f3SChris Lattner 12418c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 12518c89411SRafael Espindola /// false if they are not. 126b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 127b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 128290e2cc5SRafael Espindola if (DstTy->getTypeID() != SrcTy->getTypeID()) 129290e2cc5SRafael Espindola return false; 130b1ed91f3SChris Lattner 131b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 132b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 133b1ed91f3SChris Lattner if (Entry) 134b1ed91f3SChris Lattner return Entry == DstTy; 135b1ed91f3SChris Lattner 136b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 137b1ed91f3SChris Lattner // non-speculatively. 138b1ed91f3SChris Lattner if (DstTy == SrcTy) { 139b1ed91f3SChris Lattner Entry = DstTy; 140361e513dSReid Spencer return true; 141361e513dSReid Spencer } 142361e513dSReid Spencer 143b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 144361e513dSReid Spencer 145b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 146b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 147b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 148b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 149b1ed91f3SChris Lattner Entry = DstTy; 150b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 151b1ed91f3SChris Lattner return true; 152361e513dSReid Spencer } 153b1ed91f3SChris Lattner 1545e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1555e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 156a96f235cSRafael Espindola // the dest, but fill it in later. If this is the second (different) type 157a96f235cSRafael Espindola // that we're trying to map onto the same opaque type then we fail. 158b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1595e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 16070573dcdSDavid Blaikie if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 1615e3bd972SChris Lattner return false; 1625e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 163a96f235cSRafael Espindola SpeculativeTypes.push_back(SrcTy); 164a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); 165b1ed91f3SChris Lattner Entry = DstTy; 166b1ed91f3SChris Lattner return true; 167b1ed91f3SChris Lattner } 168b1ed91f3SChris Lattner } 169b1ed91f3SChris Lattner 170b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 171b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 172b1ed91f3SChris Lattner return false; 173b1ed91f3SChris Lattner 174b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 175b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 176b1ed91f3SChris Lattner return false; // bitwidth disagrees. 177b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 178b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 179b1ed91f3SChris Lattner return false; 180eaf9b762SChris Lattner 181b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 182b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 183b1ed91f3SChris Lattner return false; 184b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 185b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 18644f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 187b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 188b1ed91f3SChris Lattner return false; 189b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 190b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 191b1ed91f3SChris Lattner return false; 192b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1935fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 194361e513dSReid Spencer return false; 195361e513dSReid Spencer } 196361e513dSReid Spencer 197b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 198b1ed91f3SChris Lattner // check the subelements. 199b1ed91f3SChris Lattner Entry = DstTy; 200b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 201eee6f995SChris Lattner 202290e2cc5SRafael Espindola for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 203290e2cc5SRafael Espindola if (!areTypesIsomorphic(DstTy->getContainedType(I), 204290e2cc5SRafael Espindola SrcTy->getContainedType(I))) 205b1ed91f3SChris Lattner return false; 206eee6f995SChris Lattner 207b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 208eee6f995SChris Lattner return true; 209eee6f995SChris Lattner } 210eee6f995SChris Lattner 211b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 212b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 213c81c3f55SRafael Espindola for (StructType *SrcSTy : SrcDefinitionsToResolve) { 214b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 215c81c3f55SRafael Espindola assert(DstSTy->isOpaque()); 216b1ed91f3SChris Lattner 217b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 218b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 219290e2cc5SRafael Espindola for (unsigned I = 0, E = Elements.size(); I != E; ++I) 220c81c3f55SRafael Espindola Elements[I] = get(SrcSTy->getElementType(I)); 221b1ed91f3SChris Lattner 222b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 223b1ed91f3SChris Lattner } 224c81c3f55SRafael Espindola SrcDefinitionsToResolve.clear(); 2255e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 226eee6f995SChris Lattner } 227eee6f995SChris Lattner 228b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 229a4e85e3dSRafael Espindola #ifndef NDEBUG 230a4e85e3dSRafael Espindola for (auto &Pair : MappedTypes) { 231a4e85e3dSRafael Espindola assert(!(Pair.first != Ty && Pair.second == Ty) && 232a4e85e3dSRafael Espindola "mapping to a source type"); 233a4e85e3dSRafael Espindola } 234a4e85e3dSRafael Espindola #endif 235a4e85e3dSRafael Espindola 236b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 237b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 238290e2cc5SRafael Espindola if (*Entry) 239290e2cc5SRafael Espindola return *Entry; 240b1ed91f3SChris Lattner 241b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 242b1ed91f3SChris Lattner // then rebuild the type from inside out. 24344f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 244b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 245b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 246b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 247b1ed91f3SChris Lattner return *Entry = Ty; 248b1ed91f3SChris Lattner 249b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 250b1ed91f3SChris Lattner bool AnyChange = false; 251b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 252b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 253290e2cc5SRafael Espindola for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 254c81c3f55SRafael Espindola ElementTypes[I] = get(Ty->getContainedType(I)); 255290e2cc5SRafael Espindola AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 256eee6f995SChris Lattner } 257b1ed91f3SChris Lattner 258b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 259b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 260290e2cc5SRafael Espindola if (*Entry) 261290e2cc5SRafael Espindola return *Entry; 262b1ed91f3SChris Lattner 263b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 264b1ed91f3SChris Lattner // as-is. 265b1ed91f3SChris Lattner if (!AnyChange) 266b1ed91f3SChris Lattner return *Entry = Ty; 267b1ed91f3SChris Lattner 268b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 269b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 270290e2cc5SRafael Espindola default: 271290e2cc5SRafael Espindola llvm_unreachable("unknown derived type to remap"); 272b1ed91f3SChris Lattner case Type::ArrayTyID: 273b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 274b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 275b1ed91f3SChris Lattner case Type::VectorTyID: 276b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 277b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 278b1ed91f3SChris Lattner case Type::PointerTyID: 279290e2cc5SRafael Espindola return *Entry = PointerType::get( 280290e2cc5SRafael Espindola ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace()); 281b1ed91f3SChris Lattner case Type::FunctionTyID: 282b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 283717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 284b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 285b1ed91f3SChris Lattner case Type::StructTyID: 286b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 287b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 288b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 289b1ed91f3SChris Lattner } 290b1ed91f3SChris Lattner } 291b1ed91f3SChris Lattner 292b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 293b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 294b1ed91f3SChris Lattner // module has something like: 295b1ed91f3SChris Lattner // %T = type {%T*, i32} 296b1ed91f3SChris Lattner // @GV = global %T* null 297b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 298b1ed91f3SChris Lattner // 299b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 300b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 301b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 302b1ed91f3SChris Lattner // %A = type { i32 } 303b1ed91f3SChris Lattner // and the source module has something like 304b1ed91f3SChris Lattner // %A' = type { i32 } 305b1ed91f3SChris Lattner // %B = type { %A'* } 306b1ed91f3SChris Lattner // @GV = global %B* null 307b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 308b1ed91f3SChris Lattner // pristine "%B" name from the source module. 309b1ed91f3SChris Lattner // 310b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 311b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 312b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 313b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 314b1ed91f3SChris Lattner // it and always rebuild a type here. 315b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 316b1ed91f3SChris Lattner 317b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 318aa9918aaSRafael Espindola if (STy->isOpaque()) { 319aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 320aa9918aaSRafael Espindola // identified structs in the destination module. 321a4e85e3dSRafael Espindola DstStructTypesSet.insert(STy); 322b1ed91f3SChris Lattner return *Entry = STy; 323aa9918aaSRafael Espindola } 324b1ed91f3SChris Lattner 325c81c3f55SRafael Espindola // Otherwise we create a new type. 3265e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 327aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 328aa9918aaSRafael Espindola // identified structs in the destination module. 329a4e85e3dSRafael Espindola DstStructTypesSet.insert(DTy); 330c81c3f55SRafael Espindola *Entry = DTy; 331c81c3f55SRafael Espindola 332c81c3f55SRafael Espindola SmallVector<Type*, 4> ElementTypes; 333c81c3f55SRafael Espindola ElementTypes.resize(STy->getNumElements()); 334c81c3f55SRafael Espindola for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I) 335c81c3f55SRafael Espindola ElementTypes[I] = get(STy->getElementType(I)); 336c81c3f55SRafael Espindola DTy->setBody(ElementTypes, STy->isPacked()); 337c81c3f55SRafael Espindola 338c81c3f55SRafael Espindola // Steal STy's name. 339c81c3f55SRafael Espindola if (STy->hasName()) { 340c81c3f55SRafael Espindola SmallString<16> TmpName = STy->getName(); 341c81c3f55SRafael Espindola STy->setName(""); 342c81c3f55SRafael Espindola DTy->setName(TmpName); 343c81c3f55SRafael Espindola } 344c81c3f55SRafael Espindola 345c81c3f55SRafael Espindola return DTy; 346b1ed91f3SChris Lattner } 347b1ed91f3SChris Lattner 348b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 349b1ed91f3SChris Lattner // ModuleLinker implementation. 350b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 351b1ed91f3SChris Lattner 352b1ed91f3SChris Lattner namespace { 353f6f121e2SJames Molloy class ModuleLinker; 354f6f121e2SJames Molloy 35518c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 35618c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 35718c89411SRafael Espindola /// few get used. 358f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 359f6f121e2SJames Molloy TypeMapTy &TypeMap; 360f6f121e2SJames Molloy Module *DstM; 361f6f121e2SJames Molloy std::vector<Function *> &LazilyLinkFunctions; 362c84f608bSRafael Espindola 363f6f121e2SJames Molloy public: 364f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 365c84f608bSRafael Espindola std::vector<Function *> &LazilyLinkFunctions) 366c84f608bSRafael Espindola : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 367c84f608bSRafael Espindola LazilyLinkFunctions(LazilyLinkFunctions) {} 368f6f121e2SJames Molloy 3698548299aSCraig Topper Value *materializeValueFor(Value *V) override; 370f6f121e2SJames Molloy }; 371f6f121e2SJames Molloy 372d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 373d12b4a33SRafael Espindola const Twine &Msg; 374d12b4a33SRafael Espindola 375d12b4a33SRafael Espindola public: 376d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 377d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 378d12b4a33SRafael Espindola }; 379d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 380d12b4a33SRafael Espindola const Twine &Msg) 381d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 382d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 383d12b4a33SRafael Espindola 38418c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the 38518c89411SRafael Espindola /// entrypoint for this file. 386b1ed91f3SChris Lattner class ModuleLinker { 387b1ed91f3SChris Lattner Module *DstM, *SrcM; 388b1ed91f3SChris Lattner 389b1ed91f3SChris Lattner TypeMapTy TypeMap; 390f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 391b1ed91f3SChris Lattner 39218c89411SRafael Espindola /// Mapping of values from what they used to be in Src, to what they are now 39318c89411SRafael Espindola /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 39418c89411SRafael Espindola /// due to the use of Value handles which the Linker doesn't actually need, 39518c89411SRafael Espindola /// but this allows us to reuse the ValueMapper code. 396b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 397b1ed91f3SChris Lattner 398b1ed91f3SChris Lattner struct AppendingVarInfo { 399b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 4003e8bc6a8SRafael Espindola const Constant *DstInit; // Old initializer from dest module. 4013e8bc6a8SRafael Espindola const Constant *SrcInit; // Old initializer from src module. 402b1ed91f3SChris Lattner }; 403b1ed91f3SChris Lattner 404b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 405b1ed91f3SChris Lattner 406cbb91408STanya Lattner // Set of items not to link in from source. 407cbb91408STanya Lattner SmallPtrSet<const Value *, 16> DoNotLinkFromSource; 408cbb91408STanya Lattner 4090a48b877STanya Lattner // Vector of functions to lazily link in. 410fa228782SBill Wendling std::vector<Function *> LazilyLinkFunctions; 4110a48b877STanya Lattner 4124160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 4134160f5d3SRafael Espindola 414b1ed91f3SChris Lattner public: 415a4e85e3dSRafael Espindola ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, 4164160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 417a4e85e3dSRafael Espindola : DstM(dstM), SrcM(srcM), TypeMap(Set), 4189f8eff31SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), 4194160f5d3SRafael Espindola DiagnosticHandler(DiagnosticHandler) {} 420b1ed91f3SChris Lattner 421b1ed91f3SChris Lattner bool run(); 422b1ed91f3SChris Lattner 423b1ed91f3SChris Lattner private: 424d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 425d12b4a33SRafael Espindola const GlobalValue &Src); 426dbb0bd1aSRafael Espindola 427d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 428b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 4294160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 430b1ed91f3SChris Lattner return true; 431b1ed91f3SChris Lattner } 432b1ed91f3SChris Lattner 433d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 4344160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 435d12b4a33SRafael Espindola } 436d12b4a33SRafael Espindola 437dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 438dad0a645SDavid Majnemer const GlobalVariable *&GVar); 439dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 440dad0a645SDavid Majnemer Comdat::SelectionKind Src, 441dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 442dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 443dad0a645SDavid Majnemer bool &LinkFromSrc); 444dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 445dad0a645SDavid Majnemer ComdatsChosen; 446dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 447dad0a645SDavid Majnemer bool &LinkFromSrc); 448dad0a645SDavid Majnemer 44918c89411SRafael Espindola /// Given a global in the source module, return the global in the 45018c89411SRafael Espindola /// destination module that is being linked to, if any. 4513e8bc6a8SRafael Espindola GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 452b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 453b1ed91f3SChris Lattner // there is no name match-up going on. 454b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4552617dcceSCraig Topper return nullptr; 456b1ed91f3SChris Lattner 457b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 458b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 459c84f608bSRafael Espindola if (!DGV) 460c84f608bSRafael Espindola return nullptr; 461b1ed91f3SChris Lattner 462b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 463b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 464b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4652617dcceSCraig Topper return nullptr; 466b1ed91f3SChris Lattner 467b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 468b1ed91f3SChris Lattner return DGV; 469b1ed91f3SChris Lattner } 470b1ed91f3SChris Lattner 471b1ed91f3SChris Lattner void computeTypeMapping(); 472b1ed91f3SChris Lattner 47309d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 47409d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 47509d84addSDuncan P. N. Exon Smith 4763e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 4773e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 478778fcc77SRafael Espindola 479778fcc77SRafael Espindola bool linkGlobalValueProto(GlobalValue *GV); 480778fcc77SRafael Espindola GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar, 481778fcc77SRafael Espindola GlobalValue *DGV, bool LinkFromSrc); 482778fcc77SRafael Espindola GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV, 483778fcc77SRafael Espindola bool LinkFromSrc); 484778fcc77SRafael Espindola GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV, 485778fcc77SRafael Espindola bool LinkFromSrc); 486778fcc77SRafael Espindola 48766f02413SBill Wendling bool linkModuleFlagsMetadata(); 488b1ed91f3SChris Lattner 489b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 490b1ed91f3SChris Lattner void linkGlobalInits(); 491b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 492b1ed91f3SChris Lattner void linkAliasBodies(); 493b1ed91f3SChris Lattner void linkNamedMDNodes(); 494eee6f995SChris Lattner }; 495d48b7783SBill Wendling } 496d48b7783SBill Wendling 49718c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 49818c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 49918c89411SRafael Espindola /// to force this back. 500b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 501b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 502b1ed91f3SChris Lattner // there is nothing for us to do. 503b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 504b1ed91f3SChris Lattner return; 505b1ed91f3SChris Lattner 506b1ed91f3SChris Lattner Module *M = GV->getParent(); 507361e513dSReid Spencer 508361e513dSReid Spencer // If there is a conflict, rename the conflict. 509b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5102a8d2e0eSChris Lattner GV->takeName(ConflictGV); 511361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 512b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5132a8d2e0eSChris Lattner } else { 5142a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5153aaaa0b2SReid Spencer } 5163aaaa0b2SReid Spencer } 5173aaaa0b2SReid Spencer 51818c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 51918c89411SRafael Espindola /// from the SrcGV to the DestGV. 520b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 521dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 52299e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 523a7d9c69cSRafael Espindola unsigned Alignment; 52499e05cf1SRafael Espindola if (DestGO) 52599e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 526a7d9c69cSRafael Espindola 527dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 528a7d9c69cSRafael Espindola 52999e05cf1SRafael Espindola if (DestGO) 53099e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 531b1ed91f3SChris Lattner 532b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 533361e513dSReid Spencer } 534361e513dSReid Spencer 53523f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 53623f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 53723f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 53823f8d64bSRafael Espindola return false; 53923f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 54023f8d64bSRafael Espindola return true; 54123f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 54223f8d64bSRafael Espindola return false; 54323f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 54423f8d64bSRafael Espindola return true; 54523f8d64bSRafael Espindola return false; 54623f8d64bSRafael Espindola } 54723f8d64bSRafael Espindola 548f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 549f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 550f6f121e2SJames Molloy if (!SF) 5512617dcceSCraig Topper return nullptr; 552f6f121e2SJames Molloy 553f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 554f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 555f6f121e2SJames Molloy copyGVAttributes(DF, SF); 556f6f121e2SJames Molloy 5573931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5583931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5593931c28bSRafael Espindola DF->setComdat(DC); 5603931c28bSRafael Espindola } 5613931c28bSRafael Espindola 562f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 563f6f121e2SJames Molloy return DF; 564f6f121e2SJames Molloy } 565f6f121e2SJames Molloy 566dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 567dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 568dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 569dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 570dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 571dad0a645SDavid Majnemer if (!GVal) 572dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 573dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 574dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 575dad0a645SDavid Majnemer } 576dad0a645SDavid Majnemer 577dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 578dad0a645SDavid Majnemer if (!GVar) 579dad0a645SDavid Majnemer return emitError( 580dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 581dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 582dad0a645SDavid Majnemer 583dad0a645SDavid Majnemer return false; 584dad0a645SDavid Majnemer } 585dad0a645SDavid Majnemer 586dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 587dad0a645SDavid Majnemer Comdat::SelectionKind Src, 588dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 589dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 590dad0a645SDavid Majnemer bool &LinkFromSrc) { 591dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 592dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 593dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 594dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 595dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 596dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 597dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 598dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 599dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 600dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 601dad0a645SDavid Majnemer else 602dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 603dad0a645SDavid Majnemer } else if (Src == Dst) { 604dad0a645SDavid Majnemer Result = Dst; 605dad0a645SDavid Majnemer } else { 606dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 607dad0a645SDavid Majnemer "': invalid selection kinds!"); 608dad0a645SDavid Majnemer } 609dad0a645SDavid Majnemer 610dad0a645SDavid Majnemer switch (Result) { 611dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 612dad0a645SDavid Majnemer // Go with Dst. 613dad0a645SDavid Majnemer LinkFromSrc = false; 614dad0a645SDavid Majnemer break; 615dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 616dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 617dad0a645SDavid Majnemer "': noduplicates has been violated!"); 618dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 619dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 620dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 621dad0a645SDavid Majnemer const GlobalVariable *DstGV; 622dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 623dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 624dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 625dad0a645SDavid Majnemer return true; 626dad0a645SDavid Majnemer 627dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 628dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 629dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 630dad0a645SDavid Majnemer return emitError( 631dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 632dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 633dad0a645SDavid Majnemer } 634dad0a645SDavid Majnemer uint64_t DstSize = 635dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 636dad0a645SDavid Majnemer uint64_t SrcSize = 637dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 638dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 639dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 640dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 641dad0a645SDavid Majnemer "': ExactMatch violated!"); 642dad0a645SDavid Majnemer LinkFromSrc = false; 643dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 644dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 645dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 646dad0a645SDavid Majnemer if (SrcSize != DstSize) 647dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 648dad0a645SDavid Majnemer "': SameSize violated!"); 649dad0a645SDavid Majnemer LinkFromSrc = false; 650dad0a645SDavid Majnemer } else { 651dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 652dad0a645SDavid Majnemer } 653dad0a645SDavid Majnemer break; 654dad0a645SDavid Majnemer } 655dad0a645SDavid Majnemer } 656dad0a645SDavid Majnemer 657dad0a645SDavid Majnemer return false; 658dad0a645SDavid Majnemer } 659dad0a645SDavid Majnemer 660dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 661dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 662dad0a645SDavid Majnemer bool &LinkFromSrc) { 663b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 664dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 665dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 666dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6672ef3f299SRafael Espindola 668b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 669b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 670b16196a3SRafael Espindola LinkFromSrc = true; 671b16196a3SRafael Espindola Result = SSK; 6722ef3f299SRafael Espindola return false; 673b16196a3SRafael Espindola } 6742ef3f299SRafael Espindola 675dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 676dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6772ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6782ef3f299SRafael Espindola LinkFromSrc); 679dad0a645SDavid Majnemer } 680f6f121e2SJames Molloy 681d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 682d12b4a33SRafael Espindola const GlobalValue &Dest, 683dbb0bd1aSRafael Espindola const GlobalValue &Src) { 684778fcc77SRafael Espindola // We always have to add Src if it has appending linkage. 685778fcc77SRafael Espindola if (Src.hasAppendingLinkage()) { 686778fcc77SRafael Espindola LinkFromSrc = true; 687778fcc77SRafael Espindola return false; 688778fcc77SRafael Espindola } 689778fcc77SRafael Espindola 690d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 691d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 692dbb0bd1aSRafael Espindola 693dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 694dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 695dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 696d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 697dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 698d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 699d12b4a33SRafael Espindola return false; 700d12b4a33SRafael Espindola } 701dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 702d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 703d12b4a33SRafael Espindola return false; 704dbb0bd1aSRafael Espindola } 705dbb0bd1aSRafael Espindola 706d12b4a33SRafael Espindola if (DestIsDeclaration) { 707dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 708d12b4a33SRafael Espindola LinkFromSrc = true; 709d12b4a33SRafael Espindola return false; 710d12b4a33SRafael Espindola } 711dbb0bd1aSRafael Espindola 7120910605aSRafael Espindola if (Src.hasCommonLinkage()) { 713d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 714d12b4a33SRafael Espindola LinkFromSrc = true; 7150910605aSRafael Espindola return false; 716d12b4a33SRafael Espindola } 717d12b4a33SRafael Espindola 718d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 719d12b4a33SRafael Espindola LinkFromSrc = false; 720d12b4a33SRafael Espindola return false; 721d12b4a33SRafael Espindola } 7220910605aSRafael Espindola 7230ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7240ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7250ae225b6SRafael Espindola 7260910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7270910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 728d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 729d12b4a33SRafael Espindola return false; 7300910605aSRafael Espindola } 7310910605aSRafael Espindola 732dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 733dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 734dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7350910605aSRafael Espindola 736d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 737d12b4a33SRafael Espindola LinkFromSrc = true; 738d12b4a33SRafael Espindola return false; 739d12b4a33SRafael Espindola } 740dbb0bd1aSRafael Espindola 741d12b4a33SRafael Espindola LinkFromSrc = false; 7420910605aSRafael Espindola return false; 743dbb0bd1aSRafael Espindola } 744dbb0bd1aSRafael Espindola 745dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 746dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 747d12b4a33SRafael Espindola LinkFromSrc = true; 748d12b4a33SRafael Espindola return false; 749dbb0bd1aSRafael Espindola } 750dbb0bd1aSRafael Espindola 751dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 752dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 753dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 754dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 755dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 756dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 757dbb0bd1aSRafael Espindola } 758dbb0bd1aSRafael Espindola 75918c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 76018c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 76118c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 76218c89411SRafael Espindola /// LLVMContext. 763b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 764c8a476eeSRafael Espindola for (GlobalValue &SGV : SrcM->globals()) { 765c8a476eeSRafael Espindola GlobalValue *DGV = getLinkedToGlobal(&SGV); 766c8a476eeSRafael Espindola if (!DGV) 767c8a476eeSRafael Espindola continue; 768b1ed91f3SChris Lattner 769c8a476eeSRafael Espindola if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 770c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 771b1ed91f3SChris Lattner continue; 7725c310be0SDevang Patel } 7735c310be0SDevang Patel 774b1ed91f3SChris Lattner // Unify the element type of appending arrays. 775b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 776c8a476eeSRafael Espindola ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 777b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 778b1ed91f3SChris Lattner } 77934fc5a0eSChris Lattner 780c8a476eeSRafael Espindola for (GlobalValue &SGV : *SrcM) { 781c8a476eeSRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 782c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 783b1ed91f3SChris Lattner } 784e79f4c77SAnton Korobeynikov 785e96d7eb8SRafael Espindola for (GlobalValue &SGV : SrcM->aliases()) { 786e96d7eb8SRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 787e96d7eb8SRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 788e96d7eb8SRafael Espindola } 789e96d7eb8SRafael Espindola 790d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 791d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 7922b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 7932b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 7948555a37cSBill Wendling TypeFinder SrcStructTypes; 7958555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 7962b3f61afSBill Wendling 797*4d4c9387SRafael Espindola for (StructType *ST : SrcStructTypes) { 798*4d4c9387SRafael Espindola if (!ST->hasName()) 799*4d4c9387SRafael Espindola continue; 8002b3f61afSBill Wendling 8012b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 802d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 803d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 80483c74e9fSGuy Benyei ST->getName().back() == '.' || 80583c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 806d48b7783SBill Wendling continue; 8072b3f61afSBill Wendling 8082b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 809d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 8102b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8118737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8128737480dSBill Wendling // actually used in the destination module. This can happen in situations 8138737480dSBill Wendling // like this: 8148737480dSBill Wendling // 8158737480dSBill Wendling // Module A Module B 8168737480dSBill Wendling // -------- -------- 8178737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8188737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8198737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8208737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8218737480dSBill Wendling // 8228737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8238737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8248737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8258737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8268737480dSBill Wendling // variables using one type and some using the other. 827dd42b533SRafael Espindola if (TypeMap.DstStructTypesSet.count(DST)) 8282b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8292b3f61afSBill Wendling } 8302b3f61afSBill Wendling 831b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 832b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 833b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 834b1ed91f3SChris Lattner } 835c08e7a00SChris Lattner 83609d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 83709d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 83809d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 83909d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 84009d84addSDuncan P. N. Exon Smith 84109d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 84209d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 84309d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 84409d84addSDuncan P. N. Exon Smith VoidPtrTy}; 84509d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 84609d84addSDuncan P. N. Exon Smith 84709d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 84809d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 84909d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 85009d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 85109d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 85209d84addSDuncan P. N. Exon Smith return; 85309d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 85409d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 85509d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 85609d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 85709d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 85809d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 85909d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 86009d84addSDuncan P. N. Exon Smith } 86109d84addSDuncan P. N. Exon Smith } 86209d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 86309d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 86409d84addSDuncan P. N. Exon Smith 86509d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 86609d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 86709d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 86809d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 86909d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 87009d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 87109d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 87209d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 87309d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 87409d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 87509d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 87609d84addSDuncan P. N. Exon Smith } 87709d84addSDuncan P. N. Exon Smith 87809d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 87909d84addSDuncan P. N. Exon Smith // Look for the global arrays. 88009d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 88109d84addSDuncan P. N. Exon Smith if (!DstGV) 88209d84addSDuncan P. N. Exon Smith return; 88309d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 88409d84addSDuncan P. N. Exon Smith if (!SrcGV) 88509d84addSDuncan P. N. Exon Smith return; 88609d84addSDuncan P. N. Exon Smith 88709d84addSDuncan P. N. Exon Smith // Check if the types already match. 88809d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 88909d84addSDuncan P. N. Exon Smith auto *SrcTy = 89009d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 89109d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 89209d84addSDuncan P. N. Exon Smith return; 89309d84addSDuncan P. N. Exon Smith 89409d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 89509d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 89609d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 89709d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 89809d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 89909d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 90009d84addSDuncan P. N. Exon Smith return; 90109d84addSDuncan P. N. Exon Smith } 90209d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 90309d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 90409d84addSDuncan P. N. Exon Smith 90509d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 90609d84addSDuncan P. N. Exon Smith } 90709d84addSDuncan P. N. Exon Smith 90809d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 90909d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 91009d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 91109d84addSDuncan P. N. Exon Smith } 91209d84addSDuncan P. N. Exon Smith 91318c89411SRafael Espindola /// If there were any appending global variables, link them together now. 91418c89411SRafael Espindola /// Return true on error. 915b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 9163e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 917d48b7783SBill Wendling 918b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 919b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 920b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 921361e513dSReid Spencer 922b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 923b1ed91f3SChris Lattner ArrayType *SrcTy = 924b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 925b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 926b1ed91f3SChris Lattner 927b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 928b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 929b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 930b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 931b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 932b1ed91f3SChris Lattner 933b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 934b1ed91f3SChris Lattner return emitError( 935b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 936b1ed91f3SChris Lattner 937b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 938b1ed91f3SChris Lattner return emitError( 939b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 940b1ed91f3SChris Lattner 941fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 942fac3a018SRafael Espindola return emitError( 943fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 944fac3a018SRafael Espindola 94564c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 946b1ed91f3SChris Lattner return emitError( 947b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 948b1ed91f3SChris Lattner 949b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 950b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 951b1ed91f3SChris Lattner 952b1ed91f3SChris Lattner // Create the new global variable. 953b1ed91f3SChris Lattner GlobalVariable *NG = 954b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9552617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 956cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 957b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 958b1ed91f3SChris Lattner 959b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 960b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 961b1ed91f3SChris Lattner 962b1ed91f3SChris Lattner AppendingVarInfo AVI; 963b1ed91f3SChris Lattner AVI.NewGV = NG; 964b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 965b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 966b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 967b1ed91f3SChris Lattner 968b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 969b1ed91f3SChris Lattner // global. 970b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 971b1ed91f3SChris Lattner 972b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 973b1ed91f3SChris Lattner DstGV->eraseFromParent(); 974b1ed91f3SChris Lattner 975cbb91408STanya Lattner // Track the source variable so we don't try to link it. 976cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 977cbb91408STanya Lattner 978b1ed91f3SChris Lattner return false; 979b1ed91f3SChris Lattner } 980b1ed91f3SChris Lattner 981778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 982b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 983b1ed91f3SChris Lattner 984778fcc77SRafael Espindola // Handle the ultra special appending linkage case first. 985778fcc77SRafael Espindola if (DGV && DGV->hasAppendingLinkage()) 986778fcc77SRafael Espindola return linkAppendingVarProto(cast<GlobalVariable>(DGV), 987778fcc77SRafael Espindola cast<GlobalVariable>(SGV)); 988778fcc77SRafael Espindola 989778fcc77SRafael Espindola bool LinkFromSrc = true; 990778fcc77SRafael Espindola Comdat *C = nullptr; 991778fcc77SRafael Espindola GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 992778fcc77SRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 993778fcc77SRafael Espindola 994dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 995dad0a645SDavid Majnemer Comdat::SelectionKind SK; 996dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 997778fcc77SRafael Espindola C = DstM->getOrInsertComdat(SC->getName()); 998778fcc77SRafael Espindola C->setSelectionKind(SK); 999778fcc77SRafael Espindola } else if (DGV) { 1000778fcc77SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 1001fc61de39SChris Lattner return true; 1002dad0a645SDavid Majnemer } 100334fc5a0eSChris Lattner 1004dad0a645SDavid Majnemer if (!LinkFromSrc) { 1005cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 1006cbb91408STanya Lattner // processing global initializers. 1007cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1008cbb91408STanya Lattner 1009778fcc77SRafael Espindola if (DGV) 1010778fcc77SRafael Espindola // Make sure to remember this mapping. 1011778fcc77SRafael Espindola ValueMap[SGV] = 1012778fcc77SRafael Espindola ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 1013778fcc77SRafael Espindola } 1014778fcc77SRafael Espindola 1015778fcc77SRafael Espindola if (DGV) { 1016778fcc77SRafael Espindola Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 1017778fcc77SRafael Espindola ? DGV->getVisibility() 1018778fcc77SRafael Espindola : Visibility; 1019778fcc77SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1020778fcc77SRafael Espindola } 1021778fcc77SRafael Espindola 1022778fcc77SRafael Espindola if (!LinkFromSrc && !DGV) 1023dad0a645SDavid Majnemer return false; 1024778fcc77SRafael Espindola 1025778fcc77SRafael Espindola GlobalValue *NewGV; 1026778fcc77SRafael Espindola if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { 1027778fcc77SRafael Espindola NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc); 1028778fcc77SRafael Espindola if (!NewGV) 1029778fcc77SRafael Espindola return true; 1030778fcc77SRafael Espindola } else if (auto *SF = dyn_cast<Function>(SGV)) { 1031778fcc77SRafael Espindola NewGV = linkFunctionProto(SF, DGV, LinkFromSrc); 1032778fcc77SRafael Espindola } else { 1033778fcc77SRafael Espindola NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc); 1034778fcc77SRafael Espindola } 1035778fcc77SRafael Espindola 1036778fcc77SRafael Espindola if (NewGV) { 1037778fcc77SRafael Espindola if (NewGV != DGV) 1038778fcc77SRafael Espindola copyGVAttributes(NewGV, SGV); 1039778fcc77SRafael Espindola 1040778fcc77SRafael Espindola NewGV->setUnnamedAddr(HasUnnamedAddr); 1041778fcc77SRafael Espindola NewGV->setVisibility(Visibility); 1042778fcc77SRafael Espindola 1043778fcc77SRafael Espindola if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1044778fcc77SRafael Espindola if (C) 1045778fcc77SRafael Espindola NewGO->setComdat(C); 1046778fcc77SRafael Espindola } 1047778fcc77SRafael Espindola 1048778fcc77SRafael Espindola // Make sure to remember this mapping. 1049778fcc77SRafael Espindola if (NewGV != DGV) { 1050778fcc77SRafael Espindola if (DGV) { 1051778fcc77SRafael Espindola DGV->replaceAllUsesWith( 1052778fcc77SRafael Espindola ConstantExpr::getBitCast(NewGV, DGV->getType())); 1053778fcc77SRafael Espindola DGV->eraseFromParent(); 1054778fcc77SRafael Espindola } 1055778fcc77SRafael Espindola ValueMap[SGV] = NewGV; 1056dad0a645SDavid Majnemer } 10574e27567aSRafael Espindola } 10584e27567aSRafael Espindola 1059fd38af2dSChandler Carruth return false; 10604e27567aSRafael Espindola } 10614e27567aSRafael Espindola 1062778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the 1063778fcc77SRafael Espindola /// dest module. 1064778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar, 1065778fcc77SRafael Espindola GlobalValue *DGV, 1066778fcc77SRafael Espindola bool LinkFromSrc) { 1067778fcc77SRafael Espindola unsigned Alignment = 0; 1068778fcc77SRafael Espindola bool ClearConstant = false; 1069778fcc77SRafael Espindola 1070778fcc77SRafael Espindola if (DGV) { 1071778fcc77SRafael Espindola if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage()) 1072778fcc77SRafael Espindola Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment()); 1073778fcc77SRafael Espindola 1074778fcc77SRafael Espindola auto *DGVar = dyn_cast<GlobalVariable>(DGV); 1075778fcc77SRafael Espindola if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant())) 1076778fcc77SRafael Espindola ClearConstant = true; 1077778fcc77SRafael Espindola } 1078778fcc77SRafael Espindola 1079778fcc77SRafael Espindola if (!LinkFromSrc) { 1080778fcc77SRafael Espindola if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) { 1081778fcc77SRafael Espindola if (Alignment) 1082778fcc77SRafael Espindola NewGVar->setAlignment(Alignment); 1083778fcc77SRafael Espindola if (NewGVar->isDeclaration() && ClearConstant) 1084778fcc77SRafael Espindola NewGVar->setConstant(false); 1085778fcc77SRafael Espindola } 1086778fcc77SRafael Espindola return DGV; 1087778fcc77SRafael Espindola } 1088778fcc77SRafael Espindola 1089b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1090b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1091b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1092778fcc77SRafael Espindola GlobalVariable *NewDGV = new GlobalVariable( 1093778fcc77SRafael Espindola *DstM, TypeMap.get(SGVar->getType()->getElementType()), 1094778fcc77SRafael Espindola SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 1095778fcc77SRafael Espindola SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 1096778fcc77SRafael Espindola SGVar->getType()->getAddressSpace()); 1097778fcc77SRafael Espindola 1098778fcc77SRafael Espindola if (Alignment) 1099fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 1100b1ed91f3SChris Lattner 1101778fcc77SRafael Espindola return NewDGV; 1102361e513dSReid Spencer } 1103361e513dSReid Spencer 110418c89411SRafael Espindola /// Link the function in the source module into the destination module if 110518c89411SRafael Espindola /// needed, setting up mapping information. 1106778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF, 1107778fcc77SRafael Espindola GlobalValue *DGV, 1108778fcc77SRafael Espindola bool LinkFromSrc) { 1109778fcc77SRafael Espindola if (!LinkFromSrc) 1110778fcc77SRafael Espindola return DGV; 1111b1ed91f3SChris Lattner 1112f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1113f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1114f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1115f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1116f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1117778fcc77SRafael Espindola return nullptr; 1118dad0a645SDavid Majnemer } 1119dad0a645SDavid Majnemer 1120b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1121b1ed91f3SChris Lattner // bring SF over. 1122778fcc77SRafael Espindola return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 1123778fcc77SRafael Espindola SF->getName(), DstM); 1124361e513dSReid Spencer } 1125361e513dSReid Spencer 112618c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 1127778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA, 1128778fcc77SRafael Espindola GlobalValue *DGV, 1129778fcc77SRafael Espindola bool LinkFromSrc) { 1130778fcc77SRafael Espindola if (!LinkFromSrc) 1131778fcc77SRafael Espindola return DGV; 1132dad0a645SDavid Majnemer 1133b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1134b1ed91f3SChris Lattner // bring over SGA. 11354fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1136778fcc77SRafael Espindola return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 113783705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1138b1ed91f3SChris Lattner } 1139b1ed91f3SChris Lattner 11403e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 11413e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 11426705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 114300245f42SChris Lattner 11446705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 11456705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 114600245f42SChris Lattner } 114700245f42SChris Lattner 1148b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1149b1ed91f3SChris Lattner // Merge the initializer. 1150d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1151d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1152b1ed91f3SChris Lattner 1153d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1154d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 115500245f42SChris Lattner 1156b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1157d31dc048SRafael Espindola 1158d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1159d31dc048SRafael Espindola bool IsNewStructor = 1160d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1161d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1162d31dc048SRafael Espindola 1163d31dc048SRafael Espindola for (auto *V : SrcElements) { 1164d31dc048SRafael Espindola if (IsNewStructor) { 1165d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1166d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1167d31dc048SRafael Espindola continue; 1168d31dc048SRafael Espindola } 1169d31dc048SRafael Espindola DstElements.push_back( 1170d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1171d31dc048SRafael Espindola } 1172d31dc048SRafael Espindola if (IsNewStructor) { 1173d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1174d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1175d31dc048SRafael Espindola } 1176d31dc048SRafael Espindola 1177d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1178b1ed91f3SChris Lattner } 1179b1ed91f3SChris Lattner 118018c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 118118c89411SRafael Espindola /// referenced are in Dest. 1182b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1183b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1184b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1185b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1186cbb91408STanya Lattner 1187cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1188cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1189b1ed91f3SChris Lattner 1190b1ed91f3SChris Lattner // Grab destination global variable. 1191b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1192b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1193b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1194f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1195b1ed91f3SChris Lattner } 1196b1ed91f3SChris Lattner } 1197b1ed91f3SChris Lattner 119818c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 119918c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 120018c89411SRafael Espindola /// that Src is not. 1201b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1202b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1203361e513dSReid Spencer 12047391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1205b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1206531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1207361e513dSReid Spencer I != E; ++I, ++DI) { 1208b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1209361e513dSReid Spencer 1210b1ed91f3SChris Lattner // Add a mapping to our mapping. 121166a6271cSAnton Korobeynikov ValueMap[I] = DI; 1212361e513dSReid Spencer } 1213361e513dSReid Spencer 12142f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1215b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1216361e513dSReid Spencer 1217361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1218361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1219361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 122043f8d164SChris Lattner // functions and patch them up to point to the local versions. 1221b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 122243f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 12239f8eff31SRafael Espindola RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 12249f8eff31SRafael Espindola &ValMaterializer); 1225cbb91408STanya Lattner 12267391dde1SChris Lattner // There is no need to map the arguments anymore. 122744ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 122844ab8aefSChris Lattner I != E; ++I) 12293aaaa0b2SReid Spencer ValueMap.erase(I); 1230cbb91408STanya Lattner 1231361e513dSReid Spencer } 1232361e513dSReid Spencer 123318c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module. 1234b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1235b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1236cbb91408STanya Lattner I != E; ++I) { 1237cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1238cbb91408STanya Lattner continue; 1239b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1240b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 12416b238633SRafael Espindola Constant *Val = 12426b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 124364c1e180SRafael Espindola DA->setAliasee(Val); 12442c4a34aeSDavid Chisnall } 1245b1ed91f3SChris Lattner } 1246cbb91408STanya Lattner } 1247b1ed91f3SChris Lattner 124818c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1249b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 125066f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1251b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1252b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 125366f02413SBill Wendling // Don't link module flags here. Do them separately. 125466f02413SBill Wendling if (&*I == SrcModFlags) continue; 1255b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1256b1ed91f3SChris Lattner // Add Src elements into Dest node. 1257b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1258b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1259f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1260b1ed91f3SChris Lattner } 1261b1ed91f3SChris Lattner } 1262b1ed91f3SChris Lattner 126318c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 126466f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 12650ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 126666f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 126766f02413SBill Wendling if (!SrcModFlags) return false; 126866f02413SBill Wendling 126966f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 127066f02413SBill Wendling // over the source module's flags. 12710ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 127266f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 127366f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 127466f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 127566f02413SBill Wendling 127666f02413SBill Wendling return false; 127766f02413SBill Wendling } 127866f02413SBill Wendling 12790ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 12800ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 12810ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 12820ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1283de36e804SDuncan P. N. Exon Smith MDNode *Op = DstModFlags->getOperand(I); 12840ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 12850ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 12860ec72bbcSDaniel Dunbar 12870ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 12880ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 12890ec72bbcSDaniel Dunbar } else { 12900ec72bbcSDaniel Dunbar Flags[ID] = Op; 12910ec72bbcSDaniel Dunbar } 12920ec72bbcSDaniel Dunbar } 12930ec72bbcSDaniel Dunbar 12940ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 12950ec72bbcSDaniel Dunbar // requirements. 129666f02413SBill Wendling bool HasErr = false; 12970ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1298de36e804SDuncan P. N. Exon Smith MDNode *SrcOp = SrcModFlags->getOperand(I); 12990ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 13000ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 13010ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 13020ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 130366f02413SBill Wendling 13040ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 13050ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 13060ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 13070ec72bbcSDaniel Dunbar // it. 13080ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 13090ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13100ec72bbcSDaniel Dunbar } 13110ec72bbcSDaniel Dunbar continue; 13120ec72bbcSDaniel Dunbar } 131366f02413SBill Wendling 13140ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 13150ec72bbcSDaniel Dunbar if (!DstOp) { 13160ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 13170ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13180ec72bbcSDaniel Dunbar continue; 13190ec72bbcSDaniel Dunbar } 132066f02413SBill Wendling 13210ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 13220ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 13230ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 13240ec72bbcSDaniel Dunbar 13250ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 13260ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 13270ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 13280ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 13290ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13300ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13310ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 13320ec72bbcSDaniel Dunbar } 13330ec72bbcSDaniel Dunbar continue; 13340ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 13350ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 13360ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 13370ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 13380ec72bbcSDaniel Dunbar continue; 13390ec72bbcSDaniel Dunbar } 13400ec72bbcSDaniel Dunbar 13410ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 13420ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 13430ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 134466f02413SBill Wendling "': IDs have conflicting behaviors"); 13450ec72bbcSDaniel Dunbar continue; 134666f02413SBill Wendling } 134766f02413SBill Wendling 13480ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 13490ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 13500ec72bbcSDaniel Dunbar case Module::Require: 13512a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 13520ec72bbcSDaniel Dunbar case Module::Error: { 13530ec72bbcSDaniel Dunbar // Emit an error if the values differ. 13540ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13550ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13560ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 135766f02413SBill Wendling } 13580ec72bbcSDaniel Dunbar continue; 135966f02413SBill Wendling } 13600ec72bbcSDaniel Dunbar case Module::Warning: { 13610ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 13620ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1363d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1364d12b4a33SRafael Espindola "': IDs have conflicting values"); 1365e17f3708SEli Bendersky } 13660ec72bbcSDaniel Dunbar continue; 13670ec72bbcSDaniel Dunbar } 1368d77d9fb0SDaniel Dunbar case Module::Append: { 1369d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1370d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1371d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1372d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1373d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1374d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1375d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1376d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1377d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1378d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1379d77d9fb0SDaniel Dunbar NumOps))); 1380d77d9fb0SDaniel Dunbar delete[] Values; 1381d77d9fb0SDaniel Dunbar break; 1382d77d9fb0SDaniel Dunbar } 1383d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1384d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1385d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1386d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1387d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1388d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1389d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1390d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1391d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1392d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1393d77d9fb0SDaniel Dunbar Elts.end()))); 1394d77d9fb0SDaniel Dunbar break; 1395d77d9fb0SDaniel Dunbar } 139666f02413SBill Wendling } 139766f02413SBill Wendling } 139866f02413SBill Wendling 13990ec72bbcSDaniel Dunbar // Check all of the requirements. 14000ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 14010ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 14020ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 14030ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 14040ec72bbcSDaniel Dunbar 14050ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 14060ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 14070ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 14089273b539SBill Wendling "': does not have the required value"); 14090ec72bbcSDaniel Dunbar continue; 141066f02413SBill Wendling } 141166f02413SBill Wendling } 141266f02413SBill Wendling 141366f02413SBill Wendling return HasErr; 141466f02413SBill Wendling } 141566f02413SBill Wendling 1416b1ed91f3SChris Lattner bool ModuleLinker::run() { 141766f02413SBill Wendling assert(DstM && "Null destination module"); 141866f02413SBill Wendling assert(SrcM && "Null source module"); 1419b1ed91f3SChris Lattner 1420b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1421b1ed91f3SChris Lattner // doesn't have one already. 1422f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1423b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1424b1ed91f3SChris Lattner 1425b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1426b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1427b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1428b1ed91f3SChris Lattner 1429f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1430ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1431d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1432d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1433d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1434d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1435d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1436e17f3708SEli Bendersky } 1437b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1438b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1439d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1440d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1441d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1442d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1443d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1444e17f3708SEli Bendersky } 1445b1ed91f3SChris Lattner 1446b1ed91f3SChris Lattner // Append the module inline asm string. 1447b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1448b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1449b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1450b1ed91f3SChris Lattner else 1451b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1452b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1453b1ed91f3SChris Lattner } 1454b1ed91f3SChris Lattner 1455b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1456b1ed91f3SChris Lattner computeTypeMapping(); 1457b1ed91f3SChris Lattner 1458dad0a645SDavid Majnemer ComdatsChosen.clear(); 14595106ce78SDavid Blaikie for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1460dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1461dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1462dad0a645SDavid Majnemer continue; 1463dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1464dad0a645SDavid Majnemer bool LinkFromSrc; 1465dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1466dad0a645SDavid Majnemer return true; 1467dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1468dad0a645SDavid Majnemer } 1469dad0a645SDavid Majnemer 147009d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 147109d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 147209d84addSDuncan P. N. Exon Smith 1473b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1474b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1475b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1476b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1477778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1478b1ed91f3SChris Lattner return true; 1479b1ed91f3SChris Lattner 1480b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1481b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1482b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1483b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1484b1ed91f3SChris Lattner // ValueMap. 1485b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1486778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1487b1ed91f3SChris Lattner return true; 1488b1ed91f3SChris Lattner 1489b1ed91f3SChris Lattner // If there were any aliases, link them now. 1490b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1491b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1492778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1493b1ed91f3SChris Lattner return true; 1494b1ed91f3SChris Lattner 1495b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1496b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1497b1ed91f3SChris Lattner 1498b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1499b1ed91f3SChris Lattner // DstM. 1500b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1501ea166d44STanya Lattner // Skip if not linking from source. 1502ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1503ea166d44STanya Lattner 15043fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 15053fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15063fa50f9bSPeter Collingbourne // Link in the prefix data. 15073fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 15083fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 15093fa50f9bSPeter Collingbourne } 15103fa50f9bSPeter Collingbourne 1511d4bcefc7SRafael Espindola // Materialize if needed. 1512d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1513d12b4a33SRafael Espindola return emitError(EC.message()); 1514b1ed91f3SChris Lattner 1515d4bcefc7SRafael Espindola // Skip if no body (function is external). 1516d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1517d4bcefc7SRafael Espindola continue; 1518d4bcefc7SRafael Espindola 15193fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 152000623787SBill Wendling SF->Dematerialize(); 1521b1ed91f3SChris Lattner } 1522b1ed91f3SChris Lattner 1523b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1524b1ed91f3SChris Lattner linkAliasBodies(); 1525b1ed91f3SChris Lattner 152666f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 15276ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 15286ddbb2e2SDevang Patel // are properly remapped. 15296ddbb2e2SDevang Patel linkNamedMDNodes(); 15306ddbb2e2SDevang Patel 153166f02413SBill Wendling // Merge the module flags into the DstM module. 153266f02413SBill Wendling if (linkModuleFlagsMetadata()) 153366f02413SBill Wendling return true; 153466f02413SBill Wendling 153591686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 153691686d6dSBill Wendling // be referenced are in DstM. 153791686d6dSBill Wendling linkGlobalInits(); 153891686d6dSBill Wendling 15390a48b877STanya Lattner // Process vector of lazily linked in functions. 15400a48b877STanya Lattner bool LinkedInAnyFunctions; 15410a48b877STanya Lattner do { 15420a48b877STanya Lattner LinkedInAnyFunctions = false; 15430a48b877STanya Lattner 1544fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 15450a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1546f6f121e2SJames Molloy Function *SF = *I; 1547f6f121e2SJames Molloy if (!SF) 15480a48b877STanya Lattner continue; 15490a48b877STanya Lattner 1550fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 15513fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15523fa50f9bSPeter Collingbourne // Link in the prefix data. 15533fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 15543fa50f9bSPeter Collingbourne ValueMap, 15553fa50f9bSPeter Collingbourne RF_None, 15563fa50f9bSPeter Collingbourne &TypeMap, 15573fa50f9bSPeter Collingbourne &ValMaterializer)); 15583fa50f9bSPeter Collingbourne } 15590a48b877STanya Lattner 1560d4bcefc7SRafael Espindola // Materialize if needed. 1561d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1562d12b4a33SRafael Espindola return emitError(EC.message()); 15630a48b877STanya Lattner 1564d4bcefc7SRafael Espindola // Skip if no body (function is external). 1565d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1566d4bcefc7SRafael Espindola continue; 1567d4bcefc7SRafael Espindola 1568f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1569f6f121e2SJames Molloy // invalidate I. 1570f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1571f6f121e2SJames Molloy 15720a48b877STanya Lattner // Link in function body. 15730a48b877STanya Lattner linkFunctionBody(DF, SF); 157400623787SBill Wendling SF->Dematerialize(); 15750a48b877STanya Lattner 15760a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 15770a48b877STanya Lattner // since we linked in a function. 15780a48b877STanya Lattner LinkedInAnyFunctions = true; 1579f6f121e2SJames Molloy break; 15800a48b877STanya Lattner } 15810a48b877STanya Lattner } while (LinkedInAnyFunctions); 15820a48b877STanya Lattner 15832609888fSAnton Korobeynikov return false; 15842609888fSAnton Korobeynikov } 1585361e513dSReid Spencer 15865cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15875cb9c82aSRafael Espindola this->Composite = M; 15885cb9c82aSRafael Espindola this->DiagnosticHandler = DiagnosticHandler; 1589a4e85e3dSRafael Espindola 1590a4e85e3dSRafael Espindola TypeFinder StructTypes; 1591a4e85e3dSRafael Espindola StructTypes.run(*M, true); 1592a4e85e3dSRafael Espindola IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1593aa9918aaSRafael Espindola } 15943df61b7bSRafael Espindola 15955cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15965cb9c82aSRafael Espindola init(M, DiagnosticHandler); 15975cb9c82aSRafael Espindola } 15985cb9c82aSRafael Espindola 15995cb9c82aSRafael Espindola Linker::Linker(Module *M) { 16005cb9c82aSRafael Espindola init(M, [this](const DiagnosticInfo &DI) { 16015cb9c82aSRafael Espindola Composite->getContext().diagnose(DI); 16025cb9c82aSRafael Espindola }); 16035cb9c82aSRafael Espindola } 16045cb9c82aSRafael Espindola 16053df61b7bSRafael Espindola Linker::~Linker() { 16063df61b7bSRafael Espindola } 16073df61b7bSRafael Espindola 160891e6f6e1SBill Wendling void Linker::deleteModule() { 160991e6f6e1SBill Wendling delete Composite; 16102617dcceSCraig Topper Composite = nullptr; 161191e6f6e1SBill Wendling } 161291e6f6e1SBill Wendling 16139f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 1614a4e85e3dSRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 1615a4e85e3dSRafael Espindola DiagnosticHandler); 1616d12b4a33SRafael Espindola return TheLinker.run(); 16173df61b7bSRafael Espindola } 16183df61b7bSRafael Espindola 1619b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1620b1ed91f3SChris Lattner // LinkModules entrypoint. 1621b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1622b1ed91f3SChris Lattner 162318c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 162418c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 162518c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 162618c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 162718c89411SRafael Espindola /// relied on to be consistent. 16289f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 16294160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 16304160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 16319f8eff31SRafael Espindola return L.linkInModule(Src); 16324160f5d3SRafael Espindola } 16334160f5d3SRafael Espindola 16349f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1635287f18b4SRafael Espindola Linker L(Dest); 16369f8eff31SRafael Espindola return L.linkInModule(Src); 1637361e513dSReid Spencer } 1638a3aeb980SBill Wendling 1639a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1640a3aeb980SBill Wendling // C API. 1641a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1642a3aeb980SBill Wendling 1643a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1644a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 164598ab63ceSRafael Espindola Module *D = unwrap(Dest); 164698ab63ceSRafael Espindola std::string Message; 16474160f5d3SRafael Espindola raw_string_ostream Stream(Message); 16484160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 16494160f5d3SRafael Espindola 16504160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 16519f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 165298ab63ceSRafael Espindola 165398ab63ceSRafael Espindola if (OutMessages && Result) 165498ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1655a3aeb980SBill Wendling return Result; 1656a3aeb980SBill Wendling } 1657