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: 61*04a74af7SRafael Espindola TypeMapTy() {} 62aa9918aaSRafael Espindola 6318c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6418c89411SRafael Espindola /// equivalent to the specified type in the source module. 65b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 66b1ed91f3SChris Lattner 67d2a13a2eSRafael Espindola /// Produce a body for an opaque type in the dest module from a type 68d2a13a2eSRafael Espindola /// definition in the source module. 69b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 70b1ed91f3SChris Lattner 7118c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 72b1ed91f3SChris Lattner /// source module. 73b1ed91f3SChris Lattner Type *get(Type *SrcTy); 74b1ed91f3SChris Lattner 75290e2cc5SRafael Espindola FunctionType *get(FunctionType *T) { 76290e2cc5SRafael Espindola return cast<FunctionType>(get((Type *)T)); 77290e2cc5SRafael Espindola } 78b1ed91f3SChris Lattner 7918c89411SRafael Espindola /// Dump out the type map for debugging purposes. 80b6af2f36SBill Wendling void dump() const { 818f14471eSRafael Espindola for (auto &Pair : MappedTypes) { 82b6af2f36SBill Wendling dbgs() << "TypeMap: "; 838f14471eSRafael Espindola Pair.first->print(dbgs()); 84b6af2f36SBill Wendling dbgs() << " => "; 858f14471eSRafael Espindola Pair.second->print(dbgs()); 86b6af2f36SBill Wendling dbgs() << '\n'; 87b6af2f36SBill Wendling } 88b6af2f36SBill Wendling } 89b6af2f36SBill Wendling 90b1ed91f3SChris Lattner private: 91290e2cc5SRafael Espindola Type *remapType(Type *SrcTy) override { return get(SrcTy); } 92b1ed91f3SChris Lattner 93b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 94b1ed91f3SChris Lattner }; 95b1ed91f3SChris Lattner } 96b1ed91f3SChris Lattner 97b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 983d097410SRafael Espindola assert(SpeculativeTypes.empty()); 99a96f235cSRafael Espindola assert(SpeculativeDstOpaqueTypes.empty()); 1003d097410SRafael Espindola 101b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 102b1ed91f3SChris Lattner // mapping between them if so. 103c586eaa1SDuncan P. N. Exon Smith if (!areTypesIsomorphic(DstTy, SrcTy)) { 104b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 105b1ed91f3SChris Lattner // any speculative mappings we've established. 1063d097410SRafael Espindola for (Type *Ty : SpeculativeTypes) 1073d097410SRafael Espindola MappedTypes.erase(Ty); 108a96f235cSRafael Espindola 109a96f235cSRafael Espindola SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - 110a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.size()); 111a96f235cSRafael Espindola for (StructType *Ty : SpeculativeDstOpaqueTypes) 112a96f235cSRafael Espindola DstResolvedOpaqueTypes.erase(Ty); 113*04a74af7SRafael Espindola } else { 114*04a74af7SRafael Espindola for (Type *Ty : SpeculativeTypes) 115*04a74af7SRafael Espindola if (auto *STy = dyn_cast<StructType>(Ty)) 116*04a74af7SRafael Espindola if (STy->hasName()) 117*04a74af7SRafael Espindola STy->setName(""); 118d48b7783SBill Wendling } 119b1ed91f3SChris Lattner SpeculativeTypes.clear(); 120a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.clear(); 121b1ed91f3SChris Lattner } 122b1ed91f3SChris Lattner 12318c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 12418c89411SRafael Espindola /// false if they are not. 125b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 126b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 127290e2cc5SRafael Espindola if (DstTy->getTypeID() != SrcTy->getTypeID()) 128290e2cc5SRafael Espindola return false; 129b1ed91f3SChris Lattner 130b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 131b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 132b1ed91f3SChris Lattner if (Entry) 133b1ed91f3SChris Lattner return Entry == DstTy; 134b1ed91f3SChris Lattner 135b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 136b1ed91f3SChris Lattner // non-speculatively. 137b1ed91f3SChris Lattner if (DstTy == SrcTy) { 138b1ed91f3SChris Lattner Entry = DstTy; 139361e513dSReid Spencer return true; 140361e513dSReid Spencer } 141361e513dSReid Spencer 142b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 143361e513dSReid Spencer 144b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 145b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 146b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 147b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 148b1ed91f3SChris Lattner Entry = DstTy; 149b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 150b1ed91f3SChris Lattner return true; 151361e513dSReid Spencer } 152b1ed91f3SChris Lattner 1535e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1545e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 155a96f235cSRafael Espindola // the dest, but fill it in later. If this is the second (different) type 156a96f235cSRafael Espindola // that we're trying to map onto the same opaque type then we fail. 157b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1585e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 15970573dcdSDavid Blaikie if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 1605e3bd972SChris Lattner return false; 1615e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 162a96f235cSRafael Espindola SpeculativeTypes.push_back(SrcTy); 163a96f235cSRafael Espindola SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); 164b1ed91f3SChris Lattner Entry = DstTy; 165b1ed91f3SChris Lattner return true; 166b1ed91f3SChris Lattner } 167b1ed91f3SChris Lattner } 168b1ed91f3SChris Lattner 169b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 170b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 171b1ed91f3SChris Lattner return false; 172b1ed91f3SChris Lattner 173b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 174b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 175b1ed91f3SChris Lattner return false; // bitwidth disagrees. 176b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 177b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 178b1ed91f3SChris Lattner return false; 179eaf9b762SChris Lattner 180b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 181b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 182b1ed91f3SChris Lattner return false; 183b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 184b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 18544f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 186b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 187b1ed91f3SChris Lattner return false; 188b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 189b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 190b1ed91f3SChris Lattner return false; 191b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1925fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 193361e513dSReid Spencer return false; 194361e513dSReid Spencer } 195361e513dSReid Spencer 196b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 197b1ed91f3SChris Lattner // check the subelements. 198b1ed91f3SChris Lattner Entry = DstTy; 199b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 200eee6f995SChris Lattner 201290e2cc5SRafael Espindola for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 202290e2cc5SRafael Espindola if (!areTypesIsomorphic(DstTy->getContainedType(I), 203290e2cc5SRafael Espindola SrcTy->getContainedType(I))) 204b1ed91f3SChris Lattner return false; 205eee6f995SChris Lattner 206b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 207eee6f995SChris Lattner return true; 208eee6f995SChris Lattner } 209eee6f995SChris Lattner 210b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 211b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 212c81c3f55SRafael Espindola for (StructType *SrcSTy : SrcDefinitionsToResolve) { 213b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 214c81c3f55SRafael Espindola assert(DstSTy->isOpaque()); 215b1ed91f3SChris Lattner 216b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 217b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 218290e2cc5SRafael Espindola for (unsigned I = 0, E = Elements.size(); I != E; ++I) 219c81c3f55SRafael Espindola Elements[I] = get(SrcSTy->getElementType(I)); 220b1ed91f3SChris Lattner 221b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 222b1ed91f3SChris Lattner } 223c81c3f55SRafael Espindola SrcDefinitionsToResolve.clear(); 2245e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 225eee6f995SChris Lattner } 226eee6f995SChris Lattner 227b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 228b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 229b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 230290e2cc5SRafael Espindola if (*Entry) 231290e2cc5SRafael Espindola return *Entry; 232b1ed91f3SChris Lattner 233b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 234b1ed91f3SChris Lattner // then rebuild the type from inside out. 23544f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 236b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 237b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 238b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 239b1ed91f3SChris Lattner return *Entry = Ty; 240b1ed91f3SChris Lattner 241b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 242b1ed91f3SChris Lattner bool AnyChange = false; 243b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 244b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 245290e2cc5SRafael Espindola for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 246c81c3f55SRafael Espindola ElementTypes[I] = get(Ty->getContainedType(I)); 247290e2cc5SRafael Espindola AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 248eee6f995SChris Lattner } 249b1ed91f3SChris Lattner 250b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 251b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 252290e2cc5SRafael Espindola if (*Entry) 253290e2cc5SRafael Espindola return *Entry; 254b1ed91f3SChris Lattner 255b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 256b1ed91f3SChris Lattner // as-is. 257b1ed91f3SChris Lattner if (!AnyChange) 258b1ed91f3SChris Lattner return *Entry = Ty; 259b1ed91f3SChris Lattner 260b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 261b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 262290e2cc5SRafael Espindola default: 263290e2cc5SRafael Espindola llvm_unreachable("unknown derived type to remap"); 264b1ed91f3SChris Lattner case Type::ArrayTyID: 265b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 266b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 267b1ed91f3SChris Lattner case Type::VectorTyID: 268b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 269b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 270b1ed91f3SChris Lattner case Type::PointerTyID: 271290e2cc5SRafael Espindola return *Entry = PointerType::get( 272290e2cc5SRafael Espindola ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace()); 273b1ed91f3SChris Lattner case Type::FunctionTyID: 274b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 275717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 276b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 277b1ed91f3SChris Lattner case Type::StructTyID: 278b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 279b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 280b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 281b1ed91f3SChris Lattner } 282b1ed91f3SChris Lattner } 283b1ed91f3SChris Lattner 284b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 285b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 286b1ed91f3SChris Lattner // module has something like: 287b1ed91f3SChris Lattner // %T = type {%T*, i32} 288b1ed91f3SChris Lattner // @GV = global %T* null 289b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 290b1ed91f3SChris Lattner // 291b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 292b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 293b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 294b1ed91f3SChris Lattner // %A = type { i32 } 295b1ed91f3SChris Lattner // and the source module has something like 296b1ed91f3SChris Lattner // %A' = type { i32 } 297b1ed91f3SChris Lattner // %B = type { %A'* } 298b1ed91f3SChris Lattner // @GV = global %B* null 299b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 300b1ed91f3SChris Lattner // pristine "%B" name from the source module. 301b1ed91f3SChris Lattner // 302b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 303b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 304b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 305b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 306b1ed91f3SChris Lattner // it and always rebuild a type here. 307b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 308b1ed91f3SChris Lattner 309b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 310aa9918aaSRafael Espindola if (STy->isOpaque()) { 311aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 312aa9918aaSRafael Espindola // identified structs in the destination module. 313b1ed91f3SChris Lattner return *Entry = STy; 314aa9918aaSRafael Espindola } 315b1ed91f3SChris Lattner 316c81c3f55SRafael Espindola // Otherwise we create a new type. 3175e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 318aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 319aa9918aaSRafael Espindola // identified structs in the destination module. 320c81c3f55SRafael Espindola *Entry = DTy; 321c81c3f55SRafael Espindola 322c81c3f55SRafael Espindola SmallVector<Type*, 4> ElementTypes; 323c81c3f55SRafael Espindola ElementTypes.resize(STy->getNumElements()); 324c81c3f55SRafael Espindola for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I) 325c81c3f55SRafael Espindola ElementTypes[I] = get(STy->getElementType(I)); 326c81c3f55SRafael Espindola DTy->setBody(ElementTypes, STy->isPacked()); 327c81c3f55SRafael Espindola 328c81c3f55SRafael Espindola // Steal STy's name. 329c81c3f55SRafael Espindola if (STy->hasName()) { 330c81c3f55SRafael Espindola SmallString<16> TmpName = STy->getName(); 331c81c3f55SRafael Espindola STy->setName(""); 332c81c3f55SRafael Espindola DTy->setName(TmpName); 333c81c3f55SRafael Espindola } 334c81c3f55SRafael Espindola 335c81c3f55SRafael Espindola return DTy; 336b1ed91f3SChris Lattner } 337b1ed91f3SChris Lattner 338b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 339b1ed91f3SChris Lattner // ModuleLinker implementation. 340b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 341b1ed91f3SChris Lattner 342b1ed91f3SChris Lattner namespace { 343f6f121e2SJames Molloy class ModuleLinker; 344f6f121e2SJames Molloy 34518c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 34618c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 34718c89411SRafael Espindola /// few get used. 348f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 349f6f121e2SJames Molloy TypeMapTy &TypeMap; 350f6f121e2SJames Molloy Module *DstM; 351f6f121e2SJames Molloy std::vector<Function *> &LazilyLinkFunctions; 352c84f608bSRafael Espindola 353f6f121e2SJames Molloy public: 354f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 355c84f608bSRafael Espindola std::vector<Function *> &LazilyLinkFunctions) 356c84f608bSRafael Espindola : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 357c84f608bSRafael Espindola LazilyLinkFunctions(LazilyLinkFunctions) {} 358f6f121e2SJames Molloy 3598548299aSCraig Topper Value *materializeValueFor(Value *V) override; 360f6f121e2SJames Molloy }; 361f6f121e2SJames Molloy 362d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 363d12b4a33SRafael Espindola const Twine &Msg; 364d12b4a33SRafael Espindola 365d12b4a33SRafael Espindola public: 366d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 367d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 368d12b4a33SRafael Espindola }; 369d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 370d12b4a33SRafael Espindola const Twine &Msg) 371d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 372d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 373d12b4a33SRafael Espindola 37418c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the 37518c89411SRafael Espindola /// entrypoint for this file. 376b1ed91f3SChris Lattner class ModuleLinker { 377b1ed91f3SChris Lattner Module *DstM, *SrcM; 378b1ed91f3SChris Lattner 379b1ed91f3SChris Lattner TypeMapTy TypeMap; 380f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 381b1ed91f3SChris Lattner 38218c89411SRafael Espindola /// Mapping of values from what they used to be in Src, to what they are now 38318c89411SRafael Espindola /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 38418c89411SRafael Espindola /// due to the use of Value handles which the Linker doesn't actually need, 38518c89411SRafael Espindola /// but this allows us to reuse the ValueMapper code. 386b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 387b1ed91f3SChris Lattner 388b1ed91f3SChris Lattner struct AppendingVarInfo { 389b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 3903e8bc6a8SRafael Espindola const Constant *DstInit; // Old initializer from dest module. 3913e8bc6a8SRafael Espindola const Constant *SrcInit; // Old initializer from src module. 392b1ed91f3SChris Lattner }; 393b1ed91f3SChris Lattner 394b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 395b1ed91f3SChris Lattner 396cbb91408STanya Lattner // Set of items not to link in from source. 397cbb91408STanya Lattner SmallPtrSet<const Value *, 16> DoNotLinkFromSource; 398cbb91408STanya Lattner 3990a48b877STanya Lattner // Vector of functions to lazily link in. 400fa228782SBill Wendling std::vector<Function *> LazilyLinkFunctions; 4010a48b877STanya Lattner 4024160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 4034160f5d3SRafael Espindola 404b1ed91f3SChris Lattner public: 405*04a74af7SRafael Espindola ModuleLinker(Module *dstM, Module *srcM, 4064160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 407*04a74af7SRafael Espindola : DstM(dstM), SrcM(srcM), 4089f8eff31SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), 4094160f5d3SRafael Espindola DiagnosticHandler(DiagnosticHandler) {} 410b1ed91f3SChris Lattner 411b1ed91f3SChris Lattner bool run(); 412b1ed91f3SChris Lattner 413b1ed91f3SChris Lattner private: 414d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 415d12b4a33SRafael Espindola const GlobalValue &Src); 416dbb0bd1aSRafael Espindola 417d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 418b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 4194160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 420b1ed91f3SChris Lattner return true; 421b1ed91f3SChris Lattner } 422b1ed91f3SChris Lattner 423d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 4244160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 425d12b4a33SRafael Espindola } 426d12b4a33SRafael Espindola 427dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 428dad0a645SDavid Majnemer const GlobalVariable *&GVar); 429dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 430dad0a645SDavid Majnemer Comdat::SelectionKind Src, 431dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 432dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 433dad0a645SDavid Majnemer bool &LinkFromSrc); 434dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 435dad0a645SDavid Majnemer ComdatsChosen; 436dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 437dad0a645SDavid Majnemer bool &LinkFromSrc); 438dad0a645SDavid Majnemer 43918c89411SRafael Espindola /// Given a global in the source module, return the global in the 44018c89411SRafael Espindola /// destination module that is being linked to, if any. 4413e8bc6a8SRafael Espindola GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 442b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 443b1ed91f3SChris Lattner // there is no name match-up going on. 444b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4452617dcceSCraig Topper return nullptr; 446b1ed91f3SChris Lattner 447b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 448b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 449c84f608bSRafael Espindola if (!DGV) 450c84f608bSRafael Espindola return nullptr; 451b1ed91f3SChris Lattner 452b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 453b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 454b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4552617dcceSCraig Topper return nullptr; 456b1ed91f3SChris Lattner 457b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 458b1ed91f3SChris Lattner return DGV; 459b1ed91f3SChris Lattner } 460b1ed91f3SChris Lattner 461b1ed91f3SChris Lattner void computeTypeMapping(); 462b1ed91f3SChris Lattner 46309d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 46409d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 46509d84addSDuncan P. N. Exon Smith 4663e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 4673e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 468778fcc77SRafael Espindola 469778fcc77SRafael Espindola bool linkGlobalValueProto(GlobalValue *GV); 470778fcc77SRafael Espindola GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar, 471778fcc77SRafael Espindola GlobalValue *DGV, bool LinkFromSrc); 472778fcc77SRafael Espindola GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV, 473778fcc77SRafael Espindola bool LinkFromSrc); 474778fcc77SRafael Espindola GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV, 475778fcc77SRafael Espindola bool LinkFromSrc); 476778fcc77SRafael Espindola 47766f02413SBill Wendling bool linkModuleFlagsMetadata(); 478b1ed91f3SChris Lattner 479b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 480b1ed91f3SChris Lattner void linkGlobalInits(); 481b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 482b1ed91f3SChris Lattner void linkAliasBodies(); 483b1ed91f3SChris Lattner void linkNamedMDNodes(); 484eee6f995SChris Lattner }; 485d48b7783SBill Wendling } 486d48b7783SBill Wendling 48718c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 48818c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 48918c89411SRafael Espindola /// to force this back. 490b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 491b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 492b1ed91f3SChris Lattner // there is nothing for us to do. 493b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 494b1ed91f3SChris Lattner return; 495b1ed91f3SChris Lattner 496b1ed91f3SChris Lattner Module *M = GV->getParent(); 497361e513dSReid Spencer 498361e513dSReid Spencer // If there is a conflict, rename the conflict. 499b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 5002a8d2e0eSChris Lattner GV->takeName(ConflictGV); 501361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 502b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 5032a8d2e0eSChris Lattner } else { 5042a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 5053aaaa0b2SReid Spencer } 5063aaaa0b2SReid Spencer } 5073aaaa0b2SReid Spencer 50818c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 50918c89411SRafael Espindola /// from the SrcGV to the DestGV. 510b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 511dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 51299e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 513a7d9c69cSRafael Espindola unsigned Alignment; 51499e05cf1SRafael Espindola if (DestGO) 51599e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 516a7d9c69cSRafael Espindola 517dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 518a7d9c69cSRafael Espindola 51999e05cf1SRafael Espindola if (DestGO) 52099e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 521b1ed91f3SChris Lattner 522b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 523361e513dSReid Spencer } 524361e513dSReid Spencer 52523f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 52623f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 52723f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 52823f8d64bSRafael Espindola return false; 52923f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 53023f8d64bSRafael Espindola return true; 53123f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 53223f8d64bSRafael Espindola return false; 53323f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 53423f8d64bSRafael Espindola return true; 53523f8d64bSRafael Espindola return false; 53623f8d64bSRafael Espindola } 53723f8d64bSRafael Espindola 538f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 539f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 540f6f121e2SJames Molloy if (!SF) 5412617dcceSCraig Topper return nullptr; 542f6f121e2SJames Molloy 543f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 544f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 545f6f121e2SJames Molloy copyGVAttributes(DF, SF); 546f6f121e2SJames Molloy 5473931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5483931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5493931c28bSRafael Espindola DF->setComdat(DC); 5503931c28bSRafael Espindola } 5513931c28bSRafael Espindola 552f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 553f6f121e2SJames Molloy return DF; 554f6f121e2SJames Molloy } 555f6f121e2SJames Molloy 556dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 557dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 558dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 559dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 560dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 561dad0a645SDavid Majnemer if (!GVal) 562dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 563dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 564dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 565dad0a645SDavid Majnemer } 566dad0a645SDavid Majnemer 567dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 568dad0a645SDavid Majnemer if (!GVar) 569dad0a645SDavid Majnemer return emitError( 570dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 571dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 572dad0a645SDavid Majnemer 573dad0a645SDavid Majnemer return false; 574dad0a645SDavid Majnemer } 575dad0a645SDavid Majnemer 576dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 577dad0a645SDavid Majnemer Comdat::SelectionKind Src, 578dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 579dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 580dad0a645SDavid Majnemer bool &LinkFromSrc) { 581dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 582dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 583dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 584dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 585dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 586dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 587dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 588dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 589dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 590dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 591dad0a645SDavid Majnemer else 592dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 593dad0a645SDavid Majnemer } else if (Src == Dst) { 594dad0a645SDavid Majnemer Result = Dst; 595dad0a645SDavid Majnemer } else { 596dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 597dad0a645SDavid Majnemer "': invalid selection kinds!"); 598dad0a645SDavid Majnemer } 599dad0a645SDavid Majnemer 600dad0a645SDavid Majnemer switch (Result) { 601dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 602dad0a645SDavid Majnemer // Go with Dst. 603dad0a645SDavid Majnemer LinkFromSrc = false; 604dad0a645SDavid Majnemer break; 605dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 606dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 607dad0a645SDavid Majnemer "': noduplicates has been violated!"); 608dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 609dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 610dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 611dad0a645SDavid Majnemer const GlobalVariable *DstGV; 612dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 613dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 614dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 615dad0a645SDavid Majnemer return true; 616dad0a645SDavid Majnemer 617dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 618dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 619dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 620dad0a645SDavid Majnemer return emitError( 621dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 622dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 623dad0a645SDavid Majnemer } 624dad0a645SDavid Majnemer uint64_t DstSize = 625dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 626dad0a645SDavid Majnemer uint64_t SrcSize = 627dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 628dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 629dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 630dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 631dad0a645SDavid Majnemer "': ExactMatch violated!"); 632dad0a645SDavid Majnemer LinkFromSrc = false; 633dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 634dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 635dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 636dad0a645SDavid Majnemer if (SrcSize != DstSize) 637dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 638dad0a645SDavid Majnemer "': SameSize violated!"); 639dad0a645SDavid Majnemer LinkFromSrc = false; 640dad0a645SDavid Majnemer } else { 641dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 642dad0a645SDavid Majnemer } 643dad0a645SDavid Majnemer break; 644dad0a645SDavid Majnemer } 645dad0a645SDavid Majnemer } 646dad0a645SDavid Majnemer 647dad0a645SDavid Majnemer return false; 648dad0a645SDavid Majnemer } 649dad0a645SDavid Majnemer 650dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 651dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 652dad0a645SDavid Majnemer bool &LinkFromSrc) { 653b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 654dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 655dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 656dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6572ef3f299SRafael Espindola 658b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 659b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 660b16196a3SRafael Espindola LinkFromSrc = true; 661b16196a3SRafael Espindola Result = SSK; 6622ef3f299SRafael Espindola return false; 663b16196a3SRafael Espindola } 6642ef3f299SRafael Espindola 665dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 666dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6672ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6682ef3f299SRafael Espindola LinkFromSrc); 669dad0a645SDavid Majnemer } 670f6f121e2SJames Molloy 671d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 672d12b4a33SRafael Espindola const GlobalValue &Dest, 673dbb0bd1aSRafael Espindola const GlobalValue &Src) { 674778fcc77SRafael Espindola // We always have to add Src if it has appending linkage. 675778fcc77SRafael Espindola if (Src.hasAppendingLinkage()) { 676778fcc77SRafael Espindola LinkFromSrc = true; 677778fcc77SRafael Espindola return false; 678778fcc77SRafael Espindola } 679778fcc77SRafael Espindola 680d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 681d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 682dbb0bd1aSRafael Espindola 683dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 684dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 685dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 686d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 687dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 688d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 689d12b4a33SRafael Espindola return false; 690d12b4a33SRafael Espindola } 691dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 692d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 693d12b4a33SRafael Espindola return false; 694dbb0bd1aSRafael Espindola } 695dbb0bd1aSRafael Espindola 696d12b4a33SRafael Espindola if (DestIsDeclaration) { 697dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 698d12b4a33SRafael Espindola LinkFromSrc = true; 699d12b4a33SRafael Espindola return false; 700d12b4a33SRafael Espindola } 701dbb0bd1aSRafael Espindola 7020910605aSRafael Espindola if (Src.hasCommonLinkage()) { 703d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 704d12b4a33SRafael Espindola LinkFromSrc = true; 7050910605aSRafael Espindola return false; 706d12b4a33SRafael Espindola } 707d12b4a33SRafael Espindola 708d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 709d12b4a33SRafael Espindola LinkFromSrc = false; 710d12b4a33SRafael Espindola return false; 711d12b4a33SRafael Espindola } 7120910605aSRafael Espindola 7130ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7140ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7150ae225b6SRafael Espindola 7160910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7170910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 718d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 719d12b4a33SRafael Espindola return false; 7200910605aSRafael Espindola } 7210910605aSRafael Espindola 722dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 723dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 724dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7250910605aSRafael Espindola 726d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 727d12b4a33SRafael Espindola LinkFromSrc = true; 728d12b4a33SRafael Espindola return false; 729d12b4a33SRafael Espindola } 730dbb0bd1aSRafael Espindola 731d12b4a33SRafael Espindola LinkFromSrc = false; 7320910605aSRafael Espindola return false; 733dbb0bd1aSRafael Espindola } 734dbb0bd1aSRafael Espindola 735dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 736dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 737d12b4a33SRafael Espindola LinkFromSrc = true; 738d12b4a33SRafael Espindola return false; 739dbb0bd1aSRafael Espindola } 740dbb0bd1aSRafael Espindola 741dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 742dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 743dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 744dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 745dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 746dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 747dbb0bd1aSRafael Espindola } 748dbb0bd1aSRafael Espindola 74918c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 75018c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 75118c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 75218c89411SRafael Espindola /// LLVMContext. 753b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 754c8a476eeSRafael Espindola for (GlobalValue &SGV : SrcM->globals()) { 755c8a476eeSRafael Espindola GlobalValue *DGV = getLinkedToGlobal(&SGV); 756c8a476eeSRafael Espindola if (!DGV) 757c8a476eeSRafael Espindola continue; 758b1ed91f3SChris Lattner 759c8a476eeSRafael Espindola if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 760c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 761b1ed91f3SChris Lattner continue; 7625c310be0SDevang Patel } 7635c310be0SDevang Patel 764b1ed91f3SChris Lattner // Unify the element type of appending arrays. 765b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 766c8a476eeSRafael Espindola ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 767b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 768b1ed91f3SChris Lattner } 76934fc5a0eSChris Lattner 770c8a476eeSRafael Espindola for (GlobalValue &SGV : *SrcM) { 771c8a476eeSRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 772c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 773b1ed91f3SChris Lattner } 774e79f4c77SAnton Korobeynikov 775e96d7eb8SRafael Espindola for (GlobalValue &SGV : SrcM->aliases()) { 776e96d7eb8SRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 777e96d7eb8SRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 778e96d7eb8SRafael Espindola } 779e96d7eb8SRafael Espindola 780d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 781d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 7822b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 7832b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 7848555a37cSBill Wendling TypeFinder SrcStructTypes; 7858555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 7862b3f61afSBill Wendling SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 7872b3f61afSBill Wendling SrcStructTypes.end()); 7882b3f61afSBill Wendling 7892b3f61afSBill Wendling for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 7902b3f61afSBill Wendling StructType *ST = SrcStructTypes[i]; 7912b3f61afSBill Wendling if (!ST->hasName()) continue; 7922b3f61afSBill Wendling 7932b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 794d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 795d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 79683c74e9fSGuy Benyei ST->getName().back() == '.' || 79783c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 798d48b7783SBill Wendling continue; 7992b3f61afSBill Wendling 8002b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 801d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 8022b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 8038737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 8048737480dSBill Wendling // actually used in the destination module. This can happen in situations 8058737480dSBill Wendling // like this: 8068737480dSBill Wendling // 8078737480dSBill Wendling // Module A Module B 8088737480dSBill Wendling // -------- -------- 8098737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 8108737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 8118737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8128737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8138737480dSBill Wendling // 8148737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8158737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8168737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8178737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8188737480dSBill Wendling // variables using one type and some using the other. 819*04a74af7SRafael Espindola if (!SrcStructTypesSet.count(DST)) 8202b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8212b3f61afSBill Wendling } 8222b3f61afSBill Wendling 823b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 824b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 825b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 826b1ed91f3SChris Lattner } 827c08e7a00SChris Lattner 82809d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 82909d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 83009d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 83109d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 83209d84addSDuncan P. N. Exon Smith 83309d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 83409d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 83509d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 83609d84addSDuncan P. N. Exon Smith VoidPtrTy}; 83709d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 83809d84addSDuncan P. N. Exon Smith 83909d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 84009d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 84109d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 84209d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 84309d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 84409d84addSDuncan P. N. Exon Smith return; 84509d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 84609d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 84709d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 84809d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 84909d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 85009d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 85109d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 85209d84addSDuncan P. N. Exon Smith } 85309d84addSDuncan P. N. Exon Smith } 85409d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 85509d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 85609d84addSDuncan P. N. Exon Smith 85709d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 85809d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 85909d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 86009d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 86109d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 86209d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 86309d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 86409d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 86509d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 86609d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 86709d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 86809d84addSDuncan P. N. Exon Smith } 86909d84addSDuncan P. N. Exon Smith 87009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 87109d84addSDuncan P. N. Exon Smith // Look for the global arrays. 87209d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 87309d84addSDuncan P. N. Exon Smith if (!DstGV) 87409d84addSDuncan P. N. Exon Smith return; 87509d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 87609d84addSDuncan P. N. Exon Smith if (!SrcGV) 87709d84addSDuncan P. N. Exon Smith return; 87809d84addSDuncan P. N. Exon Smith 87909d84addSDuncan P. N. Exon Smith // Check if the types already match. 88009d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 88109d84addSDuncan P. N. Exon Smith auto *SrcTy = 88209d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 88309d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 88409d84addSDuncan P. N. Exon Smith return; 88509d84addSDuncan P. N. Exon Smith 88609d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 88709d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 88809d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 88909d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 89009d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 89109d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 89209d84addSDuncan P. N. Exon Smith return; 89309d84addSDuncan P. N. Exon Smith } 89409d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 89509d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 89609d84addSDuncan P. N. Exon Smith 89709d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 89809d84addSDuncan P. N. Exon Smith } 89909d84addSDuncan P. N. Exon Smith 90009d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 90109d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 90209d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 90309d84addSDuncan P. N. Exon Smith } 90409d84addSDuncan P. N. Exon Smith 90518c89411SRafael Espindola /// If there were any appending global variables, link them together now. 90618c89411SRafael Espindola /// Return true on error. 907b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 9083e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 909d48b7783SBill Wendling 910b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 911b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 912b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 913361e513dSReid Spencer 914b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 915b1ed91f3SChris Lattner ArrayType *SrcTy = 916b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 917b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 918b1ed91f3SChris Lattner 919b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 920b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 921b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 922b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 923b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 924b1ed91f3SChris Lattner 925b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 926b1ed91f3SChris Lattner return emitError( 927b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 928b1ed91f3SChris Lattner 929b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 930b1ed91f3SChris Lattner return emitError( 931b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 932b1ed91f3SChris Lattner 933fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 934fac3a018SRafael Espindola return emitError( 935fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 936fac3a018SRafael Espindola 93764c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 938b1ed91f3SChris Lattner return emitError( 939b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 940b1ed91f3SChris Lattner 941b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 942b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 943b1ed91f3SChris Lattner 944b1ed91f3SChris Lattner // Create the new global variable. 945b1ed91f3SChris Lattner GlobalVariable *NG = 946b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9472617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 948cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 949b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 950b1ed91f3SChris Lattner 951b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 952b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 953b1ed91f3SChris Lattner 954b1ed91f3SChris Lattner AppendingVarInfo AVI; 955b1ed91f3SChris Lattner AVI.NewGV = NG; 956b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 957b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 958b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 959b1ed91f3SChris Lattner 960b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 961b1ed91f3SChris Lattner // global. 962b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 963b1ed91f3SChris Lattner 964b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 965b1ed91f3SChris Lattner DstGV->eraseFromParent(); 966b1ed91f3SChris Lattner 967cbb91408STanya Lattner // Track the source variable so we don't try to link it. 968cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 969cbb91408STanya Lattner 970b1ed91f3SChris Lattner return false; 971b1ed91f3SChris Lattner } 972b1ed91f3SChris Lattner 973778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 974b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 975b1ed91f3SChris Lattner 976778fcc77SRafael Espindola // Handle the ultra special appending linkage case first. 977778fcc77SRafael Espindola if (DGV && DGV->hasAppendingLinkage()) 978778fcc77SRafael Espindola return linkAppendingVarProto(cast<GlobalVariable>(DGV), 979778fcc77SRafael Espindola cast<GlobalVariable>(SGV)); 980778fcc77SRafael Espindola 981778fcc77SRafael Espindola bool LinkFromSrc = true; 982778fcc77SRafael Espindola Comdat *C = nullptr; 983778fcc77SRafael Espindola GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 984778fcc77SRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 985778fcc77SRafael Espindola 986dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 987dad0a645SDavid Majnemer Comdat::SelectionKind SK; 988dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 989778fcc77SRafael Espindola C = DstM->getOrInsertComdat(SC->getName()); 990778fcc77SRafael Espindola C->setSelectionKind(SK); 991778fcc77SRafael Espindola } else if (DGV) { 992778fcc77SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 993fc61de39SChris Lattner return true; 994dad0a645SDavid Majnemer } 99534fc5a0eSChris Lattner 996dad0a645SDavid Majnemer if (!LinkFromSrc) { 997cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 998cbb91408STanya Lattner // processing global initializers. 999cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 1000cbb91408STanya Lattner 1001778fcc77SRafael Espindola if (DGV) 1002778fcc77SRafael Espindola // Make sure to remember this mapping. 1003778fcc77SRafael Espindola ValueMap[SGV] = 1004778fcc77SRafael Espindola ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 1005778fcc77SRafael Espindola } 1006778fcc77SRafael Espindola 1007778fcc77SRafael Espindola if (DGV) { 1008778fcc77SRafael Espindola Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 1009778fcc77SRafael Espindola ? DGV->getVisibility() 1010778fcc77SRafael Espindola : Visibility; 1011778fcc77SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1012778fcc77SRafael Espindola } 1013778fcc77SRafael Espindola 1014778fcc77SRafael Espindola if (!LinkFromSrc && !DGV) 1015dad0a645SDavid Majnemer return false; 1016778fcc77SRafael Espindola 1017778fcc77SRafael Espindola GlobalValue *NewGV; 1018778fcc77SRafael Espindola if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { 1019778fcc77SRafael Espindola NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc); 1020778fcc77SRafael Espindola if (!NewGV) 1021778fcc77SRafael Espindola return true; 1022778fcc77SRafael Espindola } else if (auto *SF = dyn_cast<Function>(SGV)) { 1023778fcc77SRafael Espindola NewGV = linkFunctionProto(SF, DGV, LinkFromSrc); 1024778fcc77SRafael Espindola } else { 1025778fcc77SRafael Espindola NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc); 1026778fcc77SRafael Espindola } 1027778fcc77SRafael Espindola 1028778fcc77SRafael Espindola if (NewGV) { 1029778fcc77SRafael Espindola if (NewGV != DGV) 1030778fcc77SRafael Espindola copyGVAttributes(NewGV, SGV); 1031778fcc77SRafael Espindola 1032778fcc77SRafael Espindola NewGV->setUnnamedAddr(HasUnnamedAddr); 1033778fcc77SRafael Espindola NewGV->setVisibility(Visibility); 1034778fcc77SRafael Espindola 1035778fcc77SRafael Espindola if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1036778fcc77SRafael Espindola if (C) 1037778fcc77SRafael Espindola NewGO->setComdat(C); 1038778fcc77SRafael Espindola } 1039778fcc77SRafael Espindola 1040778fcc77SRafael Espindola // Make sure to remember this mapping. 1041778fcc77SRafael Espindola if (NewGV != DGV) { 1042778fcc77SRafael Espindola if (DGV) { 1043778fcc77SRafael Espindola DGV->replaceAllUsesWith( 1044778fcc77SRafael Espindola ConstantExpr::getBitCast(NewGV, DGV->getType())); 1045778fcc77SRafael Espindola DGV->eraseFromParent(); 1046778fcc77SRafael Espindola } 1047778fcc77SRafael Espindola ValueMap[SGV] = NewGV; 1048dad0a645SDavid Majnemer } 10494e27567aSRafael Espindola } 10504e27567aSRafael Espindola 1051fd38af2dSChandler Carruth return false; 10524e27567aSRafael Espindola } 10534e27567aSRafael Espindola 1054778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the 1055778fcc77SRafael Espindola /// dest module. 1056778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar, 1057778fcc77SRafael Espindola GlobalValue *DGV, 1058778fcc77SRafael Espindola bool LinkFromSrc) { 1059778fcc77SRafael Espindola unsigned Alignment = 0; 1060778fcc77SRafael Espindola bool ClearConstant = false; 1061778fcc77SRafael Espindola 1062778fcc77SRafael Espindola if (DGV) { 1063778fcc77SRafael Espindola if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage()) 1064778fcc77SRafael Espindola Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment()); 1065778fcc77SRafael Espindola 1066778fcc77SRafael Espindola auto *DGVar = dyn_cast<GlobalVariable>(DGV); 1067778fcc77SRafael Espindola if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant())) 1068778fcc77SRafael Espindola ClearConstant = true; 1069778fcc77SRafael Espindola } 1070778fcc77SRafael Espindola 1071778fcc77SRafael Espindola if (!LinkFromSrc) { 1072778fcc77SRafael Espindola if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) { 1073778fcc77SRafael Espindola if (Alignment) 1074778fcc77SRafael Espindola NewGVar->setAlignment(Alignment); 1075778fcc77SRafael Espindola if (NewGVar->isDeclaration() && ClearConstant) 1076778fcc77SRafael Espindola NewGVar->setConstant(false); 1077778fcc77SRafael Espindola } 1078778fcc77SRafael Espindola return DGV; 1079778fcc77SRafael Espindola } 1080778fcc77SRafael Espindola 1081b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1082b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1083b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1084778fcc77SRafael Espindola GlobalVariable *NewDGV = new GlobalVariable( 1085778fcc77SRafael Espindola *DstM, TypeMap.get(SGVar->getType()->getElementType()), 1086778fcc77SRafael Espindola SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 1087778fcc77SRafael Espindola SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 1088778fcc77SRafael Espindola SGVar->getType()->getAddressSpace()); 1089778fcc77SRafael Espindola 1090778fcc77SRafael Espindola if (Alignment) 1091fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 1092b1ed91f3SChris Lattner 1093778fcc77SRafael Espindola return NewDGV; 1094361e513dSReid Spencer } 1095361e513dSReid Spencer 109618c89411SRafael Espindola /// Link the function in the source module into the destination module if 109718c89411SRafael Espindola /// needed, setting up mapping information. 1098778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF, 1099778fcc77SRafael Espindola GlobalValue *DGV, 1100778fcc77SRafael Espindola bool LinkFromSrc) { 1101778fcc77SRafael Espindola if (!LinkFromSrc) 1102778fcc77SRafael Espindola return DGV; 1103b1ed91f3SChris Lattner 1104f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1105f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1106f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1107f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1108f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1109778fcc77SRafael Espindola return nullptr; 1110dad0a645SDavid Majnemer } 1111dad0a645SDavid Majnemer 1112b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1113b1ed91f3SChris Lattner // bring SF over. 1114778fcc77SRafael Espindola return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 1115778fcc77SRafael Espindola SF->getName(), DstM); 1116361e513dSReid Spencer } 1117361e513dSReid Spencer 111818c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 1119778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA, 1120778fcc77SRafael Espindola GlobalValue *DGV, 1121778fcc77SRafael Espindola bool LinkFromSrc) { 1122778fcc77SRafael Espindola if (!LinkFromSrc) 1123778fcc77SRafael Espindola return DGV; 1124dad0a645SDavid Majnemer 1125b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1126b1ed91f3SChris Lattner // bring over SGA. 11274fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1128778fcc77SRafael Espindola return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 112983705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1130b1ed91f3SChris Lattner } 1131b1ed91f3SChris Lattner 11323e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 11333e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 11346705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 113500245f42SChris Lattner 11366705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 11376705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 113800245f42SChris Lattner } 113900245f42SChris Lattner 1140b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1141b1ed91f3SChris Lattner // Merge the initializer. 1142d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1143d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1144b1ed91f3SChris Lattner 1145d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1146d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 114700245f42SChris Lattner 1148b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1149d31dc048SRafael Espindola 1150d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1151d31dc048SRafael Espindola bool IsNewStructor = 1152d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1153d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1154d31dc048SRafael Espindola 1155d31dc048SRafael Espindola for (auto *V : SrcElements) { 1156d31dc048SRafael Espindola if (IsNewStructor) { 1157d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1158d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1159d31dc048SRafael Espindola continue; 1160d31dc048SRafael Espindola } 1161d31dc048SRafael Espindola DstElements.push_back( 1162d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1163d31dc048SRafael Espindola } 1164d31dc048SRafael Espindola if (IsNewStructor) { 1165d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1166d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1167d31dc048SRafael Espindola } 1168d31dc048SRafael Espindola 1169d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1170b1ed91f3SChris Lattner } 1171b1ed91f3SChris Lattner 117218c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 117318c89411SRafael Espindola /// referenced are in Dest. 1174b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1175b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1176b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1177b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1178cbb91408STanya Lattner 1179cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1180cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1181b1ed91f3SChris Lattner 1182b1ed91f3SChris Lattner // Grab destination global variable. 1183b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1184b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1185b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1186f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1187b1ed91f3SChris Lattner } 1188b1ed91f3SChris Lattner } 1189b1ed91f3SChris Lattner 119018c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 119118c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 119218c89411SRafael Espindola /// that Src is not. 1193b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1194b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1195361e513dSReid Spencer 11967391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1197b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1198531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1199361e513dSReid Spencer I != E; ++I, ++DI) { 1200b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1201361e513dSReid Spencer 1202b1ed91f3SChris Lattner // Add a mapping to our mapping. 120366a6271cSAnton Korobeynikov ValueMap[I] = DI; 1204361e513dSReid Spencer } 1205361e513dSReid Spencer 12062f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1207b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1208361e513dSReid Spencer 1209361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1210361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1211361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 121243f8d164SChris Lattner // functions and patch them up to point to the local versions. 1213b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 121443f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 12159f8eff31SRafael Espindola RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 12169f8eff31SRafael Espindola &ValMaterializer); 1217cbb91408STanya Lattner 12187391dde1SChris Lattner // There is no need to map the arguments anymore. 121944ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 122044ab8aefSChris Lattner I != E; ++I) 12213aaaa0b2SReid Spencer ValueMap.erase(I); 1222cbb91408STanya Lattner 1223361e513dSReid Spencer } 1224361e513dSReid Spencer 122518c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module. 1226b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1227b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1228cbb91408STanya Lattner I != E; ++I) { 1229cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1230cbb91408STanya Lattner continue; 1231b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1232b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 12336b238633SRafael Espindola Constant *Val = 12346b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 123564c1e180SRafael Espindola DA->setAliasee(Val); 12362c4a34aeSDavid Chisnall } 1237b1ed91f3SChris Lattner } 1238cbb91408STanya Lattner } 1239b1ed91f3SChris Lattner 124018c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1241b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 124266f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1243b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1244b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 124566f02413SBill Wendling // Don't link module flags here. Do them separately. 124666f02413SBill Wendling if (&*I == SrcModFlags) continue; 1247b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1248b1ed91f3SChris Lattner // Add Src elements into Dest node. 1249b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1250b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1251f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1252b1ed91f3SChris Lattner } 1253b1ed91f3SChris Lattner } 1254b1ed91f3SChris Lattner 125518c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 125666f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 12570ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 125866f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 125966f02413SBill Wendling if (!SrcModFlags) return false; 126066f02413SBill Wendling 126166f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 126266f02413SBill Wendling // over the source module's flags. 12630ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 126466f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 126566f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 126666f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 126766f02413SBill Wendling 126866f02413SBill Wendling return false; 126966f02413SBill Wendling } 127066f02413SBill Wendling 12710ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 12720ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 12730ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 12740ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1275de36e804SDuncan P. N. Exon Smith MDNode *Op = DstModFlags->getOperand(I); 12760ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 12770ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 12780ec72bbcSDaniel Dunbar 12790ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 12800ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 12810ec72bbcSDaniel Dunbar } else { 12820ec72bbcSDaniel Dunbar Flags[ID] = Op; 12830ec72bbcSDaniel Dunbar } 12840ec72bbcSDaniel Dunbar } 12850ec72bbcSDaniel Dunbar 12860ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 12870ec72bbcSDaniel Dunbar // requirements. 128866f02413SBill Wendling bool HasErr = false; 12890ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1290de36e804SDuncan P. N. Exon Smith MDNode *SrcOp = SrcModFlags->getOperand(I); 12910ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 12920ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 12930ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 12940ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 129566f02413SBill Wendling 12960ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 12970ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 12980ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 12990ec72bbcSDaniel Dunbar // it. 13000ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 13010ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13020ec72bbcSDaniel Dunbar } 13030ec72bbcSDaniel Dunbar continue; 13040ec72bbcSDaniel Dunbar } 130566f02413SBill Wendling 13060ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 13070ec72bbcSDaniel Dunbar if (!DstOp) { 13080ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 13090ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 13100ec72bbcSDaniel Dunbar continue; 13110ec72bbcSDaniel Dunbar } 131266f02413SBill Wendling 13130ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 13140ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 13150ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 13160ec72bbcSDaniel Dunbar 13170ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 13180ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 13190ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 13200ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 13210ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13220ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13230ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 13240ec72bbcSDaniel Dunbar } 13250ec72bbcSDaniel Dunbar continue; 13260ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 13270ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 13280ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 13290ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 13300ec72bbcSDaniel Dunbar continue; 13310ec72bbcSDaniel Dunbar } 13320ec72bbcSDaniel Dunbar 13330ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 13340ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 13350ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 133666f02413SBill Wendling "': IDs have conflicting behaviors"); 13370ec72bbcSDaniel Dunbar continue; 133866f02413SBill Wendling } 133966f02413SBill Wendling 13400ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 13410ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 13420ec72bbcSDaniel Dunbar case Module::Require: 13432a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 13440ec72bbcSDaniel Dunbar case Module::Error: { 13450ec72bbcSDaniel Dunbar // Emit an error if the values differ. 13460ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13470ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13480ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 134966f02413SBill Wendling } 13500ec72bbcSDaniel Dunbar continue; 135166f02413SBill Wendling } 13520ec72bbcSDaniel Dunbar case Module::Warning: { 13530ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 13540ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1355d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1356d12b4a33SRafael Espindola "': IDs have conflicting values"); 1357e17f3708SEli Bendersky } 13580ec72bbcSDaniel Dunbar continue; 13590ec72bbcSDaniel Dunbar } 1360d77d9fb0SDaniel Dunbar case Module::Append: { 1361d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1362d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1363d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1364d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1365d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1366d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1367d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1368d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1369d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1370d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1371d77d9fb0SDaniel Dunbar NumOps))); 1372d77d9fb0SDaniel Dunbar delete[] Values; 1373d77d9fb0SDaniel Dunbar break; 1374d77d9fb0SDaniel Dunbar } 1375d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1376d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1377d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1378d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1379d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1380d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1381d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1382d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1383d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1384d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1385d77d9fb0SDaniel Dunbar Elts.end()))); 1386d77d9fb0SDaniel Dunbar break; 1387d77d9fb0SDaniel Dunbar } 138866f02413SBill Wendling } 138966f02413SBill Wendling } 139066f02413SBill Wendling 13910ec72bbcSDaniel Dunbar // Check all of the requirements. 13920ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 13930ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 13940ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 13950ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 13960ec72bbcSDaniel Dunbar 13970ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 13980ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 13990ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 14009273b539SBill Wendling "': does not have the required value"); 14010ec72bbcSDaniel Dunbar continue; 140266f02413SBill Wendling } 140366f02413SBill Wendling } 140466f02413SBill Wendling 140566f02413SBill Wendling return HasErr; 140666f02413SBill Wendling } 140766f02413SBill Wendling 1408b1ed91f3SChris Lattner bool ModuleLinker::run() { 140966f02413SBill Wendling assert(DstM && "Null destination module"); 141066f02413SBill Wendling assert(SrcM && "Null source module"); 1411b1ed91f3SChris Lattner 1412b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1413b1ed91f3SChris Lattner // doesn't have one already. 1414f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1415b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1416b1ed91f3SChris Lattner 1417b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1418b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1419b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1420b1ed91f3SChris Lattner 1421f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1422ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1423d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1424d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1425d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1426d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1427d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1428e17f3708SEli Bendersky } 1429b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1430b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1431d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1432d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1433d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1434d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1435d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1436e17f3708SEli Bendersky } 1437b1ed91f3SChris Lattner 1438b1ed91f3SChris Lattner // Append the module inline asm string. 1439b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1440b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1441b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1442b1ed91f3SChris Lattner else 1443b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1444b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1445b1ed91f3SChris Lattner } 1446b1ed91f3SChris Lattner 1447b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1448b1ed91f3SChris Lattner computeTypeMapping(); 1449b1ed91f3SChris Lattner 1450dad0a645SDavid Majnemer ComdatsChosen.clear(); 14515106ce78SDavid Blaikie for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1452dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1453dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1454dad0a645SDavid Majnemer continue; 1455dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1456dad0a645SDavid Majnemer bool LinkFromSrc; 1457dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1458dad0a645SDavid Majnemer return true; 1459dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1460dad0a645SDavid Majnemer } 1461dad0a645SDavid Majnemer 146209d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 146309d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 146409d84addSDuncan P. N. Exon Smith 1465b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1466b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1467b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1468b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1469778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1470b1ed91f3SChris Lattner return true; 1471b1ed91f3SChris Lattner 1472b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1473b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1474b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1475b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1476b1ed91f3SChris Lattner // ValueMap. 1477b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1478778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1479b1ed91f3SChris Lattner return true; 1480b1ed91f3SChris Lattner 1481b1ed91f3SChris Lattner // If there were any aliases, link them now. 1482b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1483b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1484778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1485b1ed91f3SChris Lattner return true; 1486b1ed91f3SChris Lattner 1487b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1488b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1489b1ed91f3SChris Lattner 1490b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1491b1ed91f3SChris Lattner // DstM. 1492b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1493ea166d44STanya Lattner // Skip if not linking from source. 1494ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1495ea166d44STanya Lattner 14963fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 14973fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 14983fa50f9bSPeter Collingbourne // Link in the prefix data. 14993fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 15003fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 15013fa50f9bSPeter Collingbourne } 15023fa50f9bSPeter Collingbourne 1503d4bcefc7SRafael Espindola // Materialize if needed. 1504d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1505d12b4a33SRafael Espindola return emitError(EC.message()); 1506b1ed91f3SChris Lattner 1507d4bcefc7SRafael Espindola // Skip if no body (function is external). 1508d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1509d4bcefc7SRafael Espindola continue; 1510d4bcefc7SRafael Espindola 15113fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 151200623787SBill Wendling SF->Dematerialize(); 1513b1ed91f3SChris Lattner } 1514b1ed91f3SChris Lattner 1515b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1516b1ed91f3SChris Lattner linkAliasBodies(); 1517b1ed91f3SChris Lattner 151866f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 15196ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 15206ddbb2e2SDevang Patel // are properly remapped. 15216ddbb2e2SDevang Patel linkNamedMDNodes(); 15226ddbb2e2SDevang Patel 152366f02413SBill Wendling // Merge the module flags into the DstM module. 152466f02413SBill Wendling if (linkModuleFlagsMetadata()) 152566f02413SBill Wendling return true; 152666f02413SBill Wendling 152791686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 152891686d6dSBill Wendling // be referenced are in DstM. 152991686d6dSBill Wendling linkGlobalInits(); 153091686d6dSBill Wendling 15310a48b877STanya Lattner // Process vector of lazily linked in functions. 15320a48b877STanya Lattner bool LinkedInAnyFunctions; 15330a48b877STanya Lattner do { 15340a48b877STanya Lattner LinkedInAnyFunctions = false; 15350a48b877STanya Lattner 1536fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 15370a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1538f6f121e2SJames Molloy Function *SF = *I; 1539f6f121e2SJames Molloy if (!SF) 15400a48b877STanya Lattner continue; 15410a48b877STanya Lattner 1542fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 15433fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15443fa50f9bSPeter Collingbourne // Link in the prefix data. 15453fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 15463fa50f9bSPeter Collingbourne ValueMap, 15473fa50f9bSPeter Collingbourne RF_None, 15483fa50f9bSPeter Collingbourne &TypeMap, 15493fa50f9bSPeter Collingbourne &ValMaterializer)); 15503fa50f9bSPeter Collingbourne } 15510a48b877STanya Lattner 1552d4bcefc7SRafael Espindola // Materialize if needed. 1553d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1554d12b4a33SRafael Espindola return emitError(EC.message()); 15550a48b877STanya Lattner 1556d4bcefc7SRafael Espindola // Skip if no body (function is external). 1557d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1558d4bcefc7SRafael Espindola continue; 1559d4bcefc7SRafael Espindola 1560f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1561f6f121e2SJames Molloy // invalidate I. 1562f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1563f6f121e2SJames Molloy 15640a48b877STanya Lattner // Link in function body. 15650a48b877STanya Lattner linkFunctionBody(DF, SF); 156600623787SBill Wendling SF->Dematerialize(); 15670a48b877STanya Lattner 15680a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 15690a48b877STanya Lattner // since we linked in a function. 15700a48b877STanya Lattner LinkedInAnyFunctions = true; 1571f6f121e2SJames Molloy break; 15720a48b877STanya Lattner } 15730a48b877STanya Lattner } while (LinkedInAnyFunctions); 15740a48b877STanya Lattner 15752609888fSAnton Korobeynikov return false; 15762609888fSAnton Korobeynikov } 1577361e513dSReid Spencer 15785cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15795cb9c82aSRafael Espindola this->Composite = M; 15805cb9c82aSRafael Espindola this->DiagnosticHandler = DiagnosticHandler; 1581aa9918aaSRafael Espindola } 15823df61b7bSRafael Espindola 15835cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15845cb9c82aSRafael Espindola init(M, DiagnosticHandler); 15855cb9c82aSRafael Espindola } 15865cb9c82aSRafael Espindola 15875cb9c82aSRafael Espindola Linker::Linker(Module *M) { 15885cb9c82aSRafael Espindola init(M, [this](const DiagnosticInfo &DI) { 15895cb9c82aSRafael Espindola Composite->getContext().diagnose(DI); 15905cb9c82aSRafael Espindola }); 15915cb9c82aSRafael Espindola } 15925cb9c82aSRafael Espindola 15933df61b7bSRafael Espindola Linker::~Linker() { 15943df61b7bSRafael Espindola } 15953df61b7bSRafael Espindola 159691e6f6e1SBill Wendling void Linker::deleteModule() { 159791e6f6e1SBill Wendling delete Composite; 15982617dcceSCraig Topper Composite = nullptr; 159991e6f6e1SBill Wendling } 160091e6f6e1SBill Wendling 16019f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 1602*04a74af7SRafael Espindola ModuleLinker TheLinker(Composite, Src, DiagnosticHandler); 1603d12b4a33SRafael Espindola return TheLinker.run(); 16043df61b7bSRafael Espindola } 16053df61b7bSRafael Espindola 1606b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1607b1ed91f3SChris Lattner // LinkModules entrypoint. 1608b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1609b1ed91f3SChris Lattner 161018c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 161118c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 161218c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 161318c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 161418c89411SRafael Espindola /// relied on to be consistent. 16159f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 16164160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 16174160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 16189f8eff31SRafael Espindola return L.linkInModule(Src); 16194160f5d3SRafael Espindola } 16204160f5d3SRafael Espindola 16219f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1622287f18b4SRafael Espindola Linker L(Dest); 16239f8eff31SRafael Espindola return L.linkInModule(Src); 1624361e513dSReid Spencer } 1625a3aeb980SBill Wendling 1626a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1627a3aeb980SBill Wendling // C API. 1628a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1629a3aeb980SBill Wendling 1630a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1631a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 163298ab63ceSRafael Espindola Module *D = unwrap(Dest); 163398ab63ceSRafael Espindola std::string Message; 16344160f5d3SRafael Espindola raw_string_ostream Stream(Message); 16354160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 16364160f5d3SRafael Espindola 16374160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 16389f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 163998ab63ceSRafael Espindola 164098ab63ceSRafael Espindola if (OutMessages && Result) 164198ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1642a3aeb980SBill Wendling return Result; 1643a3aeb980SBill Wendling } 1644