Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1 | //===- lib/Linker/IRMover.cpp ---------------------------------------------===// |
| 2 | // |
| 3 | // The LLVM Compiler Infrastructure |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | |
| 10 | #include "llvm/Linker/IRMover.h" |
| 11 | #include "LinkDiagnosticInfo.h" |
| 12 | #include "llvm/ADT/SetVector.h" |
| 13 | #include "llvm/ADT/SmallString.h" |
| 14 | #include "llvm/ADT/Triple.h" |
| 15 | #include "llvm/IR/Constants.h" |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 16 | #include "llvm/IR/DebugInfo.h" |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 17 | #include "llvm/IR/DiagnosticPrinter.h" |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 18 | #include "llvm/IR/GVMaterializer.h" |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 19 | #include "llvm/IR/TypeFinder.h" |
| 20 | #include "llvm/Transforms/Utils/Cloning.h" |
| 21 | using namespace llvm; |
| 22 | |
| 23 | //===----------------------------------------------------------------------===// |
| 24 | // TypeMap implementation. |
| 25 | //===----------------------------------------------------------------------===// |
| 26 | |
| 27 | namespace { |
| 28 | class TypeMapTy : public ValueMapTypeRemapper { |
| 29 | /// This is a mapping from a source type to a destination type to use. |
| 30 | DenseMap<Type *, Type *> MappedTypes; |
| 31 | |
| 32 | /// When checking to see if two subgraphs are isomorphic, we speculatively |
| 33 | /// add types to MappedTypes, but keep track of them here in case we need to |
| 34 | /// roll back. |
| 35 | SmallVector<Type *, 16> SpeculativeTypes; |
| 36 | |
| 37 | SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes; |
| 38 | |
| 39 | /// This is a list of non-opaque structs in the source module that are mapped |
| 40 | /// to an opaque struct in the destination module. |
| 41 | SmallVector<StructType *, 16> SrcDefinitionsToResolve; |
| 42 | |
| 43 | /// This is the set of opaque types in the destination modules who are |
| 44 | /// getting a body from the source module. |
| 45 | SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes; |
| 46 | |
| 47 | public: |
| 48 | TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet) |
| 49 | : DstStructTypesSet(DstStructTypesSet) {} |
| 50 | |
| 51 | IRMover::IdentifiedStructTypeSet &DstStructTypesSet; |
| 52 | /// Indicate that the specified type in the destination module is conceptually |
| 53 | /// equivalent to the specified type in the source module. |
| 54 | void addTypeMapping(Type *DstTy, Type *SrcTy); |
| 55 | |
| 56 | /// Produce a body for an opaque type in the dest module from a type |
| 57 | /// definition in the source module. |
| 58 | void linkDefinedTypeBodies(); |
| 59 | |
| 60 | /// Return the mapped type to use for the specified input type from the |
| 61 | /// source module. |
| 62 | Type *get(Type *SrcTy); |
| 63 | Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited); |
| 64 | |
| 65 | void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes); |
| 66 | |
| 67 | FunctionType *get(FunctionType *T) { |
| 68 | return cast<FunctionType>(get((Type *)T)); |
| 69 | } |
| 70 | |
| 71 | private: |
| 72 | Type *remapType(Type *SrcTy) override { return get(SrcTy); } |
| 73 | |
| 74 | bool areTypesIsomorphic(Type *DstTy, Type *SrcTy); |
| 75 | }; |
| 76 | } |
| 77 | |
| 78 | void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) { |
| 79 | assert(SpeculativeTypes.empty()); |
| 80 | assert(SpeculativeDstOpaqueTypes.empty()); |
| 81 | |
| 82 | // Check to see if these types are recursively isomorphic and establish a |
| 83 | // mapping between them if so. |
| 84 | if (!areTypesIsomorphic(DstTy, SrcTy)) { |
| 85 | // Oops, they aren't isomorphic. Just discard this request by rolling out |
| 86 | // any speculative mappings we've established. |
| 87 | for (Type *Ty : SpeculativeTypes) |
| 88 | MappedTypes.erase(Ty); |
| 89 | |
| 90 | SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() - |
| 91 | SpeculativeDstOpaqueTypes.size()); |
| 92 | for (StructType *Ty : SpeculativeDstOpaqueTypes) |
| 93 | DstResolvedOpaqueTypes.erase(Ty); |
| 94 | } else { |
| 95 | for (Type *Ty : SpeculativeTypes) |
| 96 | if (auto *STy = dyn_cast<StructType>(Ty)) |
| 97 | if (STy->hasName()) |
| 98 | STy->setName(""); |
| 99 | } |
| 100 | SpeculativeTypes.clear(); |
| 101 | SpeculativeDstOpaqueTypes.clear(); |
| 102 | } |
| 103 | |
| 104 | /// Recursively walk this pair of types, returning true if they are isomorphic, |
| 105 | /// false if they are not. |
| 106 | bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) { |
| 107 | // Two types with differing kinds are clearly not isomorphic. |
| 108 | if (DstTy->getTypeID() != SrcTy->getTypeID()) |
| 109 | return false; |
| 110 | |
| 111 | // If we have an entry in the MappedTypes table, then we have our answer. |
| 112 | Type *&Entry = MappedTypes[SrcTy]; |
| 113 | if (Entry) |
| 114 | return Entry == DstTy; |
| 115 | |
| 116 | // Two identical types are clearly isomorphic. Remember this |
| 117 | // non-speculatively. |
| 118 | if (DstTy == SrcTy) { |
| 119 | Entry = DstTy; |
| 120 | return true; |
| 121 | } |
| 122 | |
| 123 | // Okay, we have two types with identical kinds that we haven't seen before. |
| 124 | |
| 125 | // If this is an opaque struct type, special case it. |
| 126 | if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) { |
| 127 | // Mapping an opaque type to any struct, just keep the dest struct. |
| 128 | if (SSTy->isOpaque()) { |
| 129 | Entry = DstTy; |
| 130 | SpeculativeTypes.push_back(SrcTy); |
| 131 | return true; |
| 132 | } |
| 133 | |
| 134 | // Mapping a non-opaque source type to an opaque dest. If this is the first |
| 135 | // type that we're mapping onto this destination type then we succeed. Keep |
| 136 | // the dest, but fill it in later. If this is the second (different) type |
| 137 | // that we're trying to map onto the same opaque type then we fail. |
| 138 | if (cast<StructType>(DstTy)->isOpaque()) { |
| 139 | // We can only map one source type onto the opaque destination type. |
| 140 | if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second) |
| 141 | return false; |
| 142 | SrcDefinitionsToResolve.push_back(SSTy); |
| 143 | SpeculativeTypes.push_back(SrcTy); |
| 144 | SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy)); |
| 145 | Entry = DstTy; |
| 146 | return true; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | // If the number of subtypes disagree between the two types, then we fail. |
| 151 | if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes()) |
| 152 | return false; |
| 153 | |
| 154 | // Fail if any of the extra properties (e.g. array size) of the type disagree. |
| 155 | if (isa<IntegerType>(DstTy)) |
| 156 | return false; // bitwidth disagrees. |
| 157 | if (PointerType *PT = dyn_cast<PointerType>(DstTy)) { |
| 158 | if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace()) |
| 159 | return false; |
| 160 | |
| 161 | } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) { |
| 162 | if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg()) |
| 163 | return false; |
| 164 | } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) { |
| 165 | StructType *SSTy = cast<StructType>(SrcTy); |
| 166 | if (DSTy->isLiteral() != SSTy->isLiteral() || |
| 167 | DSTy->isPacked() != SSTy->isPacked()) |
| 168 | return false; |
| 169 | } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) { |
| 170 | if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements()) |
| 171 | return false; |
| 172 | } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) { |
| 173 | if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements()) |
| 174 | return false; |
| 175 | } |
| 176 | |
| 177 | // Otherwise, we speculate that these two types will line up and recursively |
| 178 | // check the subelements. |
| 179 | Entry = DstTy; |
| 180 | SpeculativeTypes.push_back(SrcTy); |
| 181 | |
| 182 | for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I) |
| 183 | if (!areTypesIsomorphic(DstTy->getContainedType(I), |
| 184 | SrcTy->getContainedType(I))) |
| 185 | return false; |
| 186 | |
| 187 | // If everything seems to have lined up, then everything is great. |
| 188 | return true; |
| 189 | } |
| 190 | |
| 191 | void TypeMapTy::linkDefinedTypeBodies() { |
| 192 | SmallVector<Type *, 16> Elements; |
| 193 | for (StructType *SrcSTy : SrcDefinitionsToResolve) { |
| 194 | StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]); |
| 195 | assert(DstSTy->isOpaque()); |
| 196 | |
| 197 | // Map the body of the source type over to a new body for the dest type. |
| 198 | Elements.resize(SrcSTy->getNumElements()); |
| 199 | for (unsigned I = 0, E = Elements.size(); I != E; ++I) |
| 200 | Elements[I] = get(SrcSTy->getElementType(I)); |
| 201 | |
| 202 | DstSTy->setBody(Elements, SrcSTy->isPacked()); |
| 203 | DstStructTypesSet.switchToNonOpaque(DstSTy); |
| 204 | } |
| 205 | SrcDefinitionsToResolve.clear(); |
| 206 | DstResolvedOpaqueTypes.clear(); |
| 207 | } |
| 208 | |
| 209 | void TypeMapTy::finishType(StructType *DTy, StructType *STy, |
| 210 | ArrayRef<Type *> ETypes) { |
| 211 | DTy->setBody(ETypes, STy->isPacked()); |
| 212 | |
| 213 | // Steal STy's name. |
| 214 | if (STy->hasName()) { |
| 215 | SmallString<16> TmpName = STy->getName(); |
| 216 | STy->setName(""); |
| 217 | DTy->setName(TmpName); |
| 218 | } |
| 219 | |
| 220 | DstStructTypesSet.addNonOpaque(DTy); |
| 221 | } |
| 222 | |
| 223 | Type *TypeMapTy::get(Type *Ty) { |
| 224 | SmallPtrSet<StructType *, 8> Visited; |
| 225 | return get(Ty, Visited); |
| 226 | } |
| 227 | |
| 228 | Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) { |
| 229 | // If we already have an entry for this type, return it. |
| 230 | Type **Entry = &MappedTypes[Ty]; |
| 231 | if (*Entry) |
| 232 | return *Entry; |
| 233 | |
| 234 | // These are types that LLVM itself will unique. |
| 235 | bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral(); |
| 236 | |
| 237 | #ifndef NDEBUG |
| 238 | if (!IsUniqued) { |
| 239 | for (auto &Pair : MappedTypes) { |
| 240 | assert(!(Pair.first != Ty && Pair.second == Ty) && |
| 241 | "mapping to a source type"); |
| 242 | } |
| 243 | } |
| 244 | #endif |
| 245 | |
| 246 | if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) { |
| 247 | StructType *DTy = StructType::create(Ty->getContext()); |
| 248 | return *Entry = DTy; |
| 249 | } |
| 250 | |
| 251 | // If this is not a recursive type, then just map all of the elements and |
| 252 | // then rebuild the type from inside out. |
| 253 | SmallVector<Type *, 4> ElementTypes; |
| 254 | |
| 255 | // If there are no element types to map, then the type is itself. This is |
| 256 | // true for the anonymous {} struct, things like 'float', integers, etc. |
| 257 | if (Ty->getNumContainedTypes() == 0 && IsUniqued) |
| 258 | return *Entry = Ty; |
| 259 | |
| 260 | // Remap all of the elements, keeping track of whether any of them change. |
| 261 | bool AnyChange = false; |
| 262 | ElementTypes.resize(Ty->getNumContainedTypes()); |
| 263 | for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) { |
| 264 | ElementTypes[I] = get(Ty->getContainedType(I), Visited); |
| 265 | AnyChange |= ElementTypes[I] != Ty->getContainedType(I); |
| 266 | } |
| 267 | |
| 268 | // If we found our type while recursively processing stuff, just use it. |
| 269 | Entry = &MappedTypes[Ty]; |
| 270 | if (*Entry) { |
| 271 | if (auto *DTy = dyn_cast<StructType>(*Entry)) { |
| 272 | if (DTy->isOpaque()) { |
| 273 | auto *STy = cast<StructType>(Ty); |
| 274 | finishType(DTy, STy, ElementTypes); |
| 275 | } |
| 276 | } |
| 277 | return *Entry; |
| 278 | } |
| 279 | |
| 280 | // If all of the element types mapped directly over and the type is not |
| 281 | // a nomed struct, then the type is usable as-is. |
| 282 | if (!AnyChange && IsUniqued) |
| 283 | return *Entry = Ty; |
| 284 | |
| 285 | // Otherwise, rebuild a modified type. |
| 286 | switch (Ty->getTypeID()) { |
| 287 | default: |
| 288 | llvm_unreachable("unknown derived type to remap"); |
| 289 | case Type::ArrayTyID: |
| 290 | return *Entry = ArrayType::get(ElementTypes[0], |
| 291 | cast<ArrayType>(Ty)->getNumElements()); |
| 292 | case Type::VectorTyID: |
| 293 | return *Entry = VectorType::get(ElementTypes[0], |
| 294 | cast<VectorType>(Ty)->getNumElements()); |
| 295 | case Type::PointerTyID: |
| 296 | return *Entry = PointerType::get(ElementTypes[0], |
| 297 | cast<PointerType>(Ty)->getAddressSpace()); |
| 298 | case Type::FunctionTyID: |
| 299 | return *Entry = FunctionType::get(ElementTypes[0], |
| 300 | makeArrayRef(ElementTypes).slice(1), |
| 301 | cast<FunctionType>(Ty)->isVarArg()); |
| 302 | case Type::StructTyID: { |
| 303 | auto *STy = cast<StructType>(Ty); |
| 304 | bool IsPacked = STy->isPacked(); |
| 305 | if (IsUniqued) |
| 306 | return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked); |
| 307 | |
| 308 | // If the type is opaque, we can just use it directly. |
| 309 | if (STy->isOpaque()) { |
| 310 | DstStructTypesSet.addOpaque(STy); |
| 311 | return *Entry = Ty; |
| 312 | } |
| 313 | |
| 314 | if (StructType *OldT = |
| 315 | DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) { |
| 316 | STy->setName(""); |
| 317 | return *Entry = OldT; |
| 318 | } |
| 319 | |
| 320 | if (!AnyChange) { |
| 321 | DstStructTypesSet.addNonOpaque(STy); |
| 322 | return *Entry = Ty; |
| 323 | } |
| 324 | |
| 325 | StructType *DTy = StructType::create(Ty->getContext()); |
| 326 | finishType(DTy, STy, ElementTypes); |
| 327 | return *Entry = DTy; |
| 328 | } |
| 329 | } |
| 330 | } |
| 331 | |
| 332 | LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity, |
| 333 | const Twine &Msg) |
| 334 | : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {} |
| 335 | void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; } |
| 336 | |
| 337 | //===----------------------------------------------------------------------===// |
Teresa Johnson | bef5436 | 2015-12-18 19:28:59 +0000 | [diff] [blame] | 338 | // IRLinker implementation. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 339 | //===----------------------------------------------------------------------===// |
| 340 | |
| 341 | namespace { |
| 342 | class IRLinker; |
| 343 | |
| 344 | /// Creates prototypes for functions that are lazily linked on the fly. This |
| 345 | /// speeds up linking for modules with many/ lazily linked functions of which |
| 346 | /// few get used. |
| 347 | class GlobalValueMaterializer final : public ValueMaterializer { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 348 | IRLinker &TheIRLinker; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 349 | |
| 350 | public: |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 351 | GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 352 | Value *materializeDeclFor(Value *V) override; |
| 353 | void materializeInitFor(GlobalValue *New, GlobalValue *Old) override; |
| 354 | }; |
| 355 | |
| 356 | class LocalValueMaterializer final : public ValueMaterializer { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 357 | IRLinker &TheIRLinker; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 358 | |
| 359 | public: |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 360 | LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {} |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 361 | Value *materializeDeclFor(Value *V) override; |
| 362 | void materializeInitFor(GlobalValue *New, GlobalValue *Old) override; |
| 363 | }; |
| 364 | |
| 365 | /// This is responsible for keeping track of the state used for moving data |
| 366 | /// from SrcM to DstM. |
| 367 | class IRLinker { |
| 368 | Module &DstM; |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 369 | std::unique_ptr<Module> SrcM; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 370 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 371 | /// See IRMover::move(). |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 372 | std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor; |
| 373 | |
| 374 | TypeMapTy TypeMap; |
| 375 | GlobalValueMaterializer GValMaterializer; |
| 376 | LocalValueMaterializer LValMaterializer; |
| 377 | |
| 378 | /// Mapping of values from what they used to be in Src, to what they are now |
| 379 | /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead |
| 380 | /// due to the use of Value handles which the Linker doesn't actually need, |
| 381 | /// but this allows us to reuse the ValueMapper code. |
| 382 | ValueToValueMapTy ValueMap; |
| 383 | ValueToValueMapTy AliasValueMap; |
| 384 | |
| 385 | DenseSet<GlobalValue *> ValuesToLink; |
| 386 | std::vector<GlobalValue *> Worklist; |
| 387 | |
| 388 | void maybeAdd(GlobalValue *GV) { |
| 389 | if (ValuesToLink.insert(GV).second) |
| 390 | Worklist.push_back(GV); |
| 391 | } |
| 392 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 393 | /// Set to true when all global value body linking is complete (including |
| 394 | /// lazy linking). Used to prevent metadata linking from creating new |
| 395 | /// references. |
| 396 | bool DoneLinkingBodies = false; |
| 397 | |
| 398 | bool HasError = false; |
| 399 | |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 400 | /// Entry point for mapping values and alternate context for mapping aliases. |
| 401 | ValueMapper Mapper; |
| 402 | unsigned AliasMCID; |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 403 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 404 | /// Handles cloning of a global values from the source module into |
| 405 | /// the destination module, including setting the attributes and visibility. |
| 406 | GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition); |
| 407 | |
| 408 | /// Helper method for setting a message and returning an error code. |
| 409 | bool emitError(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 410 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 411 | HasError = true; |
| 412 | return true; |
| 413 | } |
| 414 | |
| 415 | void emitWarning(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 416 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 417 | } |
| 418 | |
| 419 | /// Given a global in the source module, return the global in the |
| 420 | /// destination module that is being linked to, if any. |
| 421 | GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { |
| 422 | // If the source has no name it can't link. If it has local linkage, |
| 423 | // there is no name match-up going on. |
| 424 | if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) |
| 425 | return nullptr; |
| 426 | |
| 427 | // Otherwise see if we have a match in the destination module's symtab. |
| 428 | GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName()); |
| 429 | if (!DGV) |
| 430 | return nullptr; |
| 431 | |
| 432 | // If we found a global with the same name in the dest module, but it has |
| 433 | // internal linkage, we are really not doing any linkage here. |
| 434 | if (DGV->hasLocalLinkage()) |
| 435 | return nullptr; |
| 436 | |
| 437 | // Otherwise, we do in fact link to the destination global. |
| 438 | return DGV; |
| 439 | } |
| 440 | |
| 441 | void computeTypeMapping(); |
| 442 | |
| 443 | Constant *linkAppendingVarProto(GlobalVariable *DstGV, |
| 444 | const GlobalVariable *SrcGV); |
| 445 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 446 | /// Given the GlobaValue \p SGV in the source module, and the matching |
| 447 | /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV |
| 448 | /// into the destination module. |
| 449 | /// |
| 450 | /// Note this code may call the client-provided \p AddLazyFor. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 451 | bool shouldLink(GlobalValue *DGV, GlobalValue &SGV); |
| 452 | Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias); |
| 453 | |
| 454 | bool linkModuleFlagsMetadata(); |
| 455 | |
| 456 | void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src); |
| 457 | bool linkFunctionBody(Function &Dst, Function &Src); |
| 458 | void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); |
| 459 | bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src); |
| 460 | |
| 461 | /// Functions that take care of cloning a specific global value type |
| 462 | /// into the destination module. |
| 463 | GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar); |
| 464 | Function *copyFunctionProto(const Function *SF); |
| 465 | GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA); |
| 466 | |
| 467 | void linkNamedMDNodes(); |
| 468 | |
| 469 | public: |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 470 | IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, |
| 471 | std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 472 | std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 473 | : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set), |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 474 | GValMaterializer(*this), LValMaterializer(*this), |
| 475 | Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap, |
| 476 | &GValMaterializer), |
| 477 | AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap, |
| 478 | &LValMaterializer)) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 479 | for (GlobalValue *GV : ValuesToLink) |
| 480 | maybeAdd(GV); |
Teresa Johnson | cc42857 | 2015-12-30 19:32:24 +0000 | [diff] [blame] | 481 | } |
| 482 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 483 | bool run(); |
| 484 | Value *materializeDeclFor(Value *V, bool ForAlias); |
| 485 | void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias); |
| 486 | }; |
| 487 | } |
| 488 | |
| 489 | /// The LLVM SymbolTable class autorenames globals that conflict in the symbol |
| 490 | /// table. This is good for all clients except for us. Go through the trouble |
| 491 | /// to force this back. |
| 492 | static void forceRenaming(GlobalValue *GV, StringRef Name) { |
| 493 | // If the global doesn't force its name or if it already has the right name, |
| 494 | // there is nothing for us to do. |
| 495 | if (GV->hasLocalLinkage() || GV->getName() == Name) |
| 496 | return; |
| 497 | |
| 498 | Module *M = GV->getParent(); |
| 499 | |
| 500 | // If there is a conflict, rename the conflict. |
| 501 | if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { |
| 502 | GV->takeName(ConflictGV); |
| 503 | ConflictGV->setName(Name); // This will cause ConflictGV to get renamed |
| 504 | assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); |
| 505 | } else { |
| 506 | GV->setName(Name); // Force the name back |
| 507 | } |
| 508 | } |
| 509 | |
| 510 | Value *GlobalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 511 | return TheIRLinker.materializeDeclFor(V, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 512 | } |
| 513 | |
| 514 | void GlobalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 515 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 516 | TheIRLinker.materializeInitFor(New, Old, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 517 | } |
| 518 | |
| 519 | Value *LocalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 520 | return TheIRLinker.materializeDeclFor(V, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 521 | } |
| 522 | |
| 523 | void LocalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 524 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 525 | TheIRLinker.materializeInitFor(New, Old, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 526 | } |
| 527 | |
| 528 | Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) { |
| 529 | auto *SGV = dyn_cast<GlobalValue>(V); |
| 530 | if (!SGV) |
| 531 | return nullptr; |
| 532 | |
| 533 | return linkGlobalValueProto(SGV, ForAlias); |
| 534 | } |
| 535 | |
| 536 | void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old, |
| 537 | bool ForAlias) { |
| 538 | // If we already created the body, just return. |
| 539 | if (auto *F = dyn_cast<Function>(New)) { |
| 540 | if (!F->isDeclaration()) |
| 541 | return; |
| 542 | } else if (auto *V = dyn_cast<GlobalVariable>(New)) { |
| 543 | if (V->hasInitializer()) |
| 544 | return; |
| 545 | } else { |
| 546 | auto *A = cast<GlobalAlias>(New); |
| 547 | if (A->getAliasee()) |
| 548 | return; |
| 549 | } |
| 550 | |
| 551 | if (ForAlias || shouldLink(New, *Old)) |
| 552 | linkGlobalValueBody(*New, *Old); |
| 553 | } |
| 554 | |
| 555 | /// Loop through the global variables in the src module and merge them into the |
| 556 | /// dest module. |
| 557 | GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { |
| 558 | // No linking to be performed or linking from the source: simply create an |
| 559 | // identical version of the symbol over in the dest module... the |
| 560 | // initializer will be filled in later by LinkGlobalInits. |
| 561 | GlobalVariable *NewDGV = |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 562 | new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 563 | SGVar->isConstant(), GlobalValue::ExternalLinkage, |
| 564 | /*init*/ nullptr, SGVar->getName(), |
| 565 | /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), |
| 566 | SGVar->getType()->getAddressSpace()); |
| 567 | NewDGV->setAlignment(SGVar->getAlignment()); |
| 568 | return NewDGV; |
| 569 | } |
| 570 | |
| 571 | /// Link the function in the source module into the destination module if |
| 572 | /// needed, setting up mapping information. |
| 573 | Function *IRLinker::copyFunctionProto(const Function *SF) { |
| 574 | // If there is no linkage to be performed or we are linking from the source, |
| 575 | // bring SF over. |
| 576 | return Function::Create(TypeMap.get(SF->getFunctionType()), |
| 577 | GlobalValue::ExternalLinkage, SF->getName(), &DstM); |
| 578 | } |
| 579 | |
| 580 | /// Set up prototypes for any aliases that come over from the source module. |
| 581 | GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) { |
| 582 | // If there is no linkage to be performed or we're linking from the source, |
| 583 | // bring over SGA. |
| 584 | auto *Ty = TypeMap.get(SGA->getValueType()); |
| 585 | return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), |
| 586 | GlobalValue::ExternalLinkage, SGA->getName(), |
| 587 | &DstM); |
| 588 | } |
| 589 | |
| 590 | GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, |
| 591 | bool ForDefinition) { |
| 592 | GlobalValue *NewGV; |
| 593 | if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { |
| 594 | NewGV = copyGlobalVariableProto(SGVar); |
| 595 | } else if (auto *SF = dyn_cast<Function>(SGV)) { |
| 596 | NewGV = copyFunctionProto(SF); |
| 597 | } else { |
| 598 | if (ForDefinition) |
| 599 | NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV)); |
| 600 | else |
| 601 | NewGV = new GlobalVariable( |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 602 | DstM, TypeMap.get(SGV->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 603 | /*isConstant*/ false, GlobalValue::ExternalLinkage, |
| 604 | /*init*/ nullptr, SGV->getName(), |
| 605 | /*insertbefore*/ nullptr, SGV->getThreadLocalMode(), |
| 606 | SGV->getType()->getAddressSpace()); |
| 607 | } |
| 608 | |
| 609 | if (ForDefinition) |
| 610 | NewGV->setLinkage(SGV->getLinkage()); |
| 611 | else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() || |
| 612 | SGV->hasLinkOnceLinkage()) |
| 613 | NewGV->setLinkage(GlobalValue::ExternalWeakLinkage); |
| 614 | |
| 615 | NewGV->copyAttributesFrom(SGV); |
Teresa Johnson | 5fe4005 | 2016-01-12 00:24:24 +0000 | [diff] [blame] | 616 | |
| 617 | // Remove these copied constants in case this stays a declaration, since |
| 618 | // they point to the source module. If the def is linked the values will |
| 619 | // be mapped in during linkFunctionBody. |
| 620 | if (auto *NewF = dyn_cast<Function>(NewGV)) { |
| 621 | NewF->setPersonalityFn(nullptr); |
| 622 | NewF->setPrefixData(nullptr); |
| 623 | NewF->setPrologueData(nullptr); |
| 624 | } |
| 625 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 626 | return NewGV; |
| 627 | } |
| 628 | |
| 629 | /// Loop over all of the linked values to compute type mappings. For example, |
| 630 | /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct |
| 631 | /// types 'Foo' but one got renamed when the module was loaded into the same |
| 632 | /// LLVMContext. |
| 633 | void IRLinker::computeTypeMapping() { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 634 | for (GlobalValue &SGV : SrcM->globals()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 635 | GlobalValue *DGV = getLinkedToGlobal(&SGV); |
| 636 | if (!DGV) |
| 637 | continue; |
| 638 | |
| 639 | if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { |
| 640 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 641 | continue; |
| 642 | } |
| 643 | |
| 644 | // Unify the element type of appending arrays. |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 645 | ArrayType *DAT = cast<ArrayType>(DGV->getValueType()); |
| 646 | ArrayType *SAT = cast<ArrayType>(SGV.getValueType()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 647 | TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); |
| 648 | } |
| 649 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 650 | for (GlobalValue &SGV : *SrcM) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 651 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 652 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 653 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 654 | for (GlobalValue &SGV : SrcM->aliases()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 655 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 656 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 657 | |
| 658 | // Incorporate types by name, scanning all the types in the source module. |
| 659 | // At this point, the destination module may have a type "%foo = { i32 }" for |
| 660 | // example. When the source module got loaded into the same LLVMContext, if |
| 661 | // it had the same type, it would have been renamed to "%foo.42 = { i32 }". |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 662 | std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 663 | for (StructType *ST : Types) { |
| 664 | if (!ST->hasName()) |
| 665 | continue; |
| 666 | |
| 667 | // Check to see if there is a dot in the name followed by a digit. |
| 668 | size_t DotPos = ST->getName().rfind('.'); |
| 669 | if (DotPos == 0 || DotPos == StringRef::npos || |
| 670 | ST->getName().back() == '.' || |
| 671 | !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1]))) |
| 672 | continue; |
| 673 | |
| 674 | // Check to see if the destination module has a struct with the prefix name. |
| 675 | StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos)); |
| 676 | if (!DST) |
| 677 | continue; |
| 678 | |
| 679 | // Don't use it if this actually came from the source module. They're in |
| 680 | // the same LLVMContext after all. Also don't use it unless the type is |
| 681 | // actually used in the destination module. This can happen in situations |
| 682 | // like this: |
| 683 | // |
| 684 | // Module A Module B |
| 685 | // -------- -------- |
| 686 | // %Z = type { %A } %B = type { %C.1 } |
| 687 | // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } |
| 688 | // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } |
| 689 | // %C = type { i8* } %B.3 = type { %C.1 } |
| 690 | // |
| 691 | // When we link Module B with Module A, the '%B' in Module B is |
| 692 | // used. However, that would then use '%C.1'. But when we process '%C.1', |
| 693 | // we prefer to take the '%C' version. So we are then left with both |
| 694 | // '%C.1' and '%C' being used for the same types. This leads to some |
| 695 | // variables using one type and some using the other. |
| 696 | if (TypeMap.DstStructTypesSet.hasType(DST)) |
| 697 | TypeMap.addTypeMapping(DST, ST); |
| 698 | } |
| 699 | |
| 700 | // Now that we have discovered all of the type equivalences, get a body for |
| 701 | // any 'opaque' types in the dest module that are now resolved. |
| 702 | TypeMap.linkDefinedTypeBodies(); |
| 703 | } |
| 704 | |
| 705 | static void getArrayElements(const Constant *C, |
| 706 | SmallVectorImpl<Constant *> &Dest) { |
| 707 | unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); |
| 708 | |
| 709 | for (unsigned i = 0; i != NumElements; ++i) |
| 710 | Dest.push_back(C->getAggregateElement(i)); |
| 711 | } |
| 712 | |
| 713 | /// If there were any appending global variables, link them together now. |
| 714 | /// Return true on error. |
| 715 | Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV, |
| 716 | const GlobalVariable *SrcGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 717 | Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType())) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 718 | ->getElementType(); |
| 719 | |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 720 | // FIXME: This upgrade is done during linking to support the C API. Once the |
| 721 | // old form is deprecated, we should move this upgrade to |
| 722 | // llvm::UpgradeGlobalVariable() and simplify the logic here and in |
| 723 | // Mapper::mapAppendingVariable() in ValueMapper.cpp. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 724 | StringRef Name = SrcGV->getName(); |
| 725 | bool IsNewStructor = false; |
| 726 | bool IsOldStructor = false; |
| 727 | if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") { |
| 728 | if (cast<StructType>(EltTy)->getNumElements() == 3) |
| 729 | IsNewStructor = true; |
| 730 | else |
| 731 | IsOldStructor = true; |
| 732 | } |
| 733 | |
| 734 | PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo(); |
| 735 | if (IsOldStructor) { |
| 736 | auto &ST = *cast<StructType>(EltTy); |
| 737 | Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy}; |
| 738 | EltTy = StructType::get(SrcGV->getContext(), Tys, false); |
| 739 | } |
| 740 | |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 741 | uint64_t DstNumElements = 0; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 742 | if (DstGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 743 | ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType()); |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 744 | DstNumElements = DstTy->getNumElements(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 745 | |
| 746 | if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) { |
| 747 | emitError( |
| 748 | "Linking globals named '" + SrcGV->getName() + |
| 749 | "': can only link appending global with another appending global!"); |
| 750 | return nullptr; |
| 751 | } |
| 752 | |
| 753 | // Check to see that they two arrays agree on type. |
| 754 | if (EltTy != DstTy->getElementType()) { |
| 755 | emitError("Appending variables with different element types!"); |
| 756 | return nullptr; |
| 757 | } |
| 758 | if (DstGV->isConstant() != SrcGV->isConstant()) { |
| 759 | emitError("Appending variables linked with different const'ness!"); |
| 760 | return nullptr; |
| 761 | } |
| 762 | |
| 763 | if (DstGV->getAlignment() != SrcGV->getAlignment()) { |
| 764 | emitError( |
| 765 | "Appending variables with different alignment need to be linked!"); |
| 766 | return nullptr; |
| 767 | } |
| 768 | |
| 769 | if (DstGV->getVisibility() != SrcGV->getVisibility()) { |
| 770 | emitError( |
| 771 | "Appending variables with different visibility need to be linked!"); |
| 772 | return nullptr; |
| 773 | } |
| 774 | |
| 775 | if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) { |
| 776 | emitError( |
| 777 | "Appending variables with different unnamed_addr need to be linked!"); |
| 778 | return nullptr; |
| 779 | } |
| 780 | |
| 781 | if (StringRef(DstGV->getSection()) != SrcGV->getSection()) { |
| 782 | emitError( |
| 783 | "Appending variables with different section name need to be linked!"); |
| 784 | return nullptr; |
| 785 | } |
| 786 | } |
| 787 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 788 | SmallVector<Constant *, 16> SrcElements; |
| 789 | getArrayElements(SrcGV->getInitializer(), SrcElements); |
| 790 | |
| 791 | if (IsNewStructor) |
| 792 | SrcElements.erase( |
| 793 | std::remove_if(SrcElements.begin(), SrcElements.end(), |
| 794 | [this](Constant *E) { |
| 795 | auto *Key = dyn_cast<GlobalValue>( |
| 796 | E->getAggregateElement(2)->stripPointerCasts()); |
| 797 | if (!Key) |
| 798 | return false; |
| 799 | GlobalValue *DGV = getLinkedToGlobal(Key); |
| 800 | return !shouldLink(DGV, *Key); |
| 801 | }), |
| 802 | SrcElements.end()); |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 803 | uint64_t NewSize = DstNumElements + SrcElements.size(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 804 | ArrayType *NewType = ArrayType::get(EltTy, NewSize); |
| 805 | |
| 806 | // Create the new global variable. |
| 807 | GlobalVariable *NG = new GlobalVariable( |
| 808 | DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(), |
| 809 | /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(), |
| 810 | SrcGV->getType()->getAddressSpace()); |
| 811 | |
| 812 | NG->copyAttributesFrom(SrcGV); |
| 813 | forceRenaming(NG, SrcGV->getName()); |
| 814 | |
| 815 | Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); |
| 816 | |
| 817 | // Stop recursion. |
| 818 | ValueMap[SrcGV] = Ret; |
| 819 | |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 820 | Mapper.scheduleMapAppendingVariable(*NG, |
| 821 | DstGV ? DstGV->getInitializer() : nullptr, |
| 822 | IsOldStructor, SrcElements); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 823 | |
| 824 | // Replace any uses of the two global variables with uses of the new |
| 825 | // global. |
| 826 | if (DstGV) { |
| 827 | DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); |
| 828 | DstGV->eraseFromParent(); |
| 829 | } |
| 830 | |
| 831 | return Ret; |
| 832 | } |
| 833 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 834 | bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) { |
| 835 | if (ValuesToLink.count(&SGV)) |
| 836 | return true; |
| 837 | |
| 838 | if (SGV.hasLocalLinkage()) |
| 839 | return true; |
| 840 | |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 841 | if (DGV && !DGV->isDeclarationForLinker()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 842 | return false; |
| 843 | |
| 844 | if (SGV.hasAvailableExternallyLinkage()) |
| 845 | return true; |
| 846 | |
| 847 | if (DoneLinkingBodies) |
| 848 | return false; |
| 849 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 850 | |
| 851 | // Callback to the client to give a chance to lazily add the Global to the |
| 852 | // list of value to link. |
| 853 | bool LazilyAdded = false; |
| 854 | AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) { |
| 855 | maybeAdd(&GV); |
| 856 | LazilyAdded = true; |
| 857 | }); |
| 858 | return LazilyAdded; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 859 | } |
| 860 | |
| 861 | Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) { |
| 862 | GlobalValue *DGV = getLinkedToGlobal(SGV); |
| 863 | |
| 864 | bool ShouldLink = shouldLink(DGV, *SGV); |
| 865 | |
| 866 | // just missing from map |
| 867 | if (ShouldLink) { |
| 868 | auto I = ValueMap.find(SGV); |
| 869 | if (I != ValueMap.end()) |
| 870 | return cast<Constant>(I->second); |
| 871 | |
| 872 | I = AliasValueMap.find(SGV); |
| 873 | if (I != AliasValueMap.end()) |
| 874 | return cast<Constant>(I->second); |
| 875 | } |
| 876 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 877 | if (!ShouldLink && ForAlias) |
| 878 | DGV = nullptr; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 879 | |
| 880 | // Handle the ultra special appending linkage case first. |
| 881 | assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage()); |
| 882 | if (SGV->hasAppendingLinkage()) |
| 883 | return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV), |
| 884 | cast<GlobalVariable>(SGV)); |
| 885 | |
| 886 | GlobalValue *NewGV; |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 887 | if (DGV && !ShouldLink) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 888 | NewGV = DGV; |
| 889 | } else { |
| 890 | // If we are done linking global value bodies (i.e. we are performing |
| 891 | // metadata linking), don't link in the global value due to this |
| 892 | // reference, simply map it to null. |
| 893 | if (DoneLinkingBodies) |
| 894 | return nullptr; |
| 895 | |
| 896 | NewGV = copyGlobalValueProto(SGV, ShouldLink); |
Evgeniy Stepanov | 9fb70f5 | 2016-01-20 22:05:50 +0000 | [diff] [blame] | 897 | if (ShouldLink || !ForAlias) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 898 | forceRenaming(NewGV, SGV->getName()); |
| 899 | } |
| 900 | if (ShouldLink || ForAlias) { |
| 901 | if (const Comdat *SC = SGV->getComdat()) { |
| 902 | if (auto *GO = dyn_cast<GlobalObject>(NewGV)) { |
| 903 | Comdat *DC = DstM.getOrInsertComdat(SC->getName()); |
| 904 | DC->setSelectionKind(SC->getSelectionKind()); |
| 905 | GO->setComdat(DC); |
| 906 | } |
| 907 | } |
| 908 | } |
| 909 | |
| 910 | if (!ShouldLink && ForAlias) |
| 911 | NewGV->setLinkage(GlobalValue::InternalLinkage); |
| 912 | |
| 913 | Constant *C = NewGV; |
| 914 | if (DGV) |
| 915 | C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType())); |
| 916 | |
| 917 | if (DGV && NewGV != DGV) { |
| 918 | DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); |
| 919 | DGV->eraseFromParent(); |
| 920 | } |
| 921 | |
| 922 | return C; |
| 923 | } |
| 924 | |
| 925 | /// Update the initializers in the Dest module now that all globals that may be |
| 926 | /// referenced are in Dest. |
| 927 | void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) { |
| 928 | // Figure out what the initializer looks like in the dest module. |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 929 | Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 930 | } |
| 931 | |
| 932 | /// Copy the source function over into the dest function and fix up references |
| 933 | /// to values. At this point we know that Dest is an external function, and |
| 934 | /// that Src is not. |
| 935 | bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) { |
| 936 | assert(Dst.isDeclaration() && !Src.isDeclaration()); |
| 937 | |
| 938 | // Materialize if needed. |
| 939 | if (std::error_code EC = Src.materialize()) |
| 940 | return emitError(EC.message()); |
| 941 | |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 942 | // Link in the operands without remapping. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 943 | if (Src.hasPrefixData()) |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 944 | Dst.setPrefixData(Src.getPrefixData()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 945 | if (Src.hasPrologueData()) |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 946 | Dst.setPrologueData(Src.getPrologueData()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 947 | if (Src.hasPersonalityFn()) |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 948 | Dst.setPersonalityFn(Src.getPersonalityFn()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 949 | |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 950 | // Copy over the metadata attachments without remapping. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 951 | SmallVector<std::pair<unsigned, MDNode *>, 8> MDs; |
| 952 | Src.getAllMetadata(MDs); |
| 953 | for (const auto &I : MDs) |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 954 | Dst.setMetadata(I.first, I.second); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 955 | |
Duncan P. N. Exon Smith | bdfc984 | 2016-04-06 06:38:15 +0000 | [diff] [blame] | 956 | // Steal arguments and splice the body of Src into Dst. |
| 957 | Dst.stealArgumentListFrom(Src); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 958 | Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); |
| 959 | |
Duncan P. N. Exon Smith | bb2c3e1 | 2016-04-08 19:26:32 +0000 | [diff] [blame] | 960 | // Everything has been moved over. Remap it. |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 961 | Mapper.scheduleRemapFunction(Dst); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 962 | return false; |
| 963 | } |
| 964 | |
| 965 | void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 966 | Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 967 | } |
| 968 | |
| 969 | bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) { |
| 970 | if (auto *F = dyn_cast<Function>(&Src)) |
| 971 | return linkFunctionBody(cast<Function>(Dst), *F); |
| 972 | if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { |
| 973 | linkGlobalInit(cast<GlobalVariable>(Dst), *GVar); |
| 974 | return false; |
| 975 | } |
| 976 | linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src)); |
| 977 | return false; |
| 978 | } |
| 979 | |
| 980 | /// Insert all of the named MDNodes in Src into the Dest module. |
| 981 | void IRLinker::linkNamedMDNodes() { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 982 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
| 983 | for (const NamedMDNode &NMD : SrcM->named_metadata()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 984 | // Don't link module flags here. Do them separately. |
| 985 | if (&NMD == SrcModFlags) |
| 986 | continue; |
| 987 | NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); |
| 988 | // Add Src elements into Dest node. |
Duncan P. N. Exon Smith | 8a15dab | 2016-04-15 23:32:44 +0000 | [diff] [blame] | 989 | for (const MDNode *Op : NMD.operands()) |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 990 | DestNMD->addOperand(Mapper.mapMDNode(*Op)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 991 | } |
| 992 | } |
| 993 | |
| 994 | /// Merge the linker flags in Src into the Dest module. |
| 995 | bool IRLinker::linkModuleFlagsMetadata() { |
| 996 | // If the source module has no module flags, we are done. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 997 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 998 | if (!SrcModFlags) |
| 999 | return false; |
| 1000 | |
| 1001 | // If the destination module doesn't have module flags yet, then just copy |
| 1002 | // over the source module's flags. |
| 1003 | NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata(); |
| 1004 | if (DstModFlags->getNumOperands() == 0) { |
| 1005 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) |
| 1006 | DstModFlags->addOperand(SrcModFlags->getOperand(I)); |
| 1007 | |
| 1008 | return false; |
| 1009 | } |
| 1010 | |
| 1011 | // First build a map of the existing module flags and requirements. |
| 1012 | DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; |
| 1013 | SmallSetVector<MDNode *, 16> Requirements; |
| 1014 | for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { |
| 1015 | MDNode *Op = DstModFlags->getOperand(I); |
| 1016 | ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); |
| 1017 | MDString *ID = cast<MDString>(Op->getOperand(1)); |
| 1018 | |
| 1019 | if (Behavior->getZExtValue() == Module::Require) { |
| 1020 | Requirements.insert(cast<MDNode>(Op->getOperand(2))); |
| 1021 | } else { |
| 1022 | Flags[ID] = std::make_pair(Op, I); |
| 1023 | } |
| 1024 | } |
| 1025 | |
| 1026 | // Merge in the flags from the source module, and also collect its set of |
| 1027 | // requirements. |
| 1028 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { |
| 1029 | MDNode *SrcOp = SrcModFlags->getOperand(I); |
| 1030 | ConstantInt *SrcBehavior = |
| 1031 | mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); |
| 1032 | MDString *ID = cast<MDString>(SrcOp->getOperand(1)); |
| 1033 | MDNode *DstOp; |
| 1034 | unsigned DstIndex; |
| 1035 | std::tie(DstOp, DstIndex) = Flags.lookup(ID); |
| 1036 | unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); |
| 1037 | |
| 1038 | // If this is a requirement, add it and continue. |
| 1039 | if (SrcBehaviorValue == Module::Require) { |
| 1040 | // If the destination module does not already have this requirement, add |
| 1041 | // it. |
| 1042 | if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { |
| 1043 | DstModFlags->addOperand(SrcOp); |
| 1044 | } |
| 1045 | continue; |
| 1046 | } |
| 1047 | |
| 1048 | // If there is no existing flag with this ID, just add it. |
| 1049 | if (!DstOp) { |
| 1050 | Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); |
| 1051 | DstModFlags->addOperand(SrcOp); |
| 1052 | continue; |
| 1053 | } |
| 1054 | |
| 1055 | // Otherwise, perform a merge. |
| 1056 | ConstantInt *DstBehavior = |
| 1057 | mdconst::extract<ConstantInt>(DstOp->getOperand(0)); |
| 1058 | unsigned DstBehaviorValue = DstBehavior->getZExtValue(); |
| 1059 | |
| 1060 | // If either flag has override behavior, handle it first. |
| 1061 | if (DstBehaviorValue == Module::Override) { |
| 1062 | // Diagnose inconsistent flags which both have override behavior. |
| 1063 | if (SrcBehaviorValue == Module::Override && |
| 1064 | SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1065 | emitError("linking module flags '" + ID->getString() + |
| 1066 | "': IDs have conflicting override values"); |
| 1067 | } |
| 1068 | continue; |
| 1069 | } else if (SrcBehaviorValue == Module::Override) { |
| 1070 | // Update the destination flag to that of the source. |
| 1071 | DstModFlags->setOperand(DstIndex, SrcOp); |
| 1072 | Flags[ID].first = SrcOp; |
| 1073 | continue; |
| 1074 | } |
| 1075 | |
| 1076 | // Diagnose inconsistent merge behavior types. |
| 1077 | if (SrcBehaviorValue != DstBehaviorValue) { |
| 1078 | emitError("linking module flags '" + ID->getString() + |
| 1079 | "': IDs have conflicting behaviors"); |
| 1080 | continue; |
| 1081 | } |
| 1082 | |
| 1083 | auto replaceDstValue = [&](MDNode *New) { |
| 1084 | Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; |
| 1085 | MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps); |
| 1086 | DstModFlags->setOperand(DstIndex, Flag); |
| 1087 | Flags[ID].first = Flag; |
| 1088 | }; |
| 1089 | |
| 1090 | // Perform the merge for standard behavior types. |
| 1091 | switch (SrcBehaviorValue) { |
| 1092 | case Module::Require: |
| 1093 | case Module::Override: |
| 1094 | llvm_unreachable("not possible"); |
| 1095 | case Module::Error: { |
| 1096 | // Emit an error if the values differ. |
| 1097 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1098 | emitError("linking module flags '" + ID->getString() + |
| 1099 | "': IDs have conflicting values"); |
| 1100 | } |
| 1101 | continue; |
| 1102 | } |
| 1103 | case Module::Warning: { |
| 1104 | // Emit a warning if the values differ. |
| 1105 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1106 | emitWarning("linking module flags '" + ID->getString() + |
| 1107 | "': IDs have conflicting values"); |
| 1108 | } |
| 1109 | continue; |
| 1110 | } |
| 1111 | case Module::Append: { |
| 1112 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1113 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1114 | SmallVector<Metadata *, 8> MDs; |
| 1115 | MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); |
| 1116 | MDs.append(DstValue->op_begin(), DstValue->op_end()); |
| 1117 | MDs.append(SrcValue->op_begin(), SrcValue->op_end()); |
| 1118 | |
| 1119 | replaceDstValue(MDNode::get(DstM.getContext(), MDs)); |
| 1120 | break; |
| 1121 | } |
| 1122 | case Module::AppendUnique: { |
| 1123 | SmallSetVector<Metadata *, 16> Elts; |
| 1124 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1125 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1126 | Elts.insert(DstValue->op_begin(), DstValue->op_end()); |
| 1127 | Elts.insert(SrcValue->op_begin(), SrcValue->op_end()); |
| 1128 | |
| 1129 | replaceDstValue(MDNode::get(DstM.getContext(), |
| 1130 | makeArrayRef(Elts.begin(), Elts.end()))); |
| 1131 | break; |
| 1132 | } |
| 1133 | } |
| 1134 | } |
| 1135 | |
| 1136 | // Check all of the requirements. |
| 1137 | for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { |
| 1138 | MDNode *Requirement = Requirements[I]; |
| 1139 | MDString *Flag = cast<MDString>(Requirement->getOperand(0)); |
| 1140 | Metadata *ReqValue = Requirement->getOperand(1); |
| 1141 | |
| 1142 | MDNode *Op = Flags[Flag].first; |
| 1143 | if (!Op || Op->getOperand(2) != ReqValue) { |
| 1144 | emitError("linking module flags '" + Flag->getString() + |
| 1145 | "': does not have the required value"); |
| 1146 | continue; |
| 1147 | } |
| 1148 | } |
| 1149 | |
| 1150 | return HasError; |
| 1151 | } |
| 1152 | |
| 1153 | // This function returns true if the triples match. |
| 1154 | static bool triplesMatch(const Triple &T0, const Triple &T1) { |
| 1155 | // If vendor is apple, ignore the version number. |
| 1156 | if (T0.getVendor() == Triple::Apple) |
| 1157 | return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() && |
| 1158 | T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS(); |
| 1159 | |
| 1160 | return T0 == T1; |
| 1161 | } |
| 1162 | |
| 1163 | // This function returns the merged triple. |
| 1164 | static std::string mergeTriples(const Triple &SrcTriple, |
| 1165 | const Triple &DstTriple) { |
| 1166 | // If vendor is apple, pick the triple with the larger version number. |
| 1167 | if (SrcTriple.getVendor() == Triple::Apple) |
| 1168 | if (DstTriple.isOSVersionLT(SrcTriple)) |
| 1169 | return SrcTriple.str(); |
| 1170 | |
| 1171 | return DstTriple.str(); |
| 1172 | } |
| 1173 | |
| 1174 | bool IRLinker::run() { |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1175 | // Ensure metadata materialized before value mapping. |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1176 | if (SrcM->getMaterializer() && SrcM->getMaterializer()->materializeMetadata()) |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1177 | return true; |
| 1178 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1179 | // Inherit the target data from the source module if the destination module |
| 1180 | // doesn't have one already. |
| 1181 | if (DstM.getDataLayout().isDefault()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1182 | DstM.setDataLayout(SrcM->getDataLayout()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1183 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1184 | if (SrcM->getDataLayout() != DstM.getDataLayout()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1185 | emitWarning("Linking two modules of different data layouts: '" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1186 | SrcM->getModuleIdentifier() + "' is '" + |
| 1187 | SrcM->getDataLayoutStr() + "' whereas '" + |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1188 | DstM.getModuleIdentifier() + "' is '" + |
| 1189 | DstM.getDataLayoutStr() + "'\n"); |
| 1190 | } |
| 1191 | |
| 1192 | // Copy the target triple from the source to dest if the dest's is empty. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1193 | if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) |
| 1194 | DstM.setTargetTriple(SrcM->getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1195 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1196 | Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1197 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1198 | if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple)) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1199 | emitWarning("Linking two modules of different target triples: " + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1200 | SrcM->getModuleIdentifier() + "' is '" + |
| 1201 | SrcM->getTargetTriple() + "' whereas '" + |
| 1202 | DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() + |
| 1203 | "'\n"); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1204 | |
| 1205 | DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple)); |
| 1206 | |
| 1207 | // Append the module inline asm string. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1208 | if (!SrcM->getModuleInlineAsm().empty()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1209 | if (DstM.getModuleInlineAsm().empty()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1210 | DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1211 | else |
| 1212 | DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1213 | SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1214 | } |
| 1215 | |
| 1216 | // Loop over all of the linked values to compute type mappings. |
| 1217 | computeTypeMapping(); |
| 1218 | |
| 1219 | std::reverse(Worklist.begin(), Worklist.end()); |
| 1220 | while (!Worklist.empty()) { |
| 1221 | GlobalValue *GV = Worklist.back(); |
| 1222 | Worklist.pop_back(); |
| 1223 | |
| 1224 | // Already mapped. |
| 1225 | if (ValueMap.find(GV) != ValueMap.end() || |
| 1226 | AliasValueMap.find(GV) != AliasValueMap.end()) |
| 1227 | continue; |
| 1228 | |
| 1229 | assert(!GV->isDeclaration()); |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 1230 | Mapper.mapValue(*GV); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1231 | if (HasError) |
| 1232 | return true; |
| 1233 | } |
| 1234 | |
| 1235 | // Note that we are done linking global value bodies. This prevents |
| 1236 | // metadata linking from creating new references. |
| 1237 | DoneLinkingBodies = true; |
Duncan P. N. Exon Smith | 39423b0 | 2016-04-16 02:29:55 +0000 | [diff] [blame^] | 1238 | Mapper.addFlags(RF_NullMapMissingGlobalValues); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1239 | |
| 1240 | // Remap all of the named MDNodes in Src into the DstM module. We do this |
| 1241 | // after linking GlobalValues so that MDNodes that reference GlobalValues |
| 1242 | // are properly remapped. |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1243 | linkNamedMDNodes(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1244 | |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1245 | // Merge the module flags into the DstM module. |
| 1246 | if (linkModuleFlagsMetadata()) |
| 1247 | return true; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1248 | |
| 1249 | return false; |
| 1250 | } |
| 1251 | |
| 1252 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) |
| 1253 | : ETypes(E), IsPacked(P) {} |
| 1254 | |
| 1255 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) |
| 1256 | : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} |
| 1257 | |
| 1258 | bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { |
| 1259 | if (IsPacked != That.IsPacked) |
| 1260 | return false; |
| 1261 | if (ETypes != That.ETypes) |
| 1262 | return false; |
| 1263 | return true; |
| 1264 | } |
| 1265 | |
| 1266 | bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { |
| 1267 | return !this->operator==(That); |
| 1268 | } |
| 1269 | |
| 1270 | StructType *IRMover::StructTypeKeyInfo::getEmptyKey() { |
| 1271 | return DenseMapInfo<StructType *>::getEmptyKey(); |
| 1272 | } |
| 1273 | |
| 1274 | StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() { |
| 1275 | return DenseMapInfo<StructType *>::getTombstoneKey(); |
| 1276 | } |
| 1277 | |
| 1278 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { |
| 1279 | return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), |
| 1280 | Key.IsPacked); |
| 1281 | } |
| 1282 | |
| 1283 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) { |
| 1284 | return getHashValue(KeyTy(ST)); |
| 1285 | } |
| 1286 | |
| 1287 | bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS, |
| 1288 | const StructType *RHS) { |
| 1289 | if (RHS == getEmptyKey() || RHS == getTombstoneKey()) |
| 1290 | return false; |
| 1291 | return LHS == KeyTy(RHS); |
| 1292 | } |
| 1293 | |
| 1294 | bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS, |
| 1295 | const StructType *RHS) { |
| 1296 | if (RHS == getEmptyKey()) |
| 1297 | return LHS == getEmptyKey(); |
| 1298 | |
| 1299 | if (RHS == getTombstoneKey()) |
| 1300 | return LHS == getTombstoneKey(); |
| 1301 | |
| 1302 | return KeyTy(LHS) == KeyTy(RHS); |
| 1303 | } |
| 1304 | |
| 1305 | void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { |
| 1306 | assert(!Ty->isOpaque()); |
| 1307 | NonOpaqueStructTypes.insert(Ty); |
| 1308 | } |
| 1309 | |
| 1310 | void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) { |
| 1311 | assert(!Ty->isOpaque()); |
| 1312 | NonOpaqueStructTypes.insert(Ty); |
| 1313 | bool Removed = OpaqueStructTypes.erase(Ty); |
| 1314 | (void)Removed; |
| 1315 | assert(Removed); |
| 1316 | } |
| 1317 | |
| 1318 | void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { |
| 1319 | assert(Ty->isOpaque()); |
| 1320 | OpaqueStructTypes.insert(Ty); |
| 1321 | } |
| 1322 | |
| 1323 | StructType * |
| 1324 | IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, |
| 1325 | bool IsPacked) { |
| 1326 | IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); |
| 1327 | auto I = NonOpaqueStructTypes.find_as(Key); |
| 1328 | if (I == NonOpaqueStructTypes.end()) |
| 1329 | return nullptr; |
| 1330 | return *I; |
| 1331 | } |
| 1332 | |
| 1333 | bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) { |
| 1334 | if (Ty->isOpaque()) |
| 1335 | return OpaqueStructTypes.count(Ty); |
| 1336 | auto I = NonOpaqueStructTypes.find(Ty); |
| 1337 | if (I == NonOpaqueStructTypes.end()) |
| 1338 | return false; |
| 1339 | return *I == Ty; |
| 1340 | } |
| 1341 | |
Rafael Espindola | 9d2bfc4 | 2015-12-14 23:17:03 +0000 | [diff] [blame] | 1342 | IRMover::IRMover(Module &M) : Composite(M) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1343 | TypeFinder StructTypes; |
| 1344 | StructTypes.run(M, true); |
| 1345 | for (StructType *Ty : StructTypes) { |
| 1346 | if (Ty->isOpaque()) |
| 1347 | IdentifiedStructTypes.addOpaque(Ty); |
| 1348 | else |
| 1349 | IdentifiedStructTypes.addNonOpaque(Ty); |
| 1350 | } |
| 1351 | } |
| 1352 | |
| 1353 | bool IRMover::move( |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1354 | std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1355 | std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1356 | IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src), |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1357 | ValuesToLink, AddLazyFor); |
Teresa Johnson | bef5436 | 2015-12-18 19:28:59 +0000 | [diff] [blame] | 1358 | bool RetCode = TheIRLinker.run(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1359 | Composite.dropTriviallyDeadConstantArrays(); |
| 1360 | return RetCode; |
| 1361 | } |