159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===// 2361e513dSReid Spencer // 3361e513dSReid Spencer // The LLVM Compiler Infrastructure 4361e513dSReid Spencer // 5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source 6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details. 7361e513dSReid Spencer // 8361e513dSReid Spencer //===----------------------------------------------------------------------===// 9361e513dSReid Spencer // 10361e513dSReid Spencer // This file implements the LLVM module linker. 11361e513dSReid Spencer // 12361e513dSReid Spencer //===----------------------------------------------------------------------===// 13361e513dSReid Spencer 146cc07df4SChandler Carruth #include "llvm/Linker/Linker.h" 15ed0881b2SChandler Carruth #include "llvm-c/Linker.h" 1623f8d64bSRafael Espindola #include "llvm/ADT/Optional.h" 1766f02413SBill Wendling #include "llvm/ADT/SetVector.h" 180f7fd36fSEli Bendersky #include "llvm/ADT/SmallString.h" 199fb823bbSChandler Carruth #include "llvm/IR/Constants.h" 20d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticInfo.h" 21d12b4a33SRafael Espindola #include "llvm/IR/DiagnosticPrinter.h" 22d12b4a33SRafael Espindola #include "llvm/IR/LLVMContext.h" 239fb823bbSChandler Carruth #include "llvm/IR/Module.h" 24dcb603feSChandler Carruth #include "llvm/IR/TypeFinder.h" 25e17f3708SEli Bendersky #include "llvm/Support/CommandLine.h" 26b6af2f36SBill Wendling #include "llvm/Support/Debug.h" 27b6af2f36SBill Wendling #include "llvm/Support/raw_ostream.h" 28cbb91408STanya Lattner #include "llvm/Transforms/Utils/Cloning.h" 29981af002SWill Dietz #include <cctype> 3082d6ff6bSDavid Majnemer #include <tuple> 31361e513dSReid Spencer using namespace llvm; 32361e513dSReid Spencer 33e17f3708SEli Bendersky 34b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 35b1ed91f3SChris Lattner // TypeMap implementation. 36b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 37b1ed91f3SChris Lattner 38b1ed91f3SChris Lattner namespace { 39aa9918aaSRafael Espindola typedef SmallPtrSet<StructType *, 32> TypeSet; 40aa9918aaSRafael Espindola 41b1ed91f3SChris Lattner class TypeMapTy : public ValueMapTypeRemapper { 4218c89411SRafael Espindola /// This is a mapping from a source type to a destination type to use. 43b1ed91f3SChris Lattner DenseMap<Type*, Type*> MappedTypes; 44b1ed91f3SChris Lattner 4518c89411SRafael Espindola /// When checking to see if two subgraphs are isomorphic, we speculatively 4618c89411SRafael Espindola /// add types to MappedTypes, but keep track of them here in case we need to 4718c89411SRafael Espindola /// roll back. 48b1ed91f3SChris Lattner SmallVector<Type*, 16> SpeculativeTypes; 49b1ed91f3SChris Lattner 5018c89411SRafael Espindola /// This is a list of non-opaque structs in the source module that are mapped 5118c89411SRafael Espindola /// to an opaque struct in the destination module. 525e3bd972SChris Lattner SmallVector<StructType*, 16> SrcDefinitionsToResolve; 535e3bd972SChris Lattner 5418c89411SRafael Espindola /// This is the set of opaque types in the destination modules who are 5518c89411SRafael Espindola /// getting a body from the source module. 565e3bd972SChris Lattner SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes; 57d48b7783SBill Wendling 588c2cc416SBill Wendling public: 59aa9918aaSRafael Espindola TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {} 60aa9918aaSRafael Espindola 61aa9918aaSRafael Espindola TypeSet &DstStructTypesSet; 6218c89411SRafael Espindola /// Indicate that the specified type in the destination module is conceptually 6318c89411SRafael Espindola /// equivalent to the specified type in the source module. 64b1ed91f3SChris Lattner void addTypeMapping(Type *DstTy, Type *SrcTy); 65b1ed91f3SChris Lattner 66d2a13a2eSRafael Espindola /// Produce a body for an opaque type in the dest module from a type 67d2a13a2eSRafael Espindola /// definition in the source module. 68b1ed91f3SChris Lattner void linkDefinedTypeBodies(); 69b1ed91f3SChris Lattner 7018c89411SRafael Espindola /// Return the mapped type to use for the specified input type from the 71b1ed91f3SChris Lattner /// source module. 72b1ed91f3SChris Lattner Type *get(Type *SrcTy); 73b1ed91f3SChris Lattner 74290e2cc5SRafael Espindola FunctionType *get(FunctionType *T) { 75290e2cc5SRafael Espindola return cast<FunctionType>(get((Type *)T)); 76290e2cc5SRafael Espindola } 77b1ed91f3SChris Lattner 7818c89411SRafael Espindola /// Dump out the type map for debugging purposes. 79b6af2f36SBill Wendling void dump() const { 808f14471eSRafael Espindola for (auto &Pair : MappedTypes) { 81b6af2f36SBill Wendling dbgs() << "TypeMap: "; 828f14471eSRafael Espindola Pair.first->print(dbgs()); 83b6af2f36SBill Wendling dbgs() << " => "; 848f14471eSRafael Espindola Pair.second->print(dbgs()); 85b6af2f36SBill Wendling dbgs() << '\n'; 86b6af2f36SBill Wendling } 87b6af2f36SBill Wendling } 88b6af2f36SBill Wendling 89b1ed91f3SChris Lattner private: 90290e2cc5SRafael Espindola Type *remapType(Type *SrcTy) override { return get(SrcTy); } 91b1ed91f3SChris Lattner 92b1ed91f3SChris Lattner bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); 93b1ed91f3SChris Lattner }; 94b1ed91f3SChris Lattner } 95b1ed91f3SChris Lattner 96b1ed91f3SChris Lattner void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { 97*3d097410SRafael Espindola assert(SpeculativeTypes.empty()); 98*3d097410SRafael Espindola 99b1ed91f3SChris Lattner // Check to see if these types are recursively isomorphic and establish a 100b1ed91f3SChris Lattner // mapping between them if so. 101c586eaa1SDuncan P. N. Exon Smith if (!areTypesIsomorphic(DstTy, SrcTy)) { 102b1ed91f3SChris Lattner // Oops, they aren't isomorphic. Just discard this request by rolling out 103b1ed91f3SChris Lattner // any speculative mappings we've established. 104*3d097410SRafael Espindola for (Type *Ty : SpeculativeTypes) 105*3d097410SRafael Espindola MappedTypes.erase(Ty); 106d48b7783SBill Wendling } 107b1ed91f3SChris Lattner SpeculativeTypes.clear(); 108b1ed91f3SChris Lattner } 109b1ed91f3SChris Lattner 11018c89411SRafael Espindola /// Recursively walk this pair of types, returning true if they are isomorphic, 11118c89411SRafael Espindola /// false if they are not. 112b1ed91f3SChris Lattner bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { 113b1ed91f3SChris Lattner // Two types with differing kinds are clearly not isomorphic. 114290e2cc5SRafael Espindola if (DstTy->getTypeID() != SrcTy->getTypeID()) 115290e2cc5SRafael Espindola return false; 116b1ed91f3SChris Lattner 117b1ed91f3SChris Lattner // If we have an entry in the MappedTypes table, then we have our answer. 118b1ed91f3SChris Lattner Type *&Entry = MappedTypes[SrcTy]; 119b1ed91f3SChris Lattner if (Entry) 120b1ed91f3SChris Lattner return Entry == DstTy; 121b1ed91f3SChris Lattner 122b1ed91f3SChris Lattner // Two identical types are clearly isomorphic. Remember this 123b1ed91f3SChris Lattner // non-speculatively. 124b1ed91f3SChris Lattner if (DstTy == SrcTy) { 125b1ed91f3SChris Lattner Entry = DstTy; 126361e513dSReid Spencer return true; 127361e513dSReid Spencer } 128361e513dSReid Spencer 129b1ed91f3SChris Lattner // Okay, we have two types with identical kinds that we haven't seen before. 130361e513dSReid Spencer 131b1ed91f3SChris Lattner // If this is an opaque struct type, special case it. 132b1ed91f3SChris Lattner if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { 133b1ed91f3SChris Lattner // Mapping an opaque type to any struct, just keep the dest struct. 134b1ed91f3SChris Lattner if (SSTy->isOpaque()) { 135b1ed91f3SChris Lattner Entry = DstTy; 136b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 137b1ed91f3SChris Lattner return true; 138361e513dSReid Spencer } 139b1ed91f3SChris Lattner 1405e3bd972SChris Lattner // Mapping a non-opaque source type to an opaque dest. If this is the first 1415e3bd972SChris Lattner // type that we're mapping onto this destination type then we succeed. Keep 142c586eaa1SDuncan P. N. Exon Smith // the dest, but fill it in later. This doesn't need to be speculative. If 143c586eaa1SDuncan P. N. Exon Smith // this is the second (different) type that we're trying to map onto the 144c586eaa1SDuncan P. N. Exon Smith // same opaque type then we fail. 145b1ed91f3SChris Lattner if (cast<StructType>(DstTy)->isOpaque()) { 1465e3bd972SChris Lattner // We can only map one source type onto the opaque destination type. 14770573dcdSDavid Blaikie if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) 1485e3bd972SChris Lattner return false; 1495e3bd972SChris Lattner SrcDefinitionsToResolve.push_back(SSTy); 150b1ed91f3SChris Lattner Entry = DstTy; 151b1ed91f3SChris Lattner return true; 152b1ed91f3SChris Lattner } 153b1ed91f3SChris Lattner } 154b1ed91f3SChris Lattner 155b1ed91f3SChris Lattner // If the number of subtypes disagree between the two types, then we fail. 156b1ed91f3SChris Lattner if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) 157b1ed91f3SChris Lattner return false; 158b1ed91f3SChris Lattner 159b1ed91f3SChris Lattner // Fail if any of the extra properties (e.g. array size) of the type disagree. 160b1ed91f3SChris Lattner if (isa<IntegerType>(DstTy)) 161b1ed91f3SChris Lattner return false; // bitwidth disagrees. 162b1ed91f3SChris Lattner if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { 163b1ed91f3SChris Lattner if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) 164b1ed91f3SChris Lattner return false; 165eaf9b762SChris Lattner 166b1ed91f3SChris Lattner } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { 167b1ed91f3SChris Lattner if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) 168b1ed91f3SChris Lattner return false; 169b1ed91f3SChris Lattner } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { 170b1ed91f3SChris Lattner StructType *SSTy = cast<StructType>(SrcTy); 17144f7ab45SChris Lattner if (DSTy->isLiteral() != SSTy->isLiteral() || 172b1ed91f3SChris Lattner DSTy->isPacked() != SSTy->isPacked()) 173b1ed91f3SChris Lattner return false; 174b1ed91f3SChris Lattner } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { 175b1ed91f3SChris Lattner if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) 176b1ed91f3SChris Lattner return false; 177b1ed91f3SChris Lattner } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { 1785fad3e9aSJoey Gouly if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) 179361e513dSReid Spencer return false; 180361e513dSReid Spencer } 181361e513dSReid Spencer 182b1ed91f3SChris Lattner // Otherwise, we speculate that these two types will line up and recursively 183b1ed91f3SChris Lattner // check the subelements. 184b1ed91f3SChris Lattner Entry = DstTy; 185b1ed91f3SChris Lattner SpeculativeTypes.push_back(SrcTy); 186eee6f995SChris Lattner 187290e2cc5SRafael Espindola for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) 188290e2cc5SRafael Espindola if (!areTypesIsomorphic(DstTy->getContainedType(I), 189290e2cc5SRafael Espindola SrcTy->getContainedType(I))) 190b1ed91f3SChris Lattner return false; 191eee6f995SChris Lattner 192b1ed91f3SChris Lattner // If everything seems to have lined up, then everything is great. 193eee6f995SChris Lattner return true; 194eee6f995SChris Lattner } 195eee6f995SChris Lattner 196b1ed91f3SChris Lattner void TypeMapTy::linkDefinedTypeBodies() { 197b1ed91f3SChris Lattner SmallVector<Type*, 16> Elements; 198c81c3f55SRafael Espindola for (StructType *SrcSTy : SrcDefinitionsToResolve) { 199b1ed91f3SChris Lattner StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); 200c81c3f55SRafael Espindola assert(DstSTy->isOpaque()); 201b1ed91f3SChris Lattner 202b1ed91f3SChris Lattner // Map the body of the source type over to a new body for the dest type. 203b1ed91f3SChris Lattner Elements.resize(SrcSTy->getNumElements()); 204290e2cc5SRafael Espindola for (unsigned I = 0, E = Elements.size(); I != E; ++I) 205c81c3f55SRafael Espindola Elements[I] = get(SrcSTy->getElementType(I)); 206b1ed91f3SChris Lattner 207b1ed91f3SChris Lattner DstSTy->setBody(Elements, SrcSTy->isPacked()); 208b1ed91f3SChris Lattner } 209c81c3f55SRafael Espindola SrcDefinitionsToResolve.clear(); 2105e3bd972SChris Lattner DstResolvedOpaqueTypes.clear(); 211eee6f995SChris Lattner } 212eee6f995SChris Lattner 213b1ed91f3SChris Lattner Type *TypeMapTy::get(Type *Ty) { 214b1ed91f3SChris Lattner // If we already have an entry for this type, return it. 215b1ed91f3SChris Lattner Type **Entry = &MappedTypes[Ty]; 216290e2cc5SRafael Espindola if (*Entry) 217290e2cc5SRafael Espindola return *Entry; 218b1ed91f3SChris Lattner 219b1ed91f3SChris Lattner // If this is not a named struct type, then just map all of the elements and 220b1ed91f3SChris Lattner // then rebuild the type from inside out. 22144f7ab45SChris Lattner if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) { 222b1ed91f3SChris Lattner // If there are no element types to map, then the type is itself. This is 223b1ed91f3SChris Lattner // true for the anonymous {} struct, things like 'float', integers, etc. 224b1ed91f3SChris Lattner if (Ty->getNumContainedTypes() == 0) 225b1ed91f3SChris Lattner return *Entry = Ty; 226b1ed91f3SChris Lattner 227b1ed91f3SChris Lattner // Remap all of the elements, keeping track of whether any of them change. 228b1ed91f3SChris Lattner bool AnyChange = false; 229b1ed91f3SChris Lattner SmallVector<Type*, 4> ElementTypes; 230b1ed91f3SChris Lattner ElementTypes.resize(Ty->getNumContainedTypes()); 231290e2cc5SRafael Espindola for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { 232c81c3f55SRafael Espindola ElementTypes[I] = get(Ty->getContainedType(I)); 233290e2cc5SRafael Espindola AnyChange |= ElementTypes[I] != Ty->getContainedType(I); 234eee6f995SChris Lattner } 235b1ed91f3SChris Lattner 236b1ed91f3SChris Lattner // If we found our type while recursively processing stuff, just use it. 237b1ed91f3SChris Lattner Entry = &MappedTypes[Ty]; 238290e2cc5SRafael Espindola if (*Entry) 239290e2cc5SRafael Espindola return *Entry; 240b1ed91f3SChris Lattner 241b1ed91f3SChris Lattner // If all of the element types mapped directly over, then the type is usable 242b1ed91f3SChris Lattner // as-is. 243b1ed91f3SChris Lattner if (!AnyChange) 244b1ed91f3SChris Lattner return *Entry = Ty; 245b1ed91f3SChris Lattner 246b1ed91f3SChris Lattner // Otherwise, rebuild a modified type. 247b1ed91f3SChris Lattner switch (Ty->getTypeID()) { 248290e2cc5SRafael Espindola default: 249290e2cc5SRafael Espindola llvm_unreachable("unknown derived type to remap"); 250b1ed91f3SChris Lattner case Type::ArrayTyID: 251b1ed91f3SChris Lattner return *Entry = ArrayType::get(ElementTypes[0], 252b1ed91f3SChris Lattner cast<ArrayType>(Ty)->getNumElements()); 253b1ed91f3SChris Lattner case Type::VectorTyID: 254b1ed91f3SChris Lattner return *Entry = VectorType::get(ElementTypes[0], 255b1ed91f3SChris Lattner cast<VectorType>(Ty)->getNumElements()); 256b1ed91f3SChris Lattner case Type::PointerTyID: 257290e2cc5SRafael Espindola return *Entry = PointerType::get( 258290e2cc5SRafael Espindola ElementTypes[0], cast<PointerType>(Ty)->getAddressSpace()); 259b1ed91f3SChris Lattner case Type::FunctionTyID: 260b1ed91f3SChris Lattner return *Entry = FunctionType::get(ElementTypes[0], 261717d7eddSFrits van Bommel makeArrayRef(ElementTypes).slice(1), 262b1ed91f3SChris Lattner cast<FunctionType>(Ty)->isVarArg()); 263b1ed91f3SChris Lattner case Type::StructTyID: 264b1ed91f3SChris Lattner // Note that this is only reached for anonymous structs. 265b1ed91f3SChris Lattner return *Entry = StructType::get(Ty->getContext(), ElementTypes, 266b1ed91f3SChris Lattner cast<StructType>(Ty)->isPacked()); 267b1ed91f3SChris Lattner } 268b1ed91f3SChris Lattner } 269b1ed91f3SChris Lattner 270b1ed91f3SChris Lattner // Otherwise, this is an unmapped named struct. If the struct can be directly 271b1ed91f3SChris Lattner // mapped over, just use it as-is. This happens in a case when the linked-in 272b1ed91f3SChris Lattner // module has something like: 273b1ed91f3SChris Lattner // %T = type {%T*, i32} 274b1ed91f3SChris Lattner // @GV = global %T* null 275b1ed91f3SChris Lattner // where T does not exist at all in the destination module. 276b1ed91f3SChris Lattner // 277b1ed91f3SChris Lattner // The other case we watch for is when the type is not in the destination 278b1ed91f3SChris Lattner // module, but that it has to be rebuilt because it refers to something that 279b1ed91f3SChris Lattner // is already mapped. For example, if the destination module has: 280b1ed91f3SChris Lattner // %A = type { i32 } 281b1ed91f3SChris Lattner // and the source module has something like 282b1ed91f3SChris Lattner // %A' = type { i32 } 283b1ed91f3SChris Lattner // %B = type { %A'* } 284b1ed91f3SChris Lattner // @GV = global %B* null 285b1ed91f3SChris Lattner // then we want to create a new type: "%B = type { %A*}" and have it take the 286b1ed91f3SChris Lattner // pristine "%B" name from the source module. 287b1ed91f3SChris Lattner // 288b1ed91f3SChris Lattner // To determine which case this is, we have to recursively walk the type graph 289b1ed91f3SChris Lattner // speculating that we'll be able to reuse it unmodified. Only if this is 290b1ed91f3SChris Lattner // safe would we map the entire thing over. Because this is an optimization, 291b1ed91f3SChris Lattner // and is not required for the prettiness of the linked module, we just skip 292b1ed91f3SChris Lattner // it and always rebuild a type here. 293b1ed91f3SChris Lattner StructType *STy = cast<StructType>(Ty); 294b1ed91f3SChris Lattner 295b1ed91f3SChris Lattner // If the type is opaque, we can just use it directly. 296aa9918aaSRafael Espindola if (STy->isOpaque()) { 297aa9918aaSRafael Espindola // A named structure type from src module is used. Add it to the Set of 298aa9918aaSRafael Espindola // identified structs in the destination module. 299aa9918aaSRafael Espindola DstStructTypesSet.insert(STy); 300b1ed91f3SChris Lattner return *Entry = STy; 301aa9918aaSRafael Espindola } 302b1ed91f3SChris Lattner 303c81c3f55SRafael Espindola // Otherwise we create a new type. 3045e3bd972SChris Lattner StructType *DTy = StructType::create(STy->getContext()); 305aa9918aaSRafael Espindola // A new identified structure type was created. Add it to the set of 306aa9918aaSRafael Espindola // identified structs in the destination module. 307aa9918aaSRafael Espindola DstStructTypesSet.insert(DTy); 308c81c3f55SRafael Espindola *Entry = DTy; 309c81c3f55SRafael Espindola 310c81c3f55SRafael Espindola SmallVector<Type*, 4> ElementTypes; 311c81c3f55SRafael Espindola ElementTypes.resize(STy->getNumElements()); 312c81c3f55SRafael Espindola for (unsigned I = 0, E = ElementTypes.size(); I != E; ++I) 313c81c3f55SRafael Espindola ElementTypes[I] = get(STy->getElementType(I)); 314c81c3f55SRafael Espindola DTy->setBody(ElementTypes, STy->isPacked()); 315c81c3f55SRafael Espindola 316c81c3f55SRafael Espindola // Steal STy's name. 317c81c3f55SRafael Espindola if (STy->hasName()) { 318c81c3f55SRafael Espindola SmallString<16> TmpName = STy->getName(); 319c81c3f55SRafael Espindola STy->setName(""); 320c81c3f55SRafael Espindola DTy->setName(TmpName); 321c81c3f55SRafael Espindola } 322c81c3f55SRafael Espindola 323c81c3f55SRafael Espindola return DTy; 324b1ed91f3SChris Lattner } 325b1ed91f3SChris Lattner 326b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 327b1ed91f3SChris Lattner // ModuleLinker implementation. 328b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 329b1ed91f3SChris Lattner 330b1ed91f3SChris Lattner namespace { 331f6f121e2SJames Molloy class ModuleLinker; 332f6f121e2SJames Molloy 33318c89411SRafael Espindola /// Creates prototypes for functions that are lazily linked on the fly. This 33418c89411SRafael Espindola /// speeds up linking for modules with many/ lazily linked functions of which 33518c89411SRafael Espindola /// few get used. 336f6f121e2SJames Molloy class ValueMaterializerTy : public ValueMaterializer { 337f6f121e2SJames Molloy TypeMapTy &TypeMap; 338f6f121e2SJames Molloy Module *DstM; 339f6f121e2SJames Molloy std::vector<Function *> &LazilyLinkFunctions; 340c84f608bSRafael Espindola 341f6f121e2SJames Molloy public: 342f6f121e2SJames Molloy ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM, 343c84f608bSRafael Espindola std::vector<Function *> &LazilyLinkFunctions) 344c84f608bSRafael Espindola : ValueMaterializer(), TypeMap(TypeMap), DstM(DstM), 345c84f608bSRafael Espindola LazilyLinkFunctions(LazilyLinkFunctions) {} 346f6f121e2SJames Molloy 3478548299aSCraig Topper Value *materializeValueFor(Value *V) override; 348f6f121e2SJames Molloy }; 349f6f121e2SJames Molloy 350d12b4a33SRafael Espindola class LinkDiagnosticInfo : public DiagnosticInfo { 351d12b4a33SRafael Espindola const Twine &Msg; 352d12b4a33SRafael Espindola 353d12b4a33SRafael Espindola public: 354d12b4a33SRafael Espindola LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg); 355d12b4a33SRafael Espindola void print(DiagnosticPrinter &DP) const override; 356d12b4a33SRafael Espindola }; 357d12b4a33SRafael Espindola LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, 358d12b4a33SRafael Espindola const Twine &Msg) 359d12b4a33SRafael Espindola : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} 360d12b4a33SRafael Espindola void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } 361d12b4a33SRafael Espindola 36218c89411SRafael Espindola /// This is an implementation class for the LinkModules function, which is the 36318c89411SRafael Espindola /// entrypoint for this file. 364b1ed91f3SChris Lattner class ModuleLinker { 365b1ed91f3SChris Lattner Module *DstM, *SrcM; 366b1ed91f3SChris Lattner 367b1ed91f3SChris Lattner TypeMapTy TypeMap; 368f6f121e2SJames Molloy ValueMaterializerTy ValMaterializer; 369b1ed91f3SChris Lattner 37018c89411SRafael Espindola /// Mapping of values from what they used to be in Src, to what they are now 37118c89411SRafael Espindola /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead 37218c89411SRafael Espindola /// due to the use of Value handles which the Linker doesn't actually need, 37318c89411SRafael Espindola /// but this allows us to reuse the ValueMapper code. 374b1ed91f3SChris Lattner ValueToValueMapTy ValueMap; 375b1ed91f3SChris Lattner 376b1ed91f3SChris Lattner struct AppendingVarInfo { 377b1ed91f3SChris Lattner GlobalVariable *NewGV; // New aggregate global in dest module. 3783e8bc6a8SRafael Espindola const Constant *DstInit; // Old initializer from dest module. 3793e8bc6a8SRafael Espindola const Constant *SrcInit; // Old initializer from src module. 380b1ed91f3SChris Lattner }; 381b1ed91f3SChris Lattner 382b1ed91f3SChris Lattner std::vector<AppendingVarInfo> AppendingVars; 383b1ed91f3SChris Lattner 384cbb91408STanya Lattner // Set of items not to link in from source. 385cbb91408STanya Lattner SmallPtrSet<const Value *, 16> DoNotLinkFromSource; 386cbb91408STanya Lattner 3870a48b877STanya Lattner // Vector of functions to lazily link in. 388fa228782SBill Wendling std::vector<Function *> LazilyLinkFunctions; 3890a48b877STanya Lattner 3904160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler; 3914160f5d3SRafael Espindola 392b1ed91f3SChris Lattner public: 3939f8eff31SRafael Espindola ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, 3944160f5d3SRafael Espindola Linker::DiagnosticHandlerFunction DiagnosticHandler) 395f6f121e2SJames Molloy : DstM(dstM), SrcM(srcM), TypeMap(Set), 3969f8eff31SRafael Espindola ValMaterializer(TypeMap, DstM, LazilyLinkFunctions), 3974160f5d3SRafael Espindola DiagnosticHandler(DiagnosticHandler) {} 398b1ed91f3SChris Lattner 399b1ed91f3SChris Lattner bool run(); 400b1ed91f3SChris Lattner 401b1ed91f3SChris Lattner private: 402d12b4a33SRafael Espindola bool shouldLinkFromSource(bool &LinkFromSrc, const GlobalValue &Dest, 403d12b4a33SRafael Espindola const GlobalValue &Src); 404dbb0bd1aSRafael Espindola 405d12b4a33SRafael Espindola /// Helper method for setting a message and returning an error code. 406b1ed91f3SChris Lattner bool emitError(const Twine &Message) { 4074160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Error, Message)); 408b1ed91f3SChris Lattner return true; 409b1ed91f3SChris Lattner } 410b1ed91f3SChris Lattner 411d12b4a33SRafael Espindola void emitWarning(const Twine &Message) { 4124160f5d3SRafael Espindola DiagnosticHandler(LinkDiagnosticInfo(DS_Warning, Message)); 413d12b4a33SRafael Espindola } 414d12b4a33SRafael Espindola 415dad0a645SDavid Majnemer bool getComdatLeader(Module *M, StringRef ComdatName, 416dad0a645SDavid Majnemer const GlobalVariable *&GVar); 417dad0a645SDavid Majnemer bool computeResultingSelectionKind(StringRef ComdatName, 418dad0a645SDavid Majnemer Comdat::SelectionKind Src, 419dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 420dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 421dad0a645SDavid Majnemer bool &LinkFromSrc); 422dad0a645SDavid Majnemer std::map<const Comdat *, std::pair<Comdat::SelectionKind, bool>> 423dad0a645SDavid Majnemer ComdatsChosen; 424dad0a645SDavid Majnemer bool getComdatResult(const Comdat *SrcC, Comdat::SelectionKind &SK, 425dad0a645SDavid Majnemer bool &LinkFromSrc); 426dad0a645SDavid Majnemer 42718c89411SRafael Espindola /// Given a global in the source module, return the global in the 42818c89411SRafael Espindola /// destination module that is being linked to, if any. 4293e8bc6a8SRafael Espindola GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { 430b1ed91f3SChris Lattner // If the source has no name it can't link. If it has local linkage, 431b1ed91f3SChris Lattner // there is no name match-up going on. 432b1ed91f3SChris Lattner if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) 4332617dcceSCraig Topper return nullptr; 434b1ed91f3SChris Lattner 435b1ed91f3SChris Lattner // Otherwise see if we have a match in the destination module's symtab. 436b1ed91f3SChris Lattner GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName()); 437c84f608bSRafael Espindola if (!DGV) 438c84f608bSRafael Espindola return nullptr; 439b1ed91f3SChris Lattner 440b1ed91f3SChris Lattner // If we found a global with the same name in the dest module, but it has 441b1ed91f3SChris Lattner // internal linkage, we are really not doing any linkage here. 442b1ed91f3SChris Lattner if (DGV->hasLocalLinkage()) 4432617dcceSCraig Topper return nullptr; 444b1ed91f3SChris Lattner 445b1ed91f3SChris Lattner // Otherwise, we do in fact link to the destination global. 446b1ed91f3SChris Lattner return DGV; 447b1ed91f3SChris Lattner } 448b1ed91f3SChris Lattner 449b1ed91f3SChris Lattner void computeTypeMapping(); 450b1ed91f3SChris Lattner 45109d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobalArray(StringRef Name); 45209d84addSDuncan P. N. Exon Smith void upgradeMismatchedGlobals(); 45309d84addSDuncan P. N. Exon Smith 4543e8bc6a8SRafael Espindola bool linkAppendingVarProto(GlobalVariable *DstGV, 4553e8bc6a8SRafael Espindola const GlobalVariable *SrcGV); 456778fcc77SRafael Espindola 457778fcc77SRafael Espindola bool linkGlobalValueProto(GlobalValue *GV); 458778fcc77SRafael Espindola GlobalValue *linkGlobalVariableProto(const GlobalVariable *SGVar, 459778fcc77SRafael Espindola GlobalValue *DGV, bool LinkFromSrc); 460778fcc77SRafael Espindola GlobalValue *linkFunctionProto(const Function *SF, GlobalValue *DGV, 461778fcc77SRafael Espindola bool LinkFromSrc); 462778fcc77SRafael Espindola GlobalValue *linkGlobalAliasProto(const GlobalAlias *SGA, GlobalValue *DGV, 463778fcc77SRafael Espindola bool LinkFromSrc); 464778fcc77SRafael Espindola 46566f02413SBill Wendling bool linkModuleFlagsMetadata(); 466b1ed91f3SChris Lattner 467b1ed91f3SChris Lattner void linkAppendingVarInit(const AppendingVarInfo &AVI); 468b1ed91f3SChris Lattner void linkGlobalInits(); 469b1ed91f3SChris Lattner void linkFunctionBody(Function *Dst, Function *Src); 470b1ed91f3SChris Lattner void linkAliasBodies(); 471b1ed91f3SChris Lattner void linkNamedMDNodes(); 472eee6f995SChris Lattner }; 473d48b7783SBill Wendling } 474d48b7783SBill Wendling 47518c89411SRafael Espindola /// The LLVM SymbolTable class autorenames globals that conflict in the symbol 47618c89411SRafael Espindola /// table. This is good for all clients except for us. Go through the trouble 47718c89411SRafael Espindola /// to force this back. 478b1ed91f3SChris Lattner static void forceRenaming(GlobalValue *GV, StringRef Name) { 479b1ed91f3SChris Lattner // If the global doesn't force its name or if it already has the right name, 480b1ed91f3SChris Lattner // there is nothing for us to do. 481b1ed91f3SChris Lattner if (GV->hasLocalLinkage() || GV->getName() == Name) 482b1ed91f3SChris Lattner return; 483b1ed91f3SChris Lattner 484b1ed91f3SChris Lattner Module *M = GV->getParent(); 485361e513dSReid Spencer 486361e513dSReid Spencer // If there is a conflict, rename the conflict. 487b1ed91f3SChris Lattner if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { 4882a8d2e0eSChris Lattner GV->takeName(ConflictGV); 489361e513dSReid Spencer ConflictGV->setName(Name); // This will cause ConflictGV to get renamed 490b1ed91f3SChris Lattner assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); 4912a8d2e0eSChris Lattner } else { 4922a8d2e0eSChris Lattner GV->setName(Name); // Force the name back 4933aaaa0b2SReid Spencer } 4943aaaa0b2SReid Spencer } 4953aaaa0b2SReid Spencer 49618c89411SRafael Espindola /// copy additional attributes (those not needed to construct a GlobalValue) 49718c89411SRafael Espindola /// from the SrcGV to the DestGV. 498b6af2f36SBill Wendling static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) { 499dd7daee8SDuncan Sands // Use the maximum alignment, rather than just copying the alignment of SrcGV. 50099e05cf1SRafael Espindola auto *DestGO = dyn_cast<GlobalObject>(DestGV); 501a7d9c69cSRafael Espindola unsigned Alignment; 50299e05cf1SRafael Espindola if (DestGO) 50399e05cf1SRafael Espindola Alignment = std::max(DestGO->getAlignment(), SrcGV->getAlignment()); 504a7d9c69cSRafael Espindola 505dd7daee8SDuncan Sands DestGV->copyAttributesFrom(SrcGV); 506a7d9c69cSRafael Espindola 50799e05cf1SRafael Espindola if (DestGO) 50899e05cf1SRafael Espindola DestGO->setAlignment(Alignment); 509b1ed91f3SChris Lattner 510b1ed91f3SChris Lattner forceRenaming(DestGV, SrcGV->getName()); 511361e513dSReid Spencer } 512361e513dSReid Spencer 51323f8d64bSRafael Espindola static bool isLessConstraining(GlobalValue::VisibilityTypes a, 51423f8d64bSRafael Espindola GlobalValue::VisibilityTypes b) { 51523f8d64bSRafael Espindola if (a == GlobalValue::HiddenVisibility) 51623f8d64bSRafael Espindola return false; 51723f8d64bSRafael Espindola if (b == GlobalValue::HiddenVisibility) 51823f8d64bSRafael Espindola return true; 51923f8d64bSRafael Espindola if (a == GlobalValue::ProtectedVisibility) 52023f8d64bSRafael Espindola return false; 52123f8d64bSRafael Espindola if (b == GlobalValue::ProtectedVisibility) 52223f8d64bSRafael Espindola return true; 52323f8d64bSRafael Espindola return false; 52423f8d64bSRafael Espindola } 52523f8d64bSRafael Espindola 526f6f121e2SJames Molloy Value *ValueMaterializerTy::materializeValueFor(Value *V) { 527f6f121e2SJames Molloy Function *SF = dyn_cast<Function>(V); 528f6f121e2SJames Molloy if (!SF) 5292617dcceSCraig Topper return nullptr; 530f6f121e2SJames Molloy 531f6f121e2SJames Molloy Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()), 532f6f121e2SJames Molloy SF->getLinkage(), SF->getName(), DstM); 533f6f121e2SJames Molloy copyGVAttributes(DF, SF); 534f6f121e2SJames Molloy 5353931c28bSRafael Espindola if (Comdat *SC = SF->getComdat()) { 5363931c28bSRafael Espindola Comdat *DC = DstM->getOrInsertComdat(SC->getName()); 5373931c28bSRafael Espindola DF->setComdat(DC); 5383931c28bSRafael Espindola } 5393931c28bSRafael Espindola 540f6f121e2SJames Molloy LazilyLinkFunctions.push_back(SF); 541f6f121e2SJames Molloy return DF; 542f6f121e2SJames Molloy } 543f6f121e2SJames Molloy 544dad0a645SDavid Majnemer bool ModuleLinker::getComdatLeader(Module *M, StringRef ComdatName, 545dad0a645SDavid Majnemer const GlobalVariable *&GVar) { 546dad0a645SDavid Majnemer const GlobalValue *GVal = M->getNamedValue(ComdatName); 547dad0a645SDavid Majnemer if (const auto *GA = dyn_cast_or_null<GlobalAlias>(GVal)) { 548dad0a645SDavid Majnemer GVal = GA->getBaseObject(); 549dad0a645SDavid Majnemer if (!GVal) 550dad0a645SDavid Majnemer // We cannot resolve the size of the aliasee yet. 551dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 552dad0a645SDavid Majnemer "': COMDAT key involves incomputable alias size."); 553dad0a645SDavid Majnemer } 554dad0a645SDavid Majnemer 555dad0a645SDavid Majnemer GVar = dyn_cast_or_null<GlobalVariable>(GVal); 556dad0a645SDavid Majnemer if (!GVar) 557dad0a645SDavid Majnemer return emitError( 558dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 559dad0a645SDavid Majnemer "': GlobalVariable required for data dependent selection!"); 560dad0a645SDavid Majnemer 561dad0a645SDavid Majnemer return false; 562dad0a645SDavid Majnemer } 563dad0a645SDavid Majnemer 564dad0a645SDavid Majnemer bool ModuleLinker::computeResultingSelectionKind(StringRef ComdatName, 565dad0a645SDavid Majnemer Comdat::SelectionKind Src, 566dad0a645SDavid Majnemer Comdat::SelectionKind Dst, 567dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 568dad0a645SDavid Majnemer bool &LinkFromSrc) { 569dad0a645SDavid Majnemer // The ability to mix Comdat::SelectionKind::Any with 570dad0a645SDavid Majnemer // Comdat::SelectionKind::Largest is a behavior that comes from COFF. 571dad0a645SDavid Majnemer bool DstAnyOrLargest = Dst == Comdat::SelectionKind::Any || 572dad0a645SDavid Majnemer Dst == Comdat::SelectionKind::Largest; 573dad0a645SDavid Majnemer bool SrcAnyOrLargest = Src == Comdat::SelectionKind::Any || 574dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest; 575dad0a645SDavid Majnemer if (DstAnyOrLargest && SrcAnyOrLargest) { 576dad0a645SDavid Majnemer if (Dst == Comdat::SelectionKind::Largest || 577dad0a645SDavid Majnemer Src == Comdat::SelectionKind::Largest) 578dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Largest; 579dad0a645SDavid Majnemer else 580dad0a645SDavid Majnemer Result = Comdat::SelectionKind::Any; 581dad0a645SDavid Majnemer } else if (Src == Dst) { 582dad0a645SDavid Majnemer Result = Dst; 583dad0a645SDavid Majnemer } else { 584dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 585dad0a645SDavid Majnemer "': invalid selection kinds!"); 586dad0a645SDavid Majnemer } 587dad0a645SDavid Majnemer 588dad0a645SDavid Majnemer switch (Result) { 589dad0a645SDavid Majnemer case Comdat::SelectionKind::Any: 590dad0a645SDavid Majnemer // Go with Dst. 591dad0a645SDavid Majnemer LinkFromSrc = false; 592dad0a645SDavid Majnemer break; 593dad0a645SDavid Majnemer case Comdat::SelectionKind::NoDuplicates: 594dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 595dad0a645SDavid Majnemer "': noduplicates has been violated!"); 596dad0a645SDavid Majnemer case Comdat::SelectionKind::ExactMatch: 597dad0a645SDavid Majnemer case Comdat::SelectionKind::Largest: 598dad0a645SDavid Majnemer case Comdat::SelectionKind::SameSize: { 599dad0a645SDavid Majnemer const GlobalVariable *DstGV; 600dad0a645SDavid Majnemer const GlobalVariable *SrcGV; 601dad0a645SDavid Majnemer if (getComdatLeader(DstM, ComdatName, DstGV) || 602dad0a645SDavid Majnemer getComdatLeader(SrcM, ComdatName, SrcGV)) 603dad0a645SDavid Majnemer return true; 604dad0a645SDavid Majnemer 605dad0a645SDavid Majnemer const DataLayout *DstDL = DstM->getDataLayout(); 606dad0a645SDavid Majnemer const DataLayout *SrcDL = SrcM->getDataLayout(); 607dad0a645SDavid Majnemer if (!DstDL || !SrcDL) { 608dad0a645SDavid Majnemer return emitError( 609dad0a645SDavid Majnemer "Linking COMDATs named '" + ComdatName + 610dad0a645SDavid Majnemer "': can't do size dependent selection without DataLayout!"); 611dad0a645SDavid Majnemer } 612dad0a645SDavid Majnemer uint64_t DstSize = 613dad0a645SDavid Majnemer DstDL->getTypeAllocSize(DstGV->getType()->getPointerElementType()); 614dad0a645SDavid Majnemer uint64_t SrcSize = 615dad0a645SDavid Majnemer SrcDL->getTypeAllocSize(SrcGV->getType()->getPointerElementType()); 616dad0a645SDavid Majnemer if (Result == Comdat::SelectionKind::ExactMatch) { 617dad0a645SDavid Majnemer if (SrcGV->getInitializer() != DstGV->getInitializer()) 618dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 619dad0a645SDavid Majnemer "': ExactMatch violated!"); 620dad0a645SDavid Majnemer LinkFromSrc = false; 621dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::Largest) { 622dad0a645SDavid Majnemer LinkFromSrc = SrcSize > DstSize; 623dad0a645SDavid Majnemer } else if (Result == Comdat::SelectionKind::SameSize) { 624dad0a645SDavid Majnemer if (SrcSize != DstSize) 625dad0a645SDavid Majnemer return emitError("Linking COMDATs named '" + ComdatName + 626dad0a645SDavid Majnemer "': SameSize violated!"); 627dad0a645SDavid Majnemer LinkFromSrc = false; 628dad0a645SDavid Majnemer } else { 629dad0a645SDavid Majnemer llvm_unreachable("unknown selection kind"); 630dad0a645SDavid Majnemer } 631dad0a645SDavid Majnemer break; 632dad0a645SDavid Majnemer } 633dad0a645SDavid Majnemer } 634dad0a645SDavid Majnemer 635dad0a645SDavid Majnemer return false; 636dad0a645SDavid Majnemer } 637dad0a645SDavid Majnemer 638dad0a645SDavid Majnemer bool ModuleLinker::getComdatResult(const Comdat *SrcC, 639dad0a645SDavid Majnemer Comdat::SelectionKind &Result, 640dad0a645SDavid Majnemer bool &LinkFromSrc) { 641b16196a3SRafael Espindola Comdat::SelectionKind SSK = SrcC->getSelectionKind(); 642dad0a645SDavid Majnemer StringRef ComdatName = SrcC->getName(); 643dad0a645SDavid Majnemer Module::ComdatSymTabType &ComdatSymTab = DstM->getComdatSymbolTable(); 644dad0a645SDavid Majnemer Module::ComdatSymTabType::iterator DstCI = ComdatSymTab.find(ComdatName); 6452ef3f299SRafael Espindola 646b16196a3SRafael Espindola if (DstCI == ComdatSymTab.end()) { 647b16196a3SRafael Espindola // Use the comdat if it is only available in one of the modules. 648b16196a3SRafael Espindola LinkFromSrc = true; 649b16196a3SRafael Espindola Result = SSK; 6502ef3f299SRafael Espindola return false; 651b16196a3SRafael Espindola } 6522ef3f299SRafael Espindola 653dad0a645SDavid Majnemer const Comdat *DstC = &DstCI->second; 654dad0a645SDavid Majnemer Comdat::SelectionKind DSK = DstC->getSelectionKind(); 6552ef3f299SRafael Espindola return computeResultingSelectionKind(ComdatName, SSK, DSK, Result, 6562ef3f299SRafael Espindola LinkFromSrc); 657dad0a645SDavid Majnemer } 658f6f121e2SJames Molloy 659d12b4a33SRafael Espindola bool ModuleLinker::shouldLinkFromSource(bool &LinkFromSrc, 660d12b4a33SRafael Espindola const GlobalValue &Dest, 661dbb0bd1aSRafael Espindola const GlobalValue &Src) { 662778fcc77SRafael Espindola // We always have to add Src if it has appending linkage. 663778fcc77SRafael Espindola if (Src.hasAppendingLinkage()) { 664778fcc77SRafael Espindola LinkFromSrc = true; 665778fcc77SRafael Espindola return false; 666778fcc77SRafael Espindola } 667778fcc77SRafael Espindola 668d4bcefc7SRafael Espindola bool SrcIsDeclaration = Src.isDeclarationForLinker(); 669d4bcefc7SRafael Espindola bool DestIsDeclaration = Dest.isDeclarationForLinker(); 670dbb0bd1aSRafael Espindola 671dbb0bd1aSRafael Espindola if (SrcIsDeclaration) { 672dbb0bd1aSRafael Espindola // If Src is external or if both Src & Dest are external.. Just link the 673dbb0bd1aSRafael Espindola // external globals, we aren't adding anything. 674d12b4a33SRafael Espindola if (Src.hasDLLImportStorageClass()) { 675dbb0bd1aSRafael Espindola // If one of GVs is marked as DLLImport, result should be dllimport'ed. 676d12b4a33SRafael Espindola LinkFromSrc = DestIsDeclaration; 677d12b4a33SRafael Espindola return false; 678d12b4a33SRafael Espindola } 679dbb0bd1aSRafael Espindola // If the Dest is weak, use the source linkage. 680d12b4a33SRafael Espindola LinkFromSrc = Dest.hasExternalWeakLinkage(); 681d12b4a33SRafael Espindola return false; 682dbb0bd1aSRafael Espindola } 683dbb0bd1aSRafael Espindola 684d12b4a33SRafael Espindola if (DestIsDeclaration) { 685dbb0bd1aSRafael Espindola // If Dest is external but Src is not: 686d12b4a33SRafael Espindola LinkFromSrc = true; 687d12b4a33SRafael Espindola return false; 688d12b4a33SRafael Espindola } 689dbb0bd1aSRafael Espindola 6900910605aSRafael Espindola if (Src.hasCommonLinkage()) { 691d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() || Dest.hasWeakLinkage()) { 692d12b4a33SRafael Espindola LinkFromSrc = true; 6930910605aSRafael Espindola return false; 694d12b4a33SRafael Espindola } 695d12b4a33SRafael Espindola 696d12b4a33SRafael Espindola if (!Dest.hasCommonLinkage()) { 697d12b4a33SRafael Espindola LinkFromSrc = false; 698d12b4a33SRafael Espindola return false; 699d12b4a33SRafael Espindola } 7000910605aSRafael Espindola 7010ae225b6SRafael Espindola // FIXME: Make datalayout mandatory and just use getDataLayout(). 7020ae225b6SRafael Espindola DataLayout DL(Dest.getParent()); 7030ae225b6SRafael Espindola 7040910605aSRafael Espindola uint64_t DestSize = DL.getTypeAllocSize(Dest.getType()->getElementType()); 7050910605aSRafael Espindola uint64_t SrcSize = DL.getTypeAllocSize(Src.getType()->getElementType()); 706d12b4a33SRafael Espindola LinkFromSrc = SrcSize > DestSize; 707d12b4a33SRafael Espindola return false; 7080910605aSRafael Espindola } 7090910605aSRafael Espindola 710dbb0bd1aSRafael Espindola if (Src.isWeakForLinker()) { 711dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 712dbb0bd1aSRafael Espindola assert(!Dest.hasAvailableExternallyLinkage()); 7130910605aSRafael Espindola 714d12b4a33SRafael Espindola if (Dest.hasLinkOnceLinkage() && Src.hasWeakLinkage()) { 715d12b4a33SRafael Espindola LinkFromSrc = true; 716d12b4a33SRafael Espindola return false; 717d12b4a33SRafael Espindola } 718dbb0bd1aSRafael Espindola 719d12b4a33SRafael Espindola LinkFromSrc = false; 7200910605aSRafael Espindola return false; 721dbb0bd1aSRafael Espindola } 722dbb0bd1aSRafael Espindola 723dbb0bd1aSRafael Espindola if (Dest.isWeakForLinker()) { 724dbb0bd1aSRafael Espindola assert(Src.hasExternalLinkage()); 725d12b4a33SRafael Espindola LinkFromSrc = true; 726d12b4a33SRafael Espindola return false; 727dbb0bd1aSRafael Espindola } 728dbb0bd1aSRafael Espindola 729dbb0bd1aSRafael Espindola assert(!Src.hasExternalWeakLinkage()); 730dbb0bd1aSRafael Espindola assert(!Dest.hasExternalWeakLinkage()); 731dbb0bd1aSRafael Espindola assert(Dest.hasExternalLinkage() && Src.hasExternalLinkage() && 732dbb0bd1aSRafael Espindola "Unexpected linkage type!"); 733dbb0bd1aSRafael Espindola return emitError("Linking globals named '" + Src.getName() + 734dbb0bd1aSRafael Espindola "': symbol multiply defined!"); 735dbb0bd1aSRafael Espindola } 736dbb0bd1aSRafael Espindola 73718c89411SRafael Espindola /// Loop over all of the linked values to compute type mappings. For example, 73818c89411SRafael Espindola /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct 73918c89411SRafael Espindola /// types 'Foo' but one got renamed when the module was loaded into the same 74018c89411SRafael Espindola /// LLVMContext. 741b1ed91f3SChris Lattner void ModuleLinker::computeTypeMapping() { 742c8a476eeSRafael Espindola for (GlobalValue &SGV : SrcM->globals()) { 743c8a476eeSRafael Espindola GlobalValue *DGV = getLinkedToGlobal(&SGV); 744c8a476eeSRafael Espindola if (!DGV) 745c8a476eeSRafael Espindola continue; 746b1ed91f3SChris Lattner 747c8a476eeSRafael Espindola if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { 748c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 749b1ed91f3SChris Lattner continue; 7505c310be0SDevang Patel } 7515c310be0SDevang Patel 752b1ed91f3SChris Lattner // Unify the element type of appending arrays. 753b1ed91f3SChris Lattner ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType()); 754c8a476eeSRafael Espindola ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType()); 755b1ed91f3SChris Lattner TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); 756b1ed91f3SChris Lattner } 75734fc5a0eSChris Lattner 758c8a476eeSRafael Espindola for (GlobalValue &SGV : *SrcM) { 759c8a476eeSRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 760c8a476eeSRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 761b1ed91f3SChris Lattner } 762e79f4c77SAnton Korobeynikov 763e96d7eb8SRafael Espindola for (GlobalValue &SGV : SrcM->aliases()) { 764e96d7eb8SRafael Espindola if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) 765e96d7eb8SRafael Espindola TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); 766e96d7eb8SRafael Espindola } 767e96d7eb8SRafael Espindola 768d48b7783SBill Wendling // Incorporate types by name, scanning all the types in the source module. 769d48b7783SBill Wendling // At this point, the destination module may have a type "%foo = { i32 }" for 7702b3f61afSBill Wendling // example. When the source module got loaded into the same LLVMContext, if 7712b3f61afSBill Wendling // it had the same type, it would have been renamed to "%foo.42 = { i32 }". 7728555a37cSBill Wendling TypeFinder SrcStructTypes; 7738555a37cSBill Wendling SrcStructTypes.run(*SrcM, true); 7742b3f61afSBill Wendling SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(), 7752b3f61afSBill Wendling SrcStructTypes.end()); 7762b3f61afSBill Wendling 7772b3f61afSBill Wendling for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) { 7782b3f61afSBill Wendling StructType *ST = SrcStructTypes[i]; 7792b3f61afSBill Wendling if (!ST->hasName()) continue; 7802b3f61afSBill Wendling 7812b3f61afSBill Wendling // Check to see if there is a dot in the name followed by a digit. 782d48b7783SBill Wendling size_t DotPos = ST->getName().rfind('.'); 783d48b7783SBill Wendling if (DotPos == 0 || DotPos == StringRef::npos || 78483c74e9fSGuy Benyei ST->getName().back() == '.' || 78583c74e9fSGuy Benyei !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1]))) 786d48b7783SBill Wendling continue; 7872b3f61afSBill Wendling 7882b3f61afSBill Wendling // Check to see if the destination module has a struct with the prefix name. 789d48b7783SBill Wendling if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos))) 7902b3f61afSBill Wendling // Don't use it if this actually came from the source module. They're in 7918737480dSBill Wendling // the same LLVMContext after all. Also don't use it unless the type is 7928737480dSBill Wendling // actually used in the destination module. This can happen in situations 7938737480dSBill Wendling // like this: 7948737480dSBill Wendling // 7958737480dSBill Wendling // Module A Module B 7968737480dSBill Wendling // -------- -------- 7978737480dSBill Wendling // %Z = type { %A } %B = type { %C.1 } 7988737480dSBill Wendling // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } 7998737480dSBill Wendling // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } 8008737480dSBill Wendling // %C = type { i8* } %B.3 = type { %C.1 } 8018737480dSBill Wendling // 8028737480dSBill Wendling // When we link Module B with Module A, the '%B' in Module B is 8038737480dSBill Wendling // used. However, that would then use '%C.1'. But when we process '%C.1', 8048737480dSBill Wendling // we prefer to take the '%C' version. So we are then left with both 8058737480dSBill Wendling // '%C.1' and '%C' being used for the same types. This leads to some 8068737480dSBill Wendling // variables using one type and some using the other. 807aa9918aaSRafael Espindola if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST)) 8082b3f61afSBill Wendling TypeMap.addTypeMapping(DST, ST); 8092b3f61afSBill Wendling } 8102b3f61afSBill Wendling 811b1ed91f3SChris Lattner // Now that we have discovered all of the type equivalences, get a body for 812b1ed91f3SChris Lattner // any 'opaque' types in the dest module that are now resolved. 813b1ed91f3SChris Lattner TypeMap.linkDefinedTypeBodies(); 814b1ed91f3SChris Lattner } 815c08e7a00SChris Lattner 81609d84addSDuncan P. N. Exon Smith static void upgradeGlobalArray(GlobalVariable *GV) { 81709d84addSDuncan P. N. Exon Smith ArrayType *ATy = cast<ArrayType>(GV->getType()->getElementType()); 81809d84addSDuncan P. N. Exon Smith StructType *OldTy = cast<StructType>(ATy->getElementType()); 81909d84addSDuncan P. N. Exon Smith assert(OldTy->getNumElements() == 2 && "Expected to upgrade from 2 elements"); 82009d84addSDuncan P. N. Exon Smith 82109d84addSDuncan P. N. Exon Smith // Get the upgraded 3 element type. 82209d84addSDuncan P. N. Exon Smith PointerType *VoidPtrTy = Type::getInt8Ty(GV->getContext())->getPointerTo(); 82309d84addSDuncan P. N. Exon Smith Type *Tys[3] = {OldTy->getElementType(0), OldTy->getElementType(1), 82409d84addSDuncan P. N. Exon Smith VoidPtrTy}; 82509d84addSDuncan P. N. Exon Smith StructType *NewTy = StructType::get(GV->getContext(), Tys, false); 82609d84addSDuncan P. N. Exon Smith 82709d84addSDuncan P. N. Exon Smith // Build new constants with a null third field filled in. 82809d84addSDuncan P. N. Exon Smith Constant *OldInitC = GV->getInitializer(); 82909d84addSDuncan P. N. Exon Smith ConstantArray *OldInit = dyn_cast<ConstantArray>(OldInitC); 83009d84addSDuncan P. N. Exon Smith if (!OldInit && !isa<ConstantAggregateZero>(OldInitC)) 83109d84addSDuncan P. N. Exon Smith // Invalid initializer; give up. 83209d84addSDuncan P. N. Exon Smith return; 83309d84addSDuncan P. N. Exon Smith std::vector<Constant *> Initializers; 83409d84addSDuncan P. N. Exon Smith if (OldInit && OldInit->getNumOperands()) { 83509d84addSDuncan P. N. Exon Smith Value *Null = Constant::getNullValue(VoidPtrTy); 83609d84addSDuncan P. N. Exon Smith for (Use &U : OldInit->operands()) { 83709d84addSDuncan P. N. Exon Smith ConstantStruct *Init = cast<ConstantStruct>(U.get()); 83809d84addSDuncan P. N. Exon Smith Initializers.push_back(ConstantStruct::get( 83909d84addSDuncan P. N. Exon Smith NewTy, Init->getOperand(0), Init->getOperand(1), Null, nullptr)); 84009d84addSDuncan P. N. Exon Smith } 84109d84addSDuncan P. N. Exon Smith } 84209d84addSDuncan P. N. Exon Smith assert(Initializers.size() == ATy->getNumElements() && 84309d84addSDuncan P. N. Exon Smith "Failed to copy all array elements"); 84409d84addSDuncan P. N. Exon Smith 84509d84addSDuncan P. N. Exon Smith // Replace the old GV with a new one. 84609d84addSDuncan P. N. Exon Smith ATy = ArrayType::get(NewTy, Initializers.size()); 84709d84addSDuncan P. N. Exon Smith Constant *NewInit = ConstantArray::get(ATy, Initializers); 84809d84addSDuncan P. N. Exon Smith GlobalVariable *NewGV = new GlobalVariable( 84909d84addSDuncan P. N. Exon Smith *GV->getParent(), ATy, GV->isConstant(), GV->getLinkage(), NewInit, "", 85009d84addSDuncan P. N. Exon Smith GV, GV->getThreadLocalMode(), GV->getType()->getAddressSpace(), 85109d84addSDuncan P. N. Exon Smith GV->isExternallyInitialized()); 85209d84addSDuncan P. N. Exon Smith NewGV->copyAttributesFrom(GV); 85309d84addSDuncan P. N. Exon Smith NewGV->takeName(GV); 85409d84addSDuncan P. N. Exon Smith assert(GV->use_empty() && "program cannot use initializer list"); 85509d84addSDuncan P. N. Exon Smith GV->eraseFromParent(); 85609d84addSDuncan P. N. Exon Smith } 85709d84addSDuncan P. N. Exon Smith 85809d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobalArray(StringRef Name) { 85909d84addSDuncan P. N. Exon Smith // Look for the global arrays. 86009d84addSDuncan P. N. Exon Smith auto *DstGV = dyn_cast_or_null<GlobalVariable>(DstM->getNamedValue(Name)); 86109d84addSDuncan P. N. Exon Smith if (!DstGV) 86209d84addSDuncan P. N. Exon Smith return; 86309d84addSDuncan P. N. Exon Smith auto *SrcGV = dyn_cast_or_null<GlobalVariable>(SrcM->getNamedValue(Name)); 86409d84addSDuncan P. N. Exon Smith if (!SrcGV) 86509d84addSDuncan P. N. Exon Smith return; 86609d84addSDuncan P. N. Exon Smith 86709d84addSDuncan P. N. Exon Smith // Check if the types already match. 86809d84addSDuncan P. N. Exon Smith auto *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 86909d84addSDuncan P. N. Exon Smith auto *SrcTy = 87009d84addSDuncan P. N. Exon Smith cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 87109d84addSDuncan P. N. Exon Smith if (DstTy == SrcTy) 87209d84addSDuncan P. N. Exon Smith return; 87309d84addSDuncan P. N. Exon Smith 87409d84addSDuncan P. N. Exon Smith // Grab the element types. We can only upgrade an array of a two-field 87509d84addSDuncan P. N. Exon Smith // struct. Only bother if the other one has three-fields. 87609d84addSDuncan P. N. Exon Smith auto *DstEltTy = cast<StructType>(DstTy->getElementType()); 87709d84addSDuncan P. N. Exon Smith auto *SrcEltTy = cast<StructType>(SrcTy->getElementType()); 87809d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 2 && SrcEltTy->getNumElements() == 3) { 87909d84addSDuncan P. N. Exon Smith upgradeGlobalArray(DstGV); 88009d84addSDuncan P. N. Exon Smith return; 88109d84addSDuncan P. N. Exon Smith } 88209d84addSDuncan P. N. Exon Smith if (DstEltTy->getNumElements() == 3 && SrcEltTy->getNumElements() == 2) 88309d84addSDuncan P. N. Exon Smith upgradeGlobalArray(SrcGV); 88409d84addSDuncan P. N. Exon Smith 88509d84addSDuncan P. N. Exon Smith // We can't upgrade any other differences. 88609d84addSDuncan P. N. Exon Smith } 88709d84addSDuncan P. N. Exon Smith 88809d84addSDuncan P. N. Exon Smith void ModuleLinker::upgradeMismatchedGlobals() { 88909d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_ctors"); 89009d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobalArray("llvm.global_dtors"); 89109d84addSDuncan P. N. Exon Smith } 89209d84addSDuncan P. N. Exon Smith 89318c89411SRafael Espindola /// If there were any appending global variables, link them together now. 89418c89411SRafael Espindola /// Return true on error. 895b1ed91f3SChris Lattner bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV, 8963e8bc6a8SRafael Espindola const GlobalVariable *SrcGV) { 897d48b7783SBill Wendling 898b1ed91f3SChris Lattner if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) 899b1ed91f3SChris Lattner return emitError("Linking globals named '" + SrcGV->getName() + 900b1ed91f3SChris Lattner "': can only link appending global with another appending global!"); 901361e513dSReid Spencer 902b1ed91f3SChris Lattner ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType()); 903b1ed91f3SChris Lattner ArrayType *SrcTy = 904b1ed91f3SChris Lattner cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType())); 905b1ed91f3SChris Lattner Type *EltTy = DstTy->getElementType(); 906b1ed91f3SChris Lattner 907b1ed91f3SChris Lattner // Check to see that they two arrays agree on type. 908b1ed91f3SChris Lattner if (EltTy != SrcTy->getElementType()) 909b1ed91f3SChris Lattner return emitError("Appending variables with different element types!"); 910b1ed91f3SChris Lattner if (DstGV->isConstant() != SrcGV->isConstant()) 911b1ed91f3SChris Lattner return emitError("Appending variables linked with different const'ness!"); 912b1ed91f3SChris Lattner 913b1ed91f3SChris Lattner if (DstGV->getAlignment() != SrcGV->getAlignment()) 914b1ed91f3SChris Lattner return emitError( 915b1ed91f3SChris Lattner "Appending variables with different alignment need to be linked!"); 916b1ed91f3SChris Lattner 917b1ed91f3SChris Lattner if (DstGV->getVisibility() != SrcGV->getVisibility()) 918b1ed91f3SChris Lattner return emitError( 919b1ed91f3SChris Lattner "Appending variables with different visibility need to be linked!"); 920b1ed91f3SChris Lattner 921fac3a018SRafael Espindola if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) 922fac3a018SRafael Espindola return emitError( 923fac3a018SRafael Espindola "Appending variables with different unnamed_addr need to be linked!"); 924fac3a018SRafael Espindola 92564c1e180SRafael Espindola if (StringRef(DstGV->getSection()) != SrcGV->getSection()) 926b1ed91f3SChris Lattner return emitError( 927b1ed91f3SChris Lattner "Appending variables with different section name need to be linked!"); 928b1ed91f3SChris Lattner 929b1ed91f3SChris Lattner uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements(); 930b1ed91f3SChris Lattner ArrayType *NewType = ArrayType::get(EltTy, NewSize); 931b1ed91f3SChris Lattner 932b1ed91f3SChris Lattner // Create the new global variable. 933b1ed91f3SChris Lattner GlobalVariable *NG = 934b1ed91f3SChris Lattner new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(), 9352617dcceSCraig Topper DstGV->getLinkage(), /*init*/nullptr, /*name*/"", DstGV, 936cbe34b4cSHans Wennborg DstGV->getThreadLocalMode(), 937b1ed91f3SChris Lattner DstGV->getType()->getAddressSpace()); 938b1ed91f3SChris Lattner 939b1ed91f3SChris Lattner // Propagate alignment, visibility and section info. 940b6af2f36SBill Wendling copyGVAttributes(NG, DstGV); 941b1ed91f3SChris Lattner 942b1ed91f3SChris Lattner AppendingVarInfo AVI; 943b1ed91f3SChris Lattner AVI.NewGV = NG; 944b1ed91f3SChris Lattner AVI.DstInit = DstGV->getInitializer(); 945b1ed91f3SChris Lattner AVI.SrcInit = SrcGV->getInitializer(); 946b1ed91f3SChris Lattner AppendingVars.push_back(AVI); 947b1ed91f3SChris Lattner 948b1ed91f3SChris Lattner // Replace any uses of the two global variables with uses of the new 949b1ed91f3SChris Lattner // global. 950b1ed91f3SChris Lattner ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); 951b1ed91f3SChris Lattner 952b1ed91f3SChris Lattner DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); 953b1ed91f3SChris Lattner DstGV->eraseFromParent(); 954b1ed91f3SChris Lattner 955cbb91408STanya Lattner // Track the source variable so we don't try to link it. 956cbb91408STanya Lattner DoNotLinkFromSource.insert(SrcGV); 957cbb91408STanya Lattner 958b1ed91f3SChris Lattner return false; 959b1ed91f3SChris Lattner } 960b1ed91f3SChris Lattner 961778fcc77SRafael Espindola bool ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) { 962b1ed91f3SChris Lattner GlobalValue *DGV = getLinkedToGlobal(SGV); 963b1ed91f3SChris Lattner 964778fcc77SRafael Espindola // Handle the ultra special appending linkage case first. 965778fcc77SRafael Espindola if (DGV && DGV->hasAppendingLinkage()) 966778fcc77SRafael Espindola return linkAppendingVarProto(cast<GlobalVariable>(DGV), 967778fcc77SRafael Espindola cast<GlobalVariable>(SGV)); 968778fcc77SRafael Espindola 969778fcc77SRafael Espindola bool LinkFromSrc = true; 970778fcc77SRafael Espindola Comdat *C = nullptr; 971778fcc77SRafael Espindola GlobalValue::VisibilityTypes Visibility = SGV->getVisibility(); 972778fcc77SRafael Espindola bool HasUnnamedAddr = SGV->hasUnnamedAddr(); 973778fcc77SRafael Espindola 974dad0a645SDavid Majnemer if (const Comdat *SC = SGV->getComdat()) { 975dad0a645SDavid Majnemer Comdat::SelectionKind SK; 976dad0a645SDavid Majnemer std::tie(SK, LinkFromSrc) = ComdatsChosen[SC]; 977778fcc77SRafael Espindola C = DstM->getOrInsertComdat(SC->getName()); 978778fcc77SRafael Espindola C->setSelectionKind(SK); 979778fcc77SRafael Espindola } else if (DGV) { 980778fcc77SRafael Espindola if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV)) 981fc61de39SChris Lattner return true; 982dad0a645SDavid Majnemer } 98334fc5a0eSChris Lattner 984dad0a645SDavid Majnemer if (!LinkFromSrc) { 985cbb91408STanya Lattner // Track the source global so that we don't attempt to copy it over when 986cbb91408STanya Lattner // processing global initializers. 987cbb91408STanya Lattner DoNotLinkFromSource.insert(SGV); 988cbb91408STanya Lattner 989778fcc77SRafael Espindola if (DGV) 990778fcc77SRafael Espindola // Make sure to remember this mapping. 991778fcc77SRafael Espindola ValueMap[SGV] = 992778fcc77SRafael Espindola ConstantExpr::getBitCast(DGV, TypeMap.get(SGV->getType())); 993778fcc77SRafael Espindola } 994778fcc77SRafael Espindola 995778fcc77SRafael Espindola if (DGV) { 996778fcc77SRafael Espindola Visibility = isLessConstraining(Visibility, DGV->getVisibility()) 997778fcc77SRafael Espindola ? DGV->getVisibility() 998778fcc77SRafael Espindola : Visibility; 999778fcc77SRafael Espindola HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr(); 1000778fcc77SRafael Espindola } 1001778fcc77SRafael Espindola 1002778fcc77SRafael Espindola if (!LinkFromSrc && !DGV) 1003dad0a645SDavid Majnemer return false; 1004778fcc77SRafael Espindola 1005778fcc77SRafael Espindola GlobalValue *NewGV; 1006778fcc77SRafael Espindola if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { 1007778fcc77SRafael Espindola NewGV = linkGlobalVariableProto(SGVar, DGV, LinkFromSrc); 1008778fcc77SRafael Espindola if (!NewGV) 1009778fcc77SRafael Espindola return true; 1010778fcc77SRafael Espindola } else if (auto *SF = dyn_cast<Function>(SGV)) { 1011778fcc77SRafael Espindola NewGV = linkFunctionProto(SF, DGV, LinkFromSrc); 1012778fcc77SRafael Espindola } else { 1013778fcc77SRafael Espindola NewGV = linkGlobalAliasProto(cast<GlobalAlias>(SGV), DGV, LinkFromSrc); 1014778fcc77SRafael Espindola } 1015778fcc77SRafael Espindola 1016778fcc77SRafael Espindola if (NewGV) { 1017778fcc77SRafael Espindola if (NewGV != DGV) 1018778fcc77SRafael Espindola copyGVAttributes(NewGV, SGV); 1019778fcc77SRafael Espindola 1020778fcc77SRafael Espindola NewGV->setUnnamedAddr(HasUnnamedAddr); 1021778fcc77SRafael Espindola NewGV->setVisibility(Visibility); 1022778fcc77SRafael Espindola 1023778fcc77SRafael Espindola if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) { 1024778fcc77SRafael Espindola if (C) 1025778fcc77SRafael Espindola NewGO->setComdat(C); 1026778fcc77SRafael Espindola } 1027778fcc77SRafael Espindola 1028778fcc77SRafael Espindola // Make sure to remember this mapping. 1029778fcc77SRafael Espindola if (NewGV != DGV) { 1030778fcc77SRafael Espindola if (DGV) { 1031778fcc77SRafael Espindola DGV->replaceAllUsesWith( 1032778fcc77SRafael Espindola ConstantExpr::getBitCast(NewGV, DGV->getType())); 1033778fcc77SRafael Espindola DGV->eraseFromParent(); 1034778fcc77SRafael Espindola } 1035778fcc77SRafael Espindola ValueMap[SGV] = NewGV; 1036dad0a645SDavid Majnemer } 10374e27567aSRafael Espindola } 10384e27567aSRafael Espindola 1039fd38af2dSChandler Carruth return false; 10404e27567aSRafael Espindola } 10414e27567aSRafael Espindola 1042778fcc77SRafael Espindola /// Loop through the global variables in the src module and merge them into the 1043778fcc77SRafael Espindola /// dest module. 1044778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalVariableProto(const GlobalVariable *SGVar, 1045778fcc77SRafael Espindola GlobalValue *DGV, 1046778fcc77SRafael Espindola bool LinkFromSrc) { 1047778fcc77SRafael Espindola unsigned Alignment = 0; 1048778fcc77SRafael Espindola bool ClearConstant = false; 1049778fcc77SRafael Espindola 1050778fcc77SRafael Espindola if (DGV) { 1051778fcc77SRafael Espindola if (DGV->hasCommonLinkage() && SGVar->hasCommonLinkage()) 1052778fcc77SRafael Espindola Alignment = std::max(SGVar->getAlignment(), DGV->getAlignment()); 1053778fcc77SRafael Espindola 1054778fcc77SRafael Espindola auto *DGVar = dyn_cast<GlobalVariable>(DGV); 1055778fcc77SRafael Espindola if (!SGVar->isConstant() || (DGVar && !DGVar->isConstant())) 1056778fcc77SRafael Espindola ClearConstant = true; 1057778fcc77SRafael Espindola } 1058778fcc77SRafael Espindola 1059778fcc77SRafael Espindola if (!LinkFromSrc) { 1060778fcc77SRafael Espindola if (auto *NewGVar = dyn_cast<GlobalVariable>(DGV)) { 1061778fcc77SRafael Espindola if (Alignment) 1062778fcc77SRafael Espindola NewGVar->setAlignment(Alignment); 1063778fcc77SRafael Espindola if (NewGVar->isDeclaration() && ClearConstant) 1064778fcc77SRafael Espindola NewGVar->setConstant(false); 1065778fcc77SRafael Espindola } 1066778fcc77SRafael Espindola return DGV; 1067778fcc77SRafael Espindola } 1068778fcc77SRafael Espindola 1069b1ed91f3SChris Lattner // No linking to be performed or linking from the source: simply create an 1070b1ed91f3SChris Lattner // identical version of the symbol over in the dest module... the 1071b1ed91f3SChris Lattner // initializer will be filled in later by LinkGlobalInits. 1072778fcc77SRafael Espindola GlobalVariable *NewDGV = new GlobalVariable( 1073778fcc77SRafael Espindola *DstM, TypeMap.get(SGVar->getType()->getElementType()), 1074778fcc77SRafael Espindola SGVar->isConstant(), SGVar->getLinkage(), /*init*/ nullptr, 1075778fcc77SRafael Espindola SGVar->getName(), /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), 1076778fcc77SRafael Espindola SGVar->getType()->getAddressSpace()); 1077778fcc77SRafael Espindola 1078778fcc77SRafael Espindola if (Alignment) 1079fe3842cdSRafael Espindola NewDGV->setAlignment(Alignment); 1080b1ed91f3SChris Lattner 1081778fcc77SRafael Espindola return NewDGV; 1082361e513dSReid Spencer } 1083361e513dSReid Spencer 108418c89411SRafael Espindola /// Link the function in the source module into the destination module if 108518c89411SRafael Espindola /// needed, setting up mapping information. 1086778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkFunctionProto(const Function *SF, 1087778fcc77SRafael Espindola GlobalValue *DGV, 1088778fcc77SRafael Espindola bool LinkFromSrc) { 1089778fcc77SRafael Espindola if (!LinkFromSrc) 1090778fcc77SRafael Espindola return DGV; 1091b1ed91f3SChris Lattner 1092f6f121e2SJames Molloy // If the function is to be lazily linked, don't create it just yet. 1093f6f121e2SJames Molloy // The ValueMaterializerTy will deal with creating it if it's used. 1094f6f121e2SJames Molloy if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() || 1095f6f121e2SJames Molloy SF->hasAvailableExternallyLinkage())) { 1096f6f121e2SJames Molloy DoNotLinkFromSource.insert(SF); 1097778fcc77SRafael Espindola return nullptr; 1098dad0a645SDavid Majnemer } 1099dad0a645SDavid Majnemer 1100b1ed91f3SChris Lattner // If there is no linkage to be performed or we are linking from the source, 1101b1ed91f3SChris Lattner // bring SF over. 1102778fcc77SRafael Espindola return Function::Create(TypeMap.get(SF->getFunctionType()), SF->getLinkage(), 1103778fcc77SRafael Espindola SF->getName(), DstM); 1104361e513dSReid Spencer } 1105361e513dSReid Spencer 110618c89411SRafael Espindola /// Set up prototypes for any aliases that come over from the source module. 1107778fcc77SRafael Espindola GlobalValue *ModuleLinker::linkGlobalAliasProto(const GlobalAlias *SGA, 1108778fcc77SRafael Espindola GlobalValue *DGV, 1109778fcc77SRafael Espindola bool LinkFromSrc) { 1110778fcc77SRafael Espindola if (!LinkFromSrc) 1111778fcc77SRafael Espindola return DGV; 1112dad0a645SDavid Majnemer 1113b1ed91f3SChris Lattner // If there is no linkage to be performed or we're linking from the source, 1114b1ed91f3SChris Lattner // bring over SGA. 11154fe0094fSRafael Espindola auto *PTy = cast<PointerType>(TypeMap.get(SGA->getType())); 1116778fcc77SRafael Espindola return GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), 111783705658SRafael Espindola SGA->getLinkage(), SGA->getName(), DstM); 1118b1ed91f3SChris Lattner } 1119b1ed91f3SChris Lattner 11203e8bc6a8SRafael Espindola static void getArrayElements(const Constant *C, 11213e8bc6a8SRafael Espindola SmallVectorImpl<Constant *> &Dest) { 11226705883aSChris Lattner unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); 112300245f42SChris Lattner 11246705883aSChris Lattner for (unsigned i = 0; i != NumElements; ++i) 11256705883aSChris Lattner Dest.push_back(C->getAggregateElement(i)); 112600245f42SChris Lattner } 112700245f42SChris Lattner 1128b1ed91f3SChris Lattner void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) { 1129b1ed91f3SChris Lattner // Merge the initializer. 1130d31dc048SRafael Espindola SmallVector<Constant *, 16> DstElements; 1131d31dc048SRafael Espindola getArrayElements(AVI.DstInit, DstElements); 1132b1ed91f3SChris Lattner 1133d31dc048SRafael Espindola SmallVector<Constant *, 16> SrcElements; 1134d31dc048SRafael Espindola getArrayElements(AVI.SrcInit, SrcElements); 113500245f42SChris Lattner 1136b1ed91f3SChris Lattner ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType()); 1137d31dc048SRafael Espindola 1138d31dc048SRafael Espindola StringRef Name = AVI.NewGV->getName(); 1139d31dc048SRafael Espindola bool IsNewStructor = 1140d31dc048SRafael Espindola (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") && 1141d31dc048SRafael Espindola cast<StructType>(NewType->getElementType())->getNumElements() == 3; 1142d31dc048SRafael Espindola 1143d31dc048SRafael Espindola for (auto *V : SrcElements) { 1144d31dc048SRafael Espindola if (IsNewStructor) { 1145d31dc048SRafael Espindola Constant *Key = V->getAggregateElement(2); 1146d31dc048SRafael Espindola if (DoNotLinkFromSource.count(Key)) 1147d31dc048SRafael Espindola continue; 1148d31dc048SRafael Espindola } 1149d31dc048SRafael Espindola DstElements.push_back( 1150d31dc048SRafael Espindola MapValue(V, ValueMap, RF_None, &TypeMap, &ValMaterializer)); 1151d31dc048SRafael Espindola } 1152d31dc048SRafael Espindola if (IsNewStructor) { 1153d31dc048SRafael Espindola NewType = ArrayType::get(NewType->getElementType(), DstElements.size()); 1154d31dc048SRafael Espindola AVI.NewGV->mutateType(PointerType::get(NewType, 0)); 1155d31dc048SRafael Espindola } 1156d31dc048SRafael Espindola 1157d31dc048SRafael Espindola AVI.NewGV->setInitializer(ConstantArray::get(NewType, DstElements)); 1158b1ed91f3SChris Lattner } 1159b1ed91f3SChris Lattner 116018c89411SRafael Espindola /// Update the initializers in the Dest module now that all globals that may be 116118c89411SRafael Espindola /// referenced are in Dest. 1162b1ed91f3SChris Lattner void ModuleLinker::linkGlobalInits() { 1163b1ed91f3SChris Lattner // Loop over all of the globals in the src module, mapping them over as we go 1164b1ed91f3SChris Lattner for (Module::const_global_iterator I = SrcM->global_begin(), 1165b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) { 1166cbb91408STanya Lattner 1167cbb91408STanya Lattner // Only process initialized GV's or ones not already in dest. 1168cbb91408STanya Lattner if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue; 1169b1ed91f3SChris Lattner 1170b1ed91f3SChris Lattner // Grab destination global variable. 1171b1ed91f3SChris Lattner GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]); 1172b1ed91f3SChris Lattner // Figure out what the initializer looks like in the dest module. 1173b1ed91f3SChris Lattner DGV->setInitializer(MapValue(I->getInitializer(), ValueMap, 1174f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1175b1ed91f3SChris Lattner } 1176b1ed91f3SChris Lattner } 1177b1ed91f3SChris Lattner 117818c89411SRafael Espindola /// Copy the source function over into the dest function and fix up references 117918c89411SRafael Espindola /// to values. At this point we know that Dest is an external function, and 118018c89411SRafael Espindola /// that Src is not. 1181b1ed91f3SChris Lattner void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) { 1182b1ed91f3SChris Lattner assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration()); 1183361e513dSReid Spencer 11847391dde1SChris Lattner // Go through and convert function arguments over, remembering the mapping. 1185b1ed91f3SChris Lattner Function::arg_iterator DI = Dst->arg_begin(); 1186531f9e92SChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 1187361e513dSReid Spencer I != E; ++I, ++DI) { 1188b1ed91f3SChris Lattner DI->setName(I->getName()); // Copy the name over. 1189361e513dSReid Spencer 1190b1ed91f3SChris Lattner // Add a mapping to our mapping. 119166a6271cSAnton Korobeynikov ValueMap[I] = DI; 1192361e513dSReid Spencer } 1193361e513dSReid Spencer 11942f0557d0SChris Lattner // Splice the body of the source function into the dest function. 1195b1ed91f3SChris Lattner Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList()); 1196361e513dSReid Spencer 1197361e513dSReid Spencer // At this point, all of the instructions and values of the function are now 1198361e513dSReid Spencer // copied over. The only problem is that they are still referencing values in 1199361e513dSReid Spencer // the Source function as operands. Loop through all of the operands of the 120043f8d164SChris Lattner // functions and patch them up to point to the local versions. 1201b1ed91f3SChris Lattner for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB) 120243f8d164SChris Lattner for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) 12039f8eff31SRafael Espindola RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap, 12049f8eff31SRafael Espindola &ValMaterializer); 1205cbb91408STanya Lattner 12067391dde1SChris Lattner // There is no need to map the arguments anymore. 120744ab8aefSChris Lattner for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end(); 120844ab8aefSChris Lattner I != E; ++I) 12093aaaa0b2SReid Spencer ValueMap.erase(I); 1210cbb91408STanya Lattner 1211361e513dSReid Spencer } 1212361e513dSReid Spencer 121318c89411SRafael Espindola /// Insert all of the aliases in Src into the Dest module. 1214b1ed91f3SChris Lattner void ModuleLinker::linkAliasBodies() { 1215b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end(); 1216cbb91408STanya Lattner I != E; ++I) { 1217cbb91408STanya Lattner if (DoNotLinkFromSource.count(I)) 1218cbb91408STanya Lattner continue; 1219b1ed91f3SChris Lattner if (Constant *Aliasee = I->getAliasee()) { 1220b1ed91f3SChris Lattner GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]); 12216b238633SRafael Espindola Constant *Val = 12226b238633SRafael Espindola MapValue(Aliasee, ValueMap, RF_None, &TypeMap, &ValMaterializer); 122364c1e180SRafael Espindola DA->setAliasee(Val); 12242c4a34aeSDavid Chisnall } 1225b1ed91f3SChris Lattner } 1226cbb91408STanya Lattner } 1227b1ed91f3SChris Lattner 122818c89411SRafael Espindola /// Insert all of the named MDNodes in Src into the Dest module. 1229b1ed91f3SChris Lattner void ModuleLinker::linkNamedMDNodes() { 123066f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 1231b1ed91f3SChris Lattner for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), 1232b1ed91f3SChris Lattner E = SrcM->named_metadata_end(); I != E; ++I) { 123366f02413SBill Wendling // Don't link module flags here. Do them separately. 123466f02413SBill Wendling if (&*I == SrcModFlags) continue; 1235b1ed91f3SChris Lattner NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); 1236b1ed91f3SChris Lattner // Add Src elements into Dest node. 1237b1ed91f3SChris Lattner for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) 1238b1ed91f3SChris Lattner DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, 1239f6f121e2SJames Molloy RF_None, &TypeMap, &ValMaterializer)); 1240b1ed91f3SChris Lattner } 1241b1ed91f3SChris Lattner } 1242b1ed91f3SChris Lattner 124318c89411SRafael Espindola /// Merge the linker flags in Src into the Dest module. 124466f02413SBill Wendling bool ModuleLinker::linkModuleFlagsMetadata() { 12450ec72bbcSDaniel Dunbar // If the source module has no module flags, we are done. 124666f02413SBill Wendling const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); 124766f02413SBill Wendling if (!SrcModFlags) return false; 124866f02413SBill Wendling 124966f02413SBill Wendling // If the destination module doesn't have module flags yet, then just copy 125066f02413SBill Wendling // over the source module's flags. 12510ec72bbcSDaniel Dunbar NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); 125266f02413SBill Wendling if (DstModFlags->getNumOperands() == 0) { 125366f02413SBill Wendling for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) 125466f02413SBill Wendling DstModFlags->addOperand(SrcModFlags->getOperand(I)); 125566f02413SBill Wendling 125666f02413SBill Wendling return false; 125766f02413SBill Wendling } 125866f02413SBill Wendling 12590ec72bbcSDaniel Dunbar // First build a map of the existing module flags and requirements. 12600ec72bbcSDaniel Dunbar DenseMap<MDString*, MDNode*> Flags; 12610ec72bbcSDaniel Dunbar SmallSetVector<MDNode*, 16> Requirements; 12620ec72bbcSDaniel Dunbar for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { 1263de36e804SDuncan P. N. Exon Smith MDNode *Op = DstModFlags->getOperand(I); 12640ec72bbcSDaniel Dunbar ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0)); 12650ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(Op->getOperand(1)); 12660ec72bbcSDaniel Dunbar 12670ec72bbcSDaniel Dunbar if (Behavior->getZExtValue() == Module::Require) { 12680ec72bbcSDaniel Dunbar Requirements.insert(cast<MDNode>(Op->getOperand(2))); 12690ec72bbcSDaniel Dunbar } else { 12700ec72bbcSDaniel Dunbar Flags[ID] = Op; 12710ec72bbcSDaniel Dunbar } 12720ec72bbcSDaniel Dunbar } 12730ec72bbcSDaniel Dunbar 12740ec72bbcSDaniel Dunbar // Merge in the flags from the source module, and also collect its set of 12750ec72bbcSDaniel Dunbar // requirements. 127666f02413SBill Wendling bool HasErr = false; 12770ec72bbcSDaniel Dunbar for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { 1278de36e804SDuncan P. N. Exon Smith MDNode *SrcOp = SrcModFlags->getOperand(I); 12790ec72bbcSDaniel Dunbar ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0)); 12800ec72bbcSDaniel Dunbar MDString *ID = cast<MDString>(SrcOp->getOperand(1)); 12810ec72bbcSDaniel Dunbar MDNode *DstOp = Flags.lookup(ID); 12820ec72bbcSDaniel Dunbar unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); 128366f02413SBill Wendling 12840ec72bbcSDaniel Dunbar // If this is a requirement, add it and continue. 12850ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Require) { 12860ec72bbcSDaniel Dunbar // If the destination module does not already have this requirement, add 12870ec72bbcSDaniel Dunbar // it. 12880ec72bbcSDaniel Dunbar if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { 12890ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 12900ec72bbcSDaniel Dunbar } 12910ec72bbcSDaniel Dunbar continue; 12920ec72bbcSDaniel Dunbar } 129366f02413SBill Wendling 12940ec72bbcSDaniel Dunbar // If there is no existing flag with this ID, just add it. 12950ec72bbcSDaniel Dunbar if (!DstOp) { 12960ec72bbcSDaniel Dunbar Flags[ID] = SrcOp; 12970ec72bbcSDaniel Dunbar DstModFlags->addOperand(SrcOp); 12980ec72bbcSDaniel Dunbar continue; 12990ec72bbcSDaniel Dunbar } 130066f02413SBill Wendling 13010ec72bbcSDaniel Dunbar // Otherwise, perform a merge. 13020ec72bbcSDaniel Dunbar ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0)); 13030ec72bbcSDaniel Dunbar unsigned DstBehaviorValue = DstBehavior->getZExtValue(); 13040ec72bbcSDaniel Dunbar 13050ec72bbcSDaniel Dunbar // If either flag has override behavior, handle it first. 13060ec72bbcSDaniel Dunbar if (DstBehaviorValue == Module::Override) { 13070ec72bbcSDaniel Dunbar // Diagnose inconsistent flags which both have override behavior. 13080ec72bbcSDaniel Dunbar if (SrcBehaviorValue == Module::Override && 13090ec72bbcSDaniel Dunbar SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13100ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13110ec72bbcSDaniel Dunbar "': IDs have conflicting override values"); 13120ec72bbcSDaniel Dunbar } 13130ec72bbcSDaniel Dunbar continue; 13140ec72bbcSDaniel Dunbar } else if (SrcBehaviorValue == Module::Override) { 13150ec72bbcSDaniel Dunbar // Update the destination flag to that of the source. 13160ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(0, SrcBehavior); 13170ec72bbcSDaniel Dunbar DstOp->replaceOperandWith(2, SrcOp->getOperand(2)); 13180ec72bbcSDaniel Dunbar continue; 13190ec72bbcSDaniel Dunbar } 13200ec72bbcSDaniel Dunbar 13210ec72bbcSDaniel Dunbar // Diagnose inconsistent merge behavior types. 13220ec72bbcSDaniel Dunbar if (SrcBehaviorValue != DstBehaviorValue) { 13230ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 132466f02413SBill Wendling "': IDs have conflicting behaviors"); 13250ec72bbcSDaniel Dunbar continue; 132666f02413SBill Wendling } 132766f02413SBill Wendling 13280ec72bbcSDaniel Dunbar // Perform the merge for standard behavior types. 13290ec72bbcSDaniel Dunbar switch (SrcBehaviorValue) { 13300ec72bbcSDaniel Dunbar case Module::Require: 13312a30d788SCraig Topper case Module::Override: llvm_unreachable("not possible"); 13320ec72bbcSDaniel Dunbar case Module::Error: { 13330ec72bbcSDaniel Dunbar // Emit an error if the values differ. 13340ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 13350ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + ID->getString() + 13360ec72bbcSDaniel Dunbar "': IDs have conflicting values"); 133766f02413SBill Wendling } 13380ec72bbcSDaniel Dunbar continue; 133966f02413SBill Wendling } 13400ec72bbcSDaniel Dunbar case Module::Warning: { 13410ec72bbcSDaniel Dunbar // Emit a warning if the values differ. 13420ec72bbcSDaniel Dunbar if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { 1343d12b4a33SRafael Espindola emitWarning("linking module flags '" + ID->getString() + 1344d12b4a33SRafael Espindola "': IDs have conflicting values"); 1345e17f3708SEli Bendersky } 13460ec72bbcSDaniel Dunbar continue; 13470ec72bbcSDaniel Dunbar } 1348d77d9fb0SDaniel Dunbar case Module::Append: { 1349d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1350d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1351d77d9fb0SDaniel Dunbar unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands(); 1352d77d9fb0SDaniel Dunbar Value **VP, **Values = VP = new Value*[NumOps]; 1353d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP) 1354d77d9fb0SDaniel Dunbar *VP = DstValue->getOperand(i); 1355d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP) 1356d77d9fb0SDaniel Dunbar *VP = SrcValue->getOperand(i); 1357d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1358d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Values, 1359d77d9fb0SDaniel Dunbar NumOps))); 1360d77d9fb0SDaniel Dunbar delete[] Values; 1361d77d9fb0SDaniel Dunbar break; 1362d77d9fb0SDaniel Dunbar } 1363d77d9fb0SDaniel Dunbar case Module::AppendUnique: { 1364d77d9fb0SDaniel Dunbar SmallSetVector<Value*, 16> Elts; 1365d77d9fb0SDaniel Dunbar MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); 1366d77d9fb0SDaniel Dunbar MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); 1367d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i) 1368d77d9fb0SDaniel Dunbar Elts.insert(DstValue->getOperand(i)); 1369d77d9fb0SDaniel Dunbar for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i) 1370d77d9fb0SDaniel Dunbar Elts.insert(SrcValue->getOperand(i)); 1371d77d9fb0SDaniel Dunbar DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(), 1372d77d9fb0SDaniel Dunbar ArrayRef<Value*>(Elts.begin(), 1373d77d9fb0SDaniel Dunbar Elts.end()))); 1374d77d9fb0SDaniel Dunbar break; 1375d77d9fb0SDaniel Dunbar } 137666f02413SBill Wendling } 137766f02413SBill Wendling } 137866f02413SBill Wendling 13790ec72bbcSDaniel Dunbar // Check all of the requirements. 13800ec72bbcSDaniel Dunbar for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { 13810ec72bbcSDaniel Dunbar MDNode *Requirement = Requirements[I]; 13820ec72bbcSDaniel Dunbar MDString *Flag = cast<MDString>(Requirement->getOperand(0)); 13830ec72bbcSDaniel Dunbar Value *ReqValue = Requirement->getOperand(1); 13840ec72bbcSDaniel Dunbar 13850ec72bbcSDaniel Dunbar MDNode *Op = Flags[Flag]; 13860ec72bbcSDaniel Dunbar if (!Op || Op->getOperand(2) != ReqValue) { 13870ec72bbcSDaniel Dunbar HasErr |= emitError("linking module flags '" + Flag->getString() + 13889273b539SBill Wendling "': does not have the required value"); 13890ec72bbcSDaniel Dunbar continue; 139066f02413SBill Wendling } 139166f02413SBill Wendling } 139266f02413SBill Wendling 139366f02413SBill Wendling return HasErr; 139466f02413SBill Wendling } 139566f02413SBill Wendling 1396b1ed91f3SChris Lattner bool ModuleLinker::run() { 139766f02413SBill Wendling assert(DstM && "Null destination module"); 139866f02413SBill Wendling assert(SrcM && "Null source module"); 1399b1ed91f3SChris Lattner 1400b1ed91f3SChris Lattner // Inherit the target data from the source module if the destination module 1401b1ed91f3SChris Lattner // doesn't have one already. 1402f863ee29SRafael Espindola if (!DstM->getDataLayout() && SrcM->getDataLayout()) 1403b1ed91f3SChris Lattner DstM->setDataLayout(SrcM->getDataLayout()); 1404b1ed91f3SChris Lattner 1405b1ed91f3SChris Lattner // Copy the target triple from the source to dest if the dest's is empty. 1406b1ed91f3SChris Lattner if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) 1407b1ed91f3SChris Lattner DstM->setTargetTriple(SrcM->getTargetTriple()); 1408b1ed91f3SChris Lattner 1409f863ee29SRafael Espindola if (SrcM->getDataLayout() && DstM->getDataLayout() && 1410ae593f15SRafael Espindola *SrcM->getDataLayout() != *DstM->getDataLayout()) { 1411d12b4a33SRafael Espindola emitWarning("Linking two modules of different data layouts: '" + 1412d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1413d12b4a33SRafael Espindola SrcM->getDataLayoutStr() + "' whereas '" + 1414d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1415d12b4a33SRafael Espindola DstM->getDataLayoutStr() + "'\n"); 1416e17f3708SEli Bendersky } 1417b1ed91f3SChris Lattner if (!SrcM->getTargetTriple().empty() && 1418b1ed91f3SChris Lattner DstM->getTargetTriple() != SrcM->getTargetTriple()) { 1419d12b4a33SRafael Espindola emitWarning("Linking two modules of different target triples: " + 1420d12b4a33SRafael Espindola SrcM->getModuleIdentifier() + "' is '" + 1421d12b4a33SRafael Espindola SrcM->getTargetTriple() + "' whereas '" + 1422d12b4a33SRafael Espindola DstM->getModuleIdentifier() + "' is '" + 1423d12b4a33SRafael Espindola DstM->getTargetTriple() + "'\n"); 1424e17f3708SEli Bendersky } 1425b1ed91f3SChris Lattner 1426b1ed91f3SChris Lattner // Append the module inline asm string. 1427b1ed91f3SChris Lattner if (!SrcM->getModuleInlineAsm().empty()) { 1428b1ed91f3SChris Lattner if (DstM->getModuleInlineAsm().empty()) 1429b1ed91f3SChris Lattner DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm()); 1430b1ed91f3SChris Lattner else 1431b1ed91f3SChris Lattner DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+ 1432b1ed91f3SChris Lattner SrcM->getModuleInlineAsm()); 1433b1ed91f3SChris Lattner } 1434b1ed91f3SChris Lattner 1435b1ed91f3SChris Lattner // Loop over all of the linked values to compute type mappings. 1436b1ed91f3SChris Lattner computeTypeMapping(); 1437b1ed91f3SChris Lattner 1438dad0a645SDavid Majnemer ComdatsChosen.clear(); 14395106ce78SDavid Blaikie for (const auto &SMEC : SrcM->getComdatSymbolTable()) { 1440dad0a645SDavid Majnemer const Comdat &C = SMEC.getValue(); 1441dad0a645SDavid Majnemer if (ComdatsChosen.count(&C)) 1442dad0a645SDavid Majnemer continue; 1443dad0a645SDavid Majnemer Comdat::SelectionKind SK; 1444dad0a645SDavid Majnemer bool LinkFromSrc; 1445dad0a645SDavid Majnemer if (getComdatResult(&C, SK, LinkFromSrc)) 1446dad0a645SDavid Majnemer return true; 1447dad0a645SDavid Majnemer ComdatsChosen[&C] = std::make_pair(SK, LinkFromSrc); 1448dad0a645SDavid Majnemer } 1449dad0a645SDavid Majnemer 145009d84addSDuncan P. N. Exon Smith // Upgrade mismatched global arrays. 145109d84addSDuncan P. N. Exon Smith upgradeMismatchedGlobals(); 145209d84addSDuncan P. N. Exon Smith 1453b1ed91f3SChris Lattner // Insert all of the globals in src into the DstM module... without linking 1454b1ed91f3SChris Lattner // initializers (which could refer to functions not yet mapped over). 1455b1ed91f3SChris Lattner for (Module::global_iterator I = SrcM->global_begin(), 1456b1ed91f3SChris Lattner E = SrcM->global_end(); I != E; ++I) 1457778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1458b1ed91f3SChris Lattner return true; 1459b1ed91f3SChris Lattner 1460b1ed91f3SChris Lattner // Link the functions together between the two modules, without doing function 1461b1ed91f3SChris Lattner // bodies... this just adds external function prototypes to the DstM 1462b1ed91f3SChris Lattner // function... We do this so that when we begin processing function bodies, 1463b1ed91f3SChris Lattner // all of the global values that may be referenced are available in our 1464b1ed91f3SChris Lattner // ValueMap. 1465b1ed91f3SChris Lattner for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) 1466778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1467b1ed91f3SChris Lattner return true; 1468b1ed91f3SChris Lattner 1469b1ed91f3SChris Lattner // If there were any aliases, link them now. 1470b1ed91f3SChris Lattner for (Module::alias_iterator I = SrcM->alias_begin(), 1471b1ed91f3SChris Lattner E = SrcM->alias_end(); I != E; ++I) 1472778fcc77SRafael Espindola if (linkGlobalValueProto(I)) 1473b1ed91f3SChris Lattner return true; 1474b1ed91f3SChris Lattner 1475b1ed91f3SChris Lattner for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i) 1476b1ed91f3SChris Lattner linkAppendingVarInit(AppendingVars[i]); 1477b1ed91f3SChris Lattner 1478b1ed91f3SChris Lattner // Link in the function bodies that are defined in the source module into 1479b1ed91f3SChris Lattner // DstM. 1480b1ed91f3SChris Lattner for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) { 1481ea166d44STanya Lattner // Skip if not linking from source. 1482ea166d44STanya Lattner if (DoNotLinkFromSource.count(SF)) continue; 1483ea166d44STanya Lattner 14843fa50f9bSPeter Collingbourne Function *DF = cast<Function>(ValueMap[SF]); 14853fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 14863fa50f9bSPeter Collingbourne // Link in the prefix data. 14873fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue( 14883fa50f9bSPeter Collingbourne SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer)); 14893fa50f9bSPeter Collingbourne } 14903fa50f9bSPeter Collingbourne 1491d4bcefc7SRafael Espindola // Materialize if needed. 1492d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1493d12b4a33SRafael Espindola return emitError(EC.message()); 1494b1ed91f3SChris Lattner 1495d4bcefc7SRafael Espindola // Skip if no body (function is external). 1496d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1497d4bcefc7SRafael Espindola continue; 1498d4bcefc7SRafael Espindola 14993fa50f9bSPeter Collingbourne linkFunctionBody(DF, SF); 150000623787SBill Wendling SF->Dematerialize(); 1501b1ed91f3SChris Lattner } 1502b1ed91f3SChris Lattner 1503b1ed91f3SChris Lattner // Resolve all uses of aliases with aliasees. 1504b1ed91f3SChris Lattner linkAliasBodies(); 1505b1ed91f3SChris Lattner 150666f02413SBill Wendling // Remap all of the named MDNodes in Src into the DstM module. We do this 15076ddbb2e2SDevang Patel // after linking GlobalValues so that MDNodes that reference GlobalValues 15086ddbb2e2SDevang Patel // are properly remapped. 15096ddbb2e2SDevang Patel linkNamedMDNodes(); 15106ddbb2e2SDevang Patel 151166f02413SBill Wendling // Merge the module flags into the DstM module. 151266f02413SBill Wendling if (linkModuleFlagsMetadata()) 151366f02413SBill Wendling return true; 151466f02413SBill Wendling 151591686d6dSBill Wendling // Update the initializers in the DstM module now that all globals that may 151691686d6dSBill Wendling // be referenced are in DstM. 151791686d6dSBill Wendling linkGlobalInits(); 151891686d6dSBill Wendling 15190a48b877STanya Lattner // Process vector of lazily linked in functions. 15200a48b877STanya Lattner bool LinkedInAnyFunctions; 15210a48b877STanya Lattner do { 15220a48b877STanya Lattner LinkedInAnyFunctions = false; 15230a48b877STanya Lattner 1524fa228782SBill Wendling for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(), 15250a48b877STanya Lattner E = LazilyLinkFunctions.end(); I != E; ++I) { 1526f6f121e2SJames Molloy Function *SF = *I; 1527f6f121e2SJames Molloy if (!SF) 15280a48b877STanya Lattner continue; 15290a48b877STanya Lattner 1530fa228782SBill Wendling Function *DF = cast<Function>(ValueMap[SF]); 15313fa50f9bSPeter Collingbourne if (SF->hasPrefixData()) { 15323fa50f9bSPeter Collingbourne // Link in the prefix data. 15333fa50f9bSPeter Collingbourne DF->setPrefixData(MapValue(SF->getPrefixData(), 15343fa50f9bSPeter Collingbourne ValueMap, 15353fa50f9bSPeter Collingbourne RF_None, 15363fa50f9bSPeter Collingbourne &TypeMap, 15373fa50f9bSPeter Collingbourne &ValMaterializer)); 15383fa50f9bSPeter Collingbourne } 15390a48b877STanya Lattner 1540d4bcefc7SRafael Espindola // Materialize if needed. 1541d12b4a33SRafael Espindola if (std::error_code EC = SF->materialize()) 1542d12b4a33SRafael Espindola return emitError(EC.message()); 15430a48b877STanya Lattner 1544d4bcefc7SRafael Espindola // Skip if no body (function is external). 1545d4bcefc7SRafael Espindola if (SF->isDeclaration()) 1546d4bcefc7SRafael Espindola continue; 1547d4bcefc7SRafael Espindola 1548f6f121e2SJames Molloy // Erase from vector *before* the function body is linked - linkFunctionBody could 1549f6f121e2SJames Molloy // invalidate I. 1550f6f121e2SJames Molloy LazilyLinkFunctions.erase(I); 1551f6f121e2SJames Molloy 15520a48b877STanya Lattner // Link in function body. 15530a48b877STanya Lattner linkFunctionBody(DF, SF); 155400623787SBill Wendling SF->Dematerialize(); 15550a48b877STanya Lattner 15560a48b877STanya Lattner // Set flag to indicate we may have more functions to lazily link in 15570a48b877STanya Lattner // since we linked in a function. 15580a48b877STanya Lattner LinkedInAnyFunctions = true; 1559f6f121e2SJames Molloy break; 15600a48b877STanya Lattner } 15610a48b877STanya Lattner } while (LinkedInAnyFunctions); 15620a48b877STanya Lattner 15632609888fSAnton Korobeynikov return false; 15642609888fSAnton Korobeynikov } 1565361e513dSReid Spencer 15665cb9c82aSRafael Espindola void Linker::init(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15675cb9c82aSRafael Espindola this->Composite = M; 15685cb9c82aSRafael Espindola this->DiagnosticHandler = DiagnosticHandler; 15694160f5d3SRafael Espindola 1570aa9918aaSRafael Espindola TypeFinder StructTypes; 1571aa9918aaSRafael Espindola StructTypes.run(*M, true); 1572aa9918aaSRafael Espindola IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end()); 1573aa9918aaSRafael Espindola } 15743df61b7bSRafael Espindola 15755cb9c82aSRafael Espindola Linker::Linker(Module *M, DiagnosticHandlerFunction DiagnosticHandler) { 15765cb9c82aSRafael Espindola init(M, DiagnosticHandler); 15775cb9c82aSRafael Espindola } 15785cb9c82aSRafael Espindola 15795cb9c82aSRafael Espindola Linker::Linker(Module *M) { 15805cb9c82aSRafael Espindola init(M, [this](const DiagnosticInfo &DI) { 15815cb9c82aSRafael Espindola Composite->getContext().diagnose(DI); 15825cb9c82aSRafael Espindola }); 15835cb9c82aSRafael Espindola } 15845cb9c82aSRafael Espindola 15853df61b7bSRafael Espindola Linker::~Linker() { 15863df61b7bSRafael Espindola } 15873df61b7bSRafael Espindola 158891e6f6e1SBill Wendling void Linker::deleteModule() { 158991e6f6e1SBill Wendling delete Composite; 15902617dcceSCraig Topper Composite = nullptr; 159191e6f6e1SBill Wendling } 159291e6f6e1SBill Wendling 15939f8eff31SRafael Espindola bool Linker::linkInModule(Module *Src) { 15949f8eff31SRafael Espindola ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, 15959f8eff31SRafael Espindola DiagnosticHandler); 1596d12b4a33SRafael Espindola return TheLinker.run(); 15973df61b7bSRafael Espindola } 15983df61b7bSRafael Espindola 1599b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1600b1ed91f3SChris Lattner // LinkModules entrypoint. 1601b1ed91f3SChris Lattner //===----------------------------------------------------------------------===// 1602b1ed91f3SChris Lattner 160318c89411SRafael Espindola /// This function links two modules together, with the resulting Dest module 160418c89411SRafael Espindola /// modified to be the composite of the two input modules. If an error occurs, 160518c89411SRafael Espindola /// true is returned and ErrorMsg (if not null) is set to indicate the problem. 160618c89411SRafael Espindola /// Upon failure, the Dest module could be in a modified state, and shouldn't be 160718c89411SRafael Espindola /// relied on to be consistent. 16089f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src, 16094160f5d3SRafael Espindola DiagnosticHandlerFunction DiagnosticHandler) { 16104160f5d3SRafael Espindola Linker L(Dest, DiagnosticHandler); 16119f8eff31SRafael Espindola return L.linkInModule(Src); 16124160f5d3SRafael Espindola } 16134160f5d3SRafael Espindola 16149f8eff31SRafael Espindola bool Linker::LinkModules(Module *Dest, Module *Src) { 1615287f18b4SRafael Espindola Linker L(Dest); 16169f8eff31SRafael Espindola return L.linkInModule(Src); 1617361e513dSReid Spencer } 1618a3aeb980SBill Wendling 1619a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1620a3aeb980SBill Wendling // C API. 1621a3aeb980SBill Wendling //===----------------------------------------------------------------------===// 1622a3aeb980SBill Wendling 1623a3aeb980SBill Wendling LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src, 1624a3aeb980SBill Wendling LLVMLinkerMode Mode, char **OutMessages) { 162598ab63ceSRafael Espindola Module *D = unwrap(Dest); 162698ab63ceSRafael Espindola std::string Message; 16274160f5d3SRafael Espindola raw_string_ostream Stream(Message); 16284160f5d3SRafael Espindola DiagnosticPrinterRawOStream DP(Stream); 16294160f5d3SRafael Espindola 16304160f5d3SRafael Espindola LLVMBool Result = Linker::LinkModules( 16319f8eff31SRafael Espindola D, unwrap(Src), [&](const DiagnosticInfo &DI) { DI.print(DP); }); 163298ab63ceSRafael Espindola 163398ab63ceSRafael Espindola if (OutMessages && Result) 163498ab63ceSRafael Espindola *OutMessages = strdup(Message.c_str()); 1635a3aeb980SBill Wendling return Result; 1636a3aeb980SBill Wendling } 1637