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 | |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 400 | /// Flags to pass to value mapper invocations. |
| 401 | RemapFlags ValueMapperFlags = RF_MoveDistinctMDs; |
| 402 | |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 403 | /// Set of subprogram metadata that does not need to be linked into the |
| 404 | /// destination module, because the functions were not imported directly |
| 405 | /// or via an inlined body in an imported function. |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 406 | bool HasUnneededSPs = false; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 407 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 408 | /// Handles cloning of a global values from the source module into |
| 409 | /// the destination module, including setting the attributes and visibility. |
| 410 | GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition); |
| 411 | |
| 412 | /// Helper method for setting a message and returning an error code. |
| 413 | bool emitError(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 414 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 415 | HasError = true; |
| 416 | return true; |
| 417 | } |
| 418 | |
| 419 | void emitWarning(const Twine &Message) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 420 | SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 421 | } |
| 422 | |
| 423 | /// Given a global in the source module, return the global in the |
| 424 | /// destination module that is being linked to, if any. |
| 425 | GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) { |
| 426 | // If the source has no name it can't link. If it has local linkage, |
| 427 | // there is no name match-up going on. |
| 428 | if (!SrcGV->hasName() || SrcGV->hasLocalLinkage()) |
| 429 | return nullptr; |
| 430 | |
| 431 | // Otherwise see if we have a match in the destination module's symtab. |
| 432 | GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName()); |
| 433 | if (!DGV) |
| 434 | return nullptr; |
| 435 | |
| 436 | // If we found a global with the same name in the dest module, but it has |
| 437 | // internal linkage, we are really not doing any linkage here. |
| 438 | if (DGV->hasLocalLinkage()) |
| 439 | return nullptr; |
| 440 | |
| 441 | // Otherwise, we do in fact link to the destination global. |
| 442 | return DGV; |
| 443 | } |
| 444 | |
| 445 | void computeTypeMapping(); |
| 446 | |
| 447 | Constant *linkAppendingVarProto(GlobalVariable *DstGV, |
| 448 | const GlobalVariable *SrcGV); |
| 449 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 450 | /// Given the GlobaValue \p SGV in the source module, and the matching |
| 451 | /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV |
| 452 | /// into the destination module. |
| 453 | /// |
| 454 | /// Note this code may call the client-provided \p AddLazyFor. |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 455 | bool shouldLink(GlobalValue *DGV, GlobalValue &SGV); |
| 456 | Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias); |
| 457 | |
| 458 | bool linkModuleFlagsMetadata(); |
| 459 | |
| 460 | void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src); |
| 461 | bool linkFunctionBody(Function &Dst, Function &Src); |
| 462 | void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src); |
| 463 | bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src); |
| 464 | |
| 465 | /// Functions that take care of cloning a specific global value type |
| 466 | /// into the destination module. |
| 467 | GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar); |
| 468 | Function *copyFunctionProto(const Function *SF); |
| 469 | GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA); |
| 470 | |
| 471 | void linkNamedMDNodes(); |
| 472 | |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 473 | /// Look for subprograms referenced from !llvm.dbg.cu that we don't want to |
| 474 | /// link in and map it to nullptr. |
| 475 | /// |
| 476 | /// \post HasUnneededSPs is true iff any unneeded subprograms were found. |
| 477 | void mapUnneededSubprograms(); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 478 | |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 479 | /// Remove null subprograms from !llvm.dbg.cu. |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 480 | void stripNullSubprograms(DICompileUnit *CU); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 481 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 482 | public: |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 483 | IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set, |
| 484 | std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 485 | std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 486 | : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set), |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 487 | GValMaterializer(*this), LValMaterializer(*this) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 488 | for (GlobalValue *GV : ValuesToLink) |
| 489 | maybeAdd(GV); |
Teresa Johnson | cc42857 | 2015-12-30 19:32:24 +0000 | [diff] [blame] | 490 | } |
| 491 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 492 | bool run(); |
| 493 | Value *materializeDeclFor(Value *V, bool ForAlias); |
| 494 | void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias); |
| 495 | }; |
| 496 | } |
| 497 | |
| 498 | /// The LLVM SymbolTable class autorenames globals that conflict in the symbol |
| 499 | /// table. This is good for all clients except for us. Go through the trouble |
| 500 | /// to force this back. |
| 501 | static void forceRenaming(GlobalValue *GV, StringRef Name) { |
| 502 | // If the global doesn't force its name or if it already has the right name, |
| 503 | // there is nothing for us to do. |
| 504 | if (GV->hasLocalLinkage() || GV->getName() == Name) |
| 505 | return; |
| 506 | |
| 507 | Module *M = GV->getParent(); |
| 508 | |
| 509 | // If there is a conflict, rename the conflict. |
| 510 | if (GlobalValue *ConflictGV = M->getNamedValue(Name)) { |
| 511 | GV->takeName(ConflictGV); |
| 512 | ConflictGV->setName(Name); // This will cause ConflictGV to get renamed |
| 513 | assert(ConflictGV->getName() != Name && "forceRenaming didn't work"); |
| 514 | } else { |
| 515 | GV->setName(Name); // Force the name back |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | Value *GlobalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 520 | return TheIRLinker.materializeDeclFor(V, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 521 | } |
| 522 | |
| 523 | void GlobalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 524 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 525 | TheIRLinker.materializeInitFor(New, Old, false); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 526 | } |
| 527 | |
| 528 | Value *LocalValueMaterializer::materializeDeclFor(Value *V) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 529 | return TheIRLinker.materializeDeclFor(V, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 530 | } |
| 531 | |
| 532 | void LocalValueMaterializer::materializeInitFor(GlobalValue *New, |
| 533 | GlobalValue *Old) { |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 534 | TheIRLinker.materializeInitFor(New, Old, true); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 535 | } |
| 536 | |
| 537 | Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) { |
| 538 | auto *SGV = dyn_cast<GlobalValue>(V); |
| 539 | if (!SGV) |
| 540 | return nullptr; |
| 541 | |
| 542 | return linkGlobalValueProto(SGV, ForAlias); |
| 543 | } |
| 544 | |
| 545 | void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old, |
| 546 | bool ForAlias) { |
| 547 | // If we already created the body, just return. |
| 548 | if (auto *F = dyn_cast<Function>(New)) { |
| 549 | if (!F->isDeclaration()) |
| 550 | return; |
| 551 | } else if (auto *V = dyn_cast<GlobalVariable>(New)) { |
| 552 | if (V->hasInitializer()) |
| 553 | return; |
| 554 | } else { |
| 555 | auto *A = cast<GlobalAlias>(New); |
| 556 | if (A->getAliasee()) |
| 557 | return; |
| 558 | } |
| 559 | |
| 560 | if (ForAlias || shouldLink(New, *Old)) |
| 561 | linkGlobalValueBody(*New, *Old); |
| 562 | } |
| 563 | |
| 564 | /// Loop through the global variables in the src module and merge them into the |
| 565 | /// dest module. |
| 566 | GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) { |
| 567 | // No linking to be performed or linking from the source: simply create an |
| 568 | // identical version of the symbol over in the dest module... the |
| 569 | // initializer will be filled in later by LinkGlobalInits. |
| 570 | GlobalVariable *NewDGV = |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 571 | new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 572 | SGVar->isConstant(), GlobalValue::ExternalLinkage, |
| 573 | /*init*/ nullptr, SGVar->getName(), |
| 574 | /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(), |
| 575 | SGVar->getType()->getAddressSpace()); |
| 576 | NewDGV->setAlignment(SGVar->getAlignment()); |
| 577 | return NewDGV; |
| 578 | } |
| 579 | |
| 580 | /// Link the function in the source module into the destination module if |
| 581 | /// needed, setting up mapping information. |
| 582 | Function *IRLinker::copyFunctionProto(const Function *SF) { |
| 583 | // If there is no linkage to be performed or we are linking from the source, |
| 584 | // bring SF over. |
| 585 | return Function::Create(TypeMap.get(SF->getFunctionType()), |
| 586 | GlobalValue::ExternalLinkage, SF->getName(), &DstM); |
| 587 | } |
| 588 | |
| 589 | /// Set up prototypes for any aliases that come over from the source module. |
| 590 | GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) { |
| 591 | // If there is no linkage to be performed or we're linking from the source, |
| 592 | // bring over SGA. |
| 593 | auto *Ty = TypeMap.get(SGA->getValueType()); |
| 594 | return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(), |
| 595 | GlobalValue::ExternalLinkage, SGA->getName(), |
| 596 | &DstM); |
| 597 | } |
| 598 | |
| 599 | GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV, |
| 600 | bool ForDefinition) { |
| 601 | GlobalValue *NewGV; |
| 602 | if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) { |
| 603 | NewGV = copyGlobalVariableProto(SGVar); |
| 604 | } else if (auto *SF = dyn_cast<Function>(SGV)) { |
| 605 | NewGV = copyFunctionProto(SF); |
| 606 | } else { |
| 607 | if (ForDefinition) |
| 608 | NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV)); |
| 609 | else |
| 610 | NewGV = new GlobalVariable( |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 611 | DstM, TypeMap.get(SGV->getValueType()), |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 612 | /*isConstant*/ false, GlobalValue::ExternalLinkage, |
| 613 | /*init*/ nullptr, SGV->getName(), |
| 614 | /*insertbefore*/ nullptr, SGV->getThreadLocalMode(), |
| 615 | SGV->getType()->getAddressSpace()); |
| 616 | } |
| 617 | |
| 618 | if (ForDefinition) |
| 619 | NewGV->setLinkage(SGV->getLinkage()); |
| 620 | else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() || |
| 621 | SGV->hasLinkOnceLinkage()) |
| 622 | NewGV->setLinkage(GlobalValue::ExternalWeakLinkage); |
| 623 | |
| 624 | NewGV->copyAttributesFrom(SGV); |
Teresa Johnson | 5fe4005 | 2016-01-12 00:24:24 +0000 | [diff] [blame] | 625 | |
| 626 | // Remove these copied constants in case this stays a declaration, since |
| 627 | // they point to the source module. If the def is linked the values will |
| 628 | // be mapped in during linkFunctionBody. |
| 629 | if (auto *NewF = dyn_cast<Function>(NewGV)) { |
| 630 | NewF->setPersonalityFn(nullptr); |
| 631 | NewF->setPrefixData(nullptr); |
| 632 | NewF->setPrologueData(nullptr); |
| 633 | } |
| 634 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 635 | return NewGV; |
| 636 | } |
| 637 | |
| 638 | /// Loop over all of the linked values to compute type mappings. For example, |
| 639 | /// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct |
| 640 | /// types 'Foo' but one got renamed when the module was loaded into the same |
| 641 | /// LLVMContext. |
| 642 | void IRLinker::computeTypeMapping() { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 643 | for (GlobalValue &SGV : SrcM->globals()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 644 | GlobalValue *DGV = getLinkedToGlobal(&SGV); |
| 645 | if (!DGV) |
| 646 | continue; |
| 647 | |
| 648 | if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) { |
| 649 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 650 | continue; |
| 651 | } |
| 652 | |
| 653 | // Unify the element type of appending arrays. |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 654 | ArrayType *DAT = cast<ArrayType>(DGV->getValueType()); |
| 655 | ArrayType *SAT = cast<ArrayType>(SGV.getValueType()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 656 | TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType()); |
| 657 | } |
| 658 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 659 | for (GlobalValue &SGV : *SrcM) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 660 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 661 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 662 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 663 | for (GlobalValue &SGV : SrcM->aliases()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 664 | if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) |
| 665 | TypeMap.addTypeMapping(DGV->getType(), SGV.getType()); |
| 666 | |
| 667 | // Incorporate types by name, scanning all the types in the source module. |
| 668 | // At this point, the destination module may have a type "%foo = { i32 }" for |
| 669 | // example. When the source module got loaded into the same LLVMContext, if |
| 670 | // 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] | 671 | std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 672 | for (StructType *ST : Types) { |
| 673 | if (!ST->hasName()) |
| 674 | continue; |
| 675 | |
| 676 | // Check to see if there is a dot in the name followed by a digit. |
| 677 | size_t DotPos = ST->getName().rfind('.'); |
| 678 | if (DotPos == 0 || DotPos == StringRef::npos || |
| 679 | ST->getName().back() == '.' || |
| 680 | !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1]))) |
| 681 | continue; |
| 682 | |
| 683 | // Check to see if the destination module has a struct with the prefix name. |
| 684 | StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos)); |
| 685 | if (!DST) |
| 686 | continue; |
| 687 | |
| 688 | // Don't use it if this actually came from the source module. They're in |
| 689 | // the same LLVMContext after all. Also don't use it unless the type is |
| 690 | // actually used in the destination module. This can happen in situations |
| 691 | // like this: |
| 692 | // |
| 693 | // Module A Module B |
| 694 | // -------- -------- |
| 695 | // %Z = type { %A } %B = type { %C.1 } |
| 696 | // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* } |
| 697 | // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] } |
| 698 | // %C = type { i8* } %B.3 = type { %C.1 } |
| 699 | // |
| 700 | // When we link Module B with Module A, the '%B' in Module B is |
| 701 | // used. However, that would then use '%C.1'. But when we process '%C.1', |
| 702 | // we prefer to take the '%C' version. So we are then left with both |
| 703 | // '%C.1' and '%C' being used for the same types. This leads to some |
| 704 | // variables using one type and some using the other. |
| 705 | if (TypeMap.DstStructTypesSet.hasType(DST)) |
| 706 | TypeMap.addTypeMapping(DST, ST); |
| 707 | } |
| 708 | |
| 709 | // Now that we have discovered all of the type equivalences, get a body for |
| 710 | // any 'opaque' types in the dest module that are now resolved. |
| 711 | TypeMap.linkDefinedTypeBodies(); |
| 712 | } |
| 713 | |
| 714 | static void getArrayElements(const Constant *C, |
| 715 | SmallVectorImpl<Constant *> &Dest) { |
| 716 | unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements(); |
| 717 | |
| 718 | for (unsigned i = 0; i != NumElements; ++i) |
| 719 | Dest.push_back(C->getAggregateElement(i)); |
| 720 | } |
| 721 | |
| 722 | /// If there were any appending global variables, link them together now. |
| 723 | /// Return true on error. |
| 724 | Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV, |
| 725 | const GlobalVariable *SrcGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 726 | Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType())) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 727 | ->getElementType(); |
| 728 | |
| 729 | StringRef Name = SrcGV->getName(); |
| 730 | bool IsNewStructor = false; |
| 731 | bool IsOldStructor = false; |
| 732 | if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") { |
| 733 | if (cast<StructType>(EltTy)->getNumElements() == 3) |
| 734 | IsNewStructor = true; |
| 735 | else |
| 736 | IsOldStructor = true; |
| 737 | } |
| 738 | |
| 739 | PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo(); |
| 740 | if (IsOldStructor) { |
| 741 | auto &ST = *cast<StructType>(EltTy); |
| 742 | Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy}; |
| 743 | EltTy = StructType::get(SrcGV->getContext(), Tys, false); |
| 744 | } |
| 745 | |
| 746 | if (DstGV) { |
Manuel Jacob | 5f6eaac | 2016-01-16 20:30:46 +0000 | [diff] [blame] | 747 | ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 748 | |
| 749 | if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) { |
| 750 | emitError( |
| 751 | "Linking globals named '" + SrcGV->getName() + |
| 752 | "': can only link appending global with another appending global!"); |
| 753 | return nullptr; |
| 754 | } |
| 755 | |
| 756 | // Check to see that they two arrays agree on type. |
| 757 | if (EltTy != DstTy->getElementType()) { |
| 758 | emitError("Appending variables with different element types!"); |
| 759 | return nullptr; |
| 760 | } |
| 761 | if (DstGV->isConstant() != SrcGV->isConstant()) { |
| 762 | emitError("Appending variables linked with different const'ness!"); |
| 763 | return nullptr; |
| 764 | } |
| 765 | |
| 766 | if (DstGV->getAlignment() != SrcGV->getAlignment()) { |
| 767 | emitError( |
| 768 | "Appending variables with different alignment need to be linked!"); |
| 769 | return nullptr; |
| 770 | } |
| 771 | |
| 772 | if (DstGV->getVisibility() != SrcGV->getVisibility()) { |
| 773 | emitError( |
| 774 | "Appending variables with different visibility need to be linked!"); |
| 775 | return nullptr; |
| 776 | } |
| 777 | |
| 778 | if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) { |
| 779 | emitError( |
| 780 | "Appending variables with different unnamed_addr need to be linked!"); |
| 781 | return nullptr; |
| 782 | } |
| 783 | |
| 784 | if (StringRef(DstGV->getSection()) != SrcGV->getSection()) { |
| 785 | emitError( |
| 786 | "Appending variables with different section name need to be linked!"); |
| 787 | return nullptr; |
| 788 | } |
| 789 | } |
| 790 | |
| 791 | SmallVector<Constant *, 16> DstElements; |
| 792 | if (DstGV) |
| 793 | getArrayElements(DstGV->getInitializer(), DstElements); |
| 794 | |
| 795 | SmallVector<Constant *, 16> SrcElements; |
| 796 | getArrayElements(SrcGV->getInitializer(), SrcElements); |
| 797 | |
| 798 | if (IsNewStructor) |
| 799 | SrcElements.erase( |
| 800 | std::remove_if(SrcElements.begin(), SrcElements.end(), |
| 801 | [this](Constant *E) { |
| 802 | auto *Key = dyn_cast<GlobalValue>( |
| 803 | E->getAggregateElement(2)->stripPointerCasts()); |
| 804 | if (!Key) |
| 805 | return false; |
| 806 | GlobalValue *DGV = getLinkedToGlobal(Key); |
| 807 | return !shouldLink(DGV, *Key); |
| 808 | }), |
| 809 | SrcElements.end()); |
| 810 | uint64_t NewSize = DstElements.size() + SrcElements.size(); |
| 811 | ArrayType *NewType = ArrayType::get(EltTy, NewSize); |
| 812 | |
| 813 | // Create the new global variable. |
| 814 | GlobalVariable *NG = new GlobalVariable( |
| 815 | DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(), |
| 816 | /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(), |
| 817 | SrcGV->getType()->getAddressSpace()); |
| 818 | |
| 819 | NG->copyAttributesFrom(SrcGV); |
| 820 | forceRenaming(NG, SrcGV->getName()); |
| 821 | |
| 822 | Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType())); |
| 823 | |
| 824 | // Stop recursion. |
| 825 | ValueMap[SrcGV] = Ret; |
| 826 | |
| 827 | for (auto *V : SrcElements) { |
| 828 | Constant *NewV; |
| 829 | if (IsOldStructor) { |
| 830 | auto *S = cast<ConstantStruct>(V); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 831 | auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 832 | &TypeMap, &GValMaterializer); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 833 | auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 834 | &TypeMap, &GValMaterializer); |
| 835 | Value *Null = Constant::getNullValue(VoidPtrTy); |
| 836 | NewV = |
| 837 | ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr); |
| 838 | } else { |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 839 | NewV = |
| 840 | MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 841 | } |
| 842 | DstElements.push_back(NewV); |
| 843 | } |
| 844 | |
| 845 | NG->setInitializer(ConstantArray::get(NewType, DstElements)); |
| 846 | |
| 847 | // Replace any uses of the two global variables with uses of the new |
| 848 | // global. |
| 849 | if (DstGV) { |
| 850 | DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType())); |
| 851 | DstGV->eraseFromParent(); |
| 852 | } |
| 853 | |
| 854 | return Ret; |
| 855 | } |
| 856 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 857 | bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) { |
| 858 | if (ValuesToLink.count(&SGV)) |
| 859 | return true; |
| 860 | |
| 861 | if (SGV.hasLocalLinkage()) |
| 862 | return true; |
| 863 | |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 864 | if (DGV && !DGV->isDeclarationForLinker()) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 865 | return false; |
| 866 | |
| 867 | if (SGV.hasAvailableExternallyLinkage()) |
| 868 | return true; |
| 869 | |
| 870 | if (DoneLinkingBodies) |
| 871 | return false; |
| 872 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 873 | |
| 874 | // Callback to the client to give a chance to lazily add the Global to the |
| 875 | // list of value to link. |
| 876 | bool LazilyAdded = false; |
| 877 | AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) { |
| 878 | maybeAdd(&GV); |
| 879 | LazilyAdded = true; |
| 880 | }); |
| 881 | return LazilyAdded; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 882 | } |
| 883 | |
| 884 | Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) { |
| 885 | GlobalValue *DGV = getLinkedToGlobal(SGV); |
| 886 | |
| 887 | bool ShouldLink = shouldLink(DGV, *SGV); |
| 888 | |
| 889 | // just missing from map |
| 890 | if (ShouldLink) { |
| 891 | auto I = ValueMap.find(SGV); |
| 892 | if (I != ValueMap.end()) |
| 893 | return cast<Constant>(I->second); |
| 894 | |
| 895 | I = AliasValueMap.find(SGV); |
| 896 | if (I != AliasValueMap.end()) |
| 897 | return cast<Constant>(I->second); |
| 898 | } |
| 899 | |
Mehdi Amini | 3366107 | 2016-03-11 22:19:06 +0000 | [diff] [blame] | 900 | if (!ShouldLink && ForAlias) |
| 901 | DGV = nullptr; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 902 | |
| 903 | // Handle the ultra special appending linkage case first. |
| 904 | assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage()); |
| 905 | if (SGV->hasAppendingLinkage()) |
| 906 | return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV), |
| 907 | cast<GlobalVariable>(SGV)); |
| 908 | |
| 909 | GlobalValue *NewGV; |
Rafael Espindola | 55a7ae5 | 2016-01-20 22:38:23 +0000 | [diff] [blame] | 910 | if (DGV && !ShouldLink) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 911 | NewGV = DGV; |
| 912 | } else { |
| 913 | // If we are done linking global value bodies (i.e. we are performing |
| 914 | // metadata linking), don't link in the global value due to this |
| 915 | // reference, simply map it to null. |
| 916 | if (DoneLinkingBodies) |
| 917 | return nullptr; |
| 918 | |
| 919 | NewGV = copyGlobalValueProto(SGV, ShouldLink); |
Evgeniy Stepanov | 9fb70f5 | 2016-01-20 22:05:50 +0000 | [diff] [blame] | 920 | if (ShouldLink || !ForAlias) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 921 | forceRenaming(NewGV, SGV->getName()); |
| 922 | } |
| 923 | if (ShouldLink || ForAlias) { |
| 924 | if (const Comdat *SC = SGV->getComdat()) { |
| 925 | if (auto *GO = dyn_cast<GlobalObject>(NewGV)) { |
| 926 | Comdat *DC = DstM.getOrInsertComdat(SC->getName()); |
| 927 | DC->setSelectionKind(SC->getSelectionKind()); |
| 928 | GO->setComdat(DC); |
| 929 | } |
| 930 | } |
| 931 | } |
| 932 | |
| 933 | if (!ShouldLink && ForAlias) |
| 934 | NewGV->setLinkage(GlobalValue::InternalLinkage); |
| 935 | |
| 936 | Constant *C = NewGV; |
| 937 | if (DGV) |
| 938 | C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType())); |
| 939 | |
| 940 | if (DGV && NewGV != DGV) { |
| 941 | DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType())); |
| 942 | DGV->eraseFromParent(); |
| 943 | } |
| 944 | |
| 945 | return C; |
| 946 | } |
| 947 | |
| 948 | /// Update the initializers in the Dest module now that all globals that may be |
| 949 | /// referenced are in Dest. |
| 950 | void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) { |
| 951 | // Figure out what the initializer looks like in the dest module. |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 952 | Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags, |
| 953 | &TypeMap, &GValMaterializer)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 954 | } |
| 955 | |
| 956 | /// Copy the source function over into the dest function and fix up references |
| 957 | /// to values. At this point we know that Dest is an external function, and |
| 958 | /// that Src is not. |
| 959 | bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) { |
| 960 | assert(Dst.isDeclaration() && !Src.isDeclaration()); |
| 961 | |
| 962 | // Materialize if needed. |
| 963 | if (std::error_code EC = Src.materialize()) |
| 964 | return emitError(EC.message()); |
| 965 | |
| 966 | // Link in the prefix data. |
| 967 | if (Src.hasPrefixData()) |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 968 | Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags, |
| 969 | &TypeMap, &GValMaterializer)); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 970 | |
| 971 | // Link in the prologue data. |
| 972 | if (Src.hasPrologueData()) |
| 973 | Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 974 | ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 975 | &GValMaterializer)); |
| 976 | |
| 977 | // Link in the personality function. |
| 978 | if (Src.hasPersonalityFn()) |
| 979 | Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 980 | ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 981 | &GValMaterializer)); |
| 982 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 983 | // Copy over the metadata attachments. |
| 984 | SmallVector<std::pair<unsigned, MDNode *>, 8> MDs; |
| 985 | Src.getAllMetadata(MDs); |
| 986 | for (const auto &I : MDs) |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 987 | Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 988 | &TypeMap, &GValMaterializer)); |
| 989 | |
Duncan P. N. Exon Smith | bdfc984 | 2016-04-06 06:38:15 +0000 | [diff] [blame] | 990 | // Steal arguments and splice the body of Src into Dst. |
| 991 | Dst.stealArgumentListFrom(Src); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 992 | Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList()); |
| 993 | |
Duncan P. N. Exon Smith | bdfc984 | 2016-04-06 06:38:15 +0000 | [diff] [blame] | 994 | // At this point, everything has been moved over, but the types and non-local |
| 995 | // operands will be wrong. Loop through everything and patch it up. |
| 996 | for (Argument &A : Dst.args()) |
| 997 | A.mutateType(TypeMap.get(A.getType())); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 998 | for (BasicBlock &BB : Dst) |
| 999 | for (Instruction &I : BB) |
Duncan P. N. Exon Smith | da68cbc | 2016-04-07 00:26:43 +0000 | [diff] [blame] | 1000 | RemapInstruction(&I, ValueMap, RF_IgnoreMissingLocals | ValueMapperFlags, |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1001 | &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1002 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1003 | return false; |
| 1004 | } |
| 1005 | |
| 1006 | void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) { |
| 1007 | Constant *Aliasee = Src.getAliasee(); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1008 | Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap, |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1009 | &LValMaterializer); |
| 1010 | Dst.setAliasee(Val); |
| 1011 | } |
| 1012 | |
| 1013 | bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) { |
| 1014 | if (auto *F = dyn_cast<Function>(&Src)) |
| 1015 | return linkFunctionBody(cast<Function>(Dst), *F); |
| 1016 | if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) { |
| 1017 | linkGlobalInit(cast<GlobalVariable>(Dst), *GVar); |
| 1018 | return false; |
| 1019 | } |
| 1020 | linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src)); |
| 1021 | return false; |
| 1022 | } |
| 1023 | |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 1024 | void IRLinker::mapUnneededSubprograms() { |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1025 | // Track unneeded nodes to make it simpler to handle the case |
| 1026 | // where we are checking if an already-mapped SP is needed. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1027 | NamedMDNode *CompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu"); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1028 | if (!CompileUnits) |
| 1029 | return; |
Duncan P. N. Exon Smith | 0d60a98 | 2016-04-02 17:39:31 +0000 | [diff] [blame] | 1030 | |
Duncan P. N. Exon Smith | 6d72d16 | 2016-04-02 17:54:01 +0000 | [diff] [blame] | 1031 | // Seed the ValueMap with the imported entities, in case they reference new |
| 1032 | // subprograms. |
| 1033 | // FIXME: The DISubprogram for functions not linked in but kept due to |
| 1034 | // being referenced by a DIImportedEntity should also get their |
| 1035 | // IsDefinition flag is unset. |
| 1036 | for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) { |
| 1037 | if (MDTuple *IEs = cast<DICompileUnit>(CompileUnits->getOperand(I)) |
| 1038 | ->getImportedEntities() |
| 1039 | .get()) |
Duncan P. N. Exon Smith | 0d60a98 | 2016-04-02 17:39:31 +0000 | [diff] [blame] | 1040 | (void)MapMetadata(IEs, ValueMap, |
| 1041 | ValueMapperFlags | RF_NullMapMissingGlobalValues, |
| 1042 | &TypeMap, &GValMaterializer); |
Duncan P. N. Exon Smith | 6d72d16 | 2016-04-02 17:54:01 +0000 | [diff] [blame] | 1043 | } |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 1044 | |
Duncan P. N. Exon Smith | 6d72d16 | 2016-04-02 17:54:01 +0000 | [diff] [blame] | 1045 | // Try to insert nullptr into the map for any SP not already mapped. If |
| 1046 | // the insertion succeeds, we don't need this subprogram. |
| 1047 | for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) { |
| 1048 | for (auto *Op : |
| 1049 | cast<DICompileUnit>(CompileUnits->getOperand(I))->getSubprograms()) |
Duncan P. N. Exon Smith | 0d60a98 | 2016-04-02 17:39:31 +0000 | [diff] [blame] | 1050 | if (ValueMap.MD().insert(std::make_pair(Op, TrackingMDRef())).second) |
| 1051 | HasUnneededSPs = true; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1052 | } |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1053 | } |
| 1054 | |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1055 | // Squash null subprograms from the given compile unit's subprogram list. |
| 1056 | void IRLinker::stripNullSubprograms(DICompileUnit *CU) { |
| 1057 | // There won't be any nulls if we didn't have any subprograms marked |
| 1058 | // as unneeded. |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 1059 | if (!HasUnneededSPs) |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1060 | return; |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1061 | SmallVector<Metadata *, 16> NewSPs; |
| 1062 | NewSPs.reserve(CU->getSubprograms().size()); |
| 1063 | bool FoundNull = false; |
| 1064 | for (DISubprogram *SP : CU->getSubprograms()) { |
| 1065 | if (!SP) { |
| 1066 | FoundNull = true; |
| 1067 | continue; |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1068 | } |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1069 | NewSPs.push_back(SP); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1070 | } |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1071 | if (FoundNull) |
| 1072 | CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs)); |
Teresa Johnson | 0e7c82c | 2015-12-18 17:51:37 +0000 | [diff] [blame] | 1073 | } |
| 1074 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1075 | /// Insert all of the named MDNodes in Src into the Dest module. |
| 1076 | void IRLinker::linkNamedMDNodes() { |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 1077 | mapUnneededSubprograms(); |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1078 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
| 1079 | for (const NamedMDNode &NMD : SrcM->named_metadata()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1080 | // Don't link module flags here. Do them separately. |
| 1081 | if (&NMD == SrcModFlags) |
| 1082 | continue; |
| 1083 | NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); |
| 1084 | // Add Src elements into Dest node. |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1085 | for (const MDNode *op : NMD.operands()) { |
| 1086 | MDNode *DestMD = MapMetadata( |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1087 | op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues, |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1088 | &TypeMap, &GValMaterializer); |
| 1089 | // For each newly mapped compile unit remove any null subprograms, |
Duncan P. N. Exon Smith | 4b520e5 | 2016-04-02 17:12:00 +0000 | [diff] [blame] | 1090 | // which occur when mapUnneededSubprograms identified any as unneeded |
Teresa Johnson | beb43ba | 2016-01-28 15:08:09 +0000 | [diff] [blame] | 1091 | // in the dest module. |
| 1092 | if (auto *CU = dyn_cast<DICompileUnit>(DestMD)) |
| 1093 | stripNullSubprograms(CU); |
| 1094 | DestNMD->addOperand(DestMD); |
| 1095 | } |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1096 | } |
| 1097 | } |
| 1098 | |
| 1099 | /// Merge the linker flags in Src into the Dest module. |
| 1100 | bool IRLinker::linkModuleFlagsMetadata() { |
| 1101 | // If the source module has no module flags, we are done. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1102 | const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1103 | if (!SrcModFlags) |
| 1104 | return false; |
| 1105 | |
| 1106 | // If the destination module doesn't have module flags yet, then just copy |
| 1107 | // over the source module's flags. |
| 1108 | NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata(); |
| 1109 | if (DstModFlags->getNumOperands() == 0) { |
| 1110 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) |
| 1111 | DstModFlags->addOperand(SrcModFlags->getOperand(I)); |
| 1112 | |
| 1113 | return false; |
| 1114 | } |
| 1115 | |
| 1116 | // First build a map of the existing module flags and requirements. |
| 1117 | DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; |
| 1118 | SmallSetVector<MDNode *, 16> Requirements; |
| 1119 | for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { |
| 1120 | MDNode *Op = DstModFlags->getOperand(I); |
| 1121 | ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); |
| 1122 | MDString *ID = cast<MDString>(Op->getOperand(1)); |
| 1123 | |
| 1124 | if (Behavior->getZExtValue() == Module::Require) { |
| 1125 | Requirements.insert(cast<MDNode>(Op->getOperand(2))); |
| 1126 | } else { |
| 1127 | Flags[ID] = std::make_pair(Op, I); |
| 1128 | } |
| 1129 | } |
| 1130 | |
| 1131 | // Merge in the flags from the source module, and also collect its set of |
| 1132 | // requirements. |
| 1133 | for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { |
| 1134 | MDNode *SrcOp = SrcModFlags->getOperand(I); |
| 1135 | ConstantInt *SrcBehavior = |
| 1136 | mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); |
| 1137 | MDString *ID = cast<MDString>(SrcOp->getOperand(1)); |
| 1138 | MDNode *DstOp; |
| 1139 | unsigned DstIndex; |
| 1140 | std::tie(DstOp, DstIndex) = Flags.lookup(ID); |
| 1141 | unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); |
| 1142 | |
| 1143 | // If this is a requirement, add it and continue. |
| 1144 | if (SrcBehaviorValue == Module::Require) { |
| 1145 | // If the destination module does not already have this requirement, add |
| 1146 | // it. |
| 1147 | if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { |
| 1148 | DstModFlags->addOperand(SrcOp); |
| 1149 | } |
| 1150 | continue; |
| 1151 | } |
| 1152 | |
| 1153 | // If there is no existing flag with this ID, just add it. |
| 1154 | if (!DstOp) { |
| 1155 | Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); |
| 1156 | DstModFlags->addOperand(SrcOp); |
| 1157 | continue; |
| 1158 | } |
| 1159 | |
| 1160 | // Otherwise, perform a merge. |
| 1161 | ConstantInt *DstBehavior = |
| 1162 | mdconst::extract<ConstantInt>(DstOp->getOperand(0)); |
| 1163 | unsigned DstBehaviorValue = DstBehavior->getZExtValue(); |
| 1164 | |
| 1165 | // If either flag has override behavior, handle it first. |
| 1166 | if (DstBehaviorValue == Module::Override) { |
| 1167 | // Diagnose inconsistent flags which both have override behavior. |
| 1168 | if (SrcBehaviorValue == Module::Override && |
| 1169 | SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1170 | emitError("linking module flags '" + ID->getString() + |
| 1171 | "': IDs have conflicting override values"); |
| 1172 | } |
| 1173 | continue; |
| 1174 | } else if (SrcBehaviorValue == Module::Override) { |
| 1175 | // Update the destination flag to that of the source. |
| 1176 | DstModFlags->setOperand(DstIndex, SrcOp); |
| 1177 | Flags[ID].first = SrcOp; |
| 1178 | continue; |
| 1179 | } |
| 1180 | |
| 1181 | // Diagnose inconsistent merge behavior types. |
| 1182 | if (SrcBehaviorValue != DstBehaviorValue) { |
| 1183 | emitError("linking module flags '" + ID->getString() + |
| 1184 | "': IDs have conflicting behaviors"); |
| 1185 | continue; |
| 1186 | } |
| 1187 | |
| 1188 | auto replaceDstValue = [&](MDNode *New) { |
| 1189 | Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; |
| 1190 | MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps); |
| 1191 | DstModFlags->setOperand(DstIndex, Flag); |
| 1192 | Flags[ID].first = Flag; |
| 1193 | }; |
| 1194 | |
| 1195 | // Perform the merge for standard behavior types. |
| 1196 | switch (SrcBehaviorValue) { |
| 1197 | case Module::Require: |
| 1198 | case Module::Override: |
| 1199 | llvm_unreachable("not possible"); |
| 1200 | case Module::Error: { |
| 1201 | // Emit an error if the values differ. |
| 1202 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1203 | emitError("linking module flags '" + ID->getString() + |
| 1204 | "': IDs have conflicting values"); |
| 1205 | } |
| 1206 | continue; |
| 1207 | } |
| 1208 | case Module::Warning: { |
| 1209 | // Emit a warning if the values differ. |
| 1210 | if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { |
| 1211 | emitWarning("linking module flags '" + ID->getString() + |
| 1212 | "': IDs have conflicting values"); |
| 1213 | } |
| 1214 | continue; |
| 1215 | } |
| 1216 | case Module::Append: { |
| 1217 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1218 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1219 | SmallVector<Metadata *, 8> MDs; |
| 1220 | MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); |
| 1221 | MDs.append(DstValue->op_begin(), DstValue->op_end()); |
| 1222 | MDs.append(SrcValue->op_begin(), SrcValue->op_end()); |
| 1223 | |
| 1224 | replaceDstValue(MDNode::get(DstM.getContext(), MDs)); |
| 1225 | break; |
| 1226 | } |
| 1227 | case Module::AppendUnique: { |
| 1228 | SmallSetVector<Metadata *, 16> Elts; |
| 1229 | MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); |
| 1230 | MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); |
| 1231 | Elts.insert(DstValue->op_begin(), DstValue->op_end()); |
| 1232 | Elts.insert(SrcValue->op_begin(), SrcValue->op_end()); |
| 1233 | |
| 1234 | replaceDstValue(MDNode::get(DstM.getContext(), |
| 1235 | makeArrayRef(Elts.begin(), Elts.end()))); |
| 1236 | break; |
| 1237 | } |
| 1238 | } |
| 1239 | } |
| 1240 | |
| 1241 | // Check all of the requirements. |
| 1242 | for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { |
| 1243 | MDNode *Requirement = Requirements[I]; |
| 1244 | MDString *Flag = cast<MDString>(Requirement->getOperand(0)); |
| 1245 | Metadata *ReqValue = Requirement->getOperand(1); |
| 1246 | |
| 1247 | MDNode *Op = Flags[Flag].first; |
| 1248 | if (!Op || Op->getOperand(2) != ReqValue) { |
| 1249 | emitError("linking module flags '" + Flag->getString() + |
| 1250 | "': does not have the required value"); |
| 1251 | continue; |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | return HasError; |
| 1256 | } |
| 1257 | |
| 1258 | // This function returns true if the triples match. |
| 1259 | static bool triplesMatch(const Triple &T0, const Triple &T1) { |
| 1260 | // If vendor is apple, ignore the version number. |
| 1261 | if (T0.getVendor() == Triple::Apple) |
| 1262 | return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() && |
| 1263 | T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS(); |
| 1264 | |
| 1265 | return T0 == T1; |
| 1266 | } |
| 1267 | |
| 1268 | // This function returns the merged triple. |
| 1269 | static std::string mergeTriples(const Triple &SrcTriple, |
| 1270 | const Triple &DstTriple) { |
| 1271 | // If vendor is apple, pick the triple with the larger version number. |
| 1272 | if (SrcTriple.getVendor() == Triple::Apple) |
| 1273 | if (DstTriple.isOSVersionLT(SrcTriple)) |
| 1274 | return SrcTriple.str(); |
| 1275 | |
| 1276 | return DstTriple.str(); |
| 1277 | } |
| 1278 | |
| 1279 | bool IRLinker::run() { |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1280 | // Ensure metadata materialized before value mapping. |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1281 | if (SrcM->getMaterializer() && SrcM->getMaterializer()->materializeMetadata()) |
Teresa Johnson | 0556e22 | 2016-03-10 18:47:03 +0000 | [diff] [blame] | 1282 | return true; |
| 1283 | |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1284 | // Inherit the target data from the source module if the destination module |
| 1285 | // doesn't have one already. |
| 1286 | if (DstM.getDataLayout().isDefault()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1287 | DstM.setDataLayout(SrcM->getDataLayout()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1288 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1289 | if (SrcM->getDataLayout() != DstM.getDataLayout()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1290 | emitWarning("Linking two modules of different data layouts: '" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1291 | SrcM->getModuleIdentifier() + "' is '" + |
| 1292 | SrcM->getDataLayoutStr() + "' whereas '" + |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1293 | DstM.getModuleIdentifier() + "' is '" + |
| 1294 | DstM.getDataLayoutStr() + "'\n"); |
| 1295 | } |
| 1296 | |
| 1297 | // 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] | 1298 | if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty()) |
| 1299 | DstM.setTargetTriple(SrcM->getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1300 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1301 | Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1302 | |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1303 | if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple)) |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1304 | emitWarning("Linking two modules of different target triples: " + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1305 | SrcM->getModuleIdentifier() + "' is '" + |
| 1306 | SrcM->getTargetTriple() + "' whereas '" + |
| 1307 | DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() + |
| 1308 | "'\n"); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1309 | |
| 1310 | DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple)); |
| 1311 | |
| 1312 | // Append the module inline asm string. |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1313 | if (!SrcM->getModuleInlineAsm().empty()) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1314 | if (DstM.getModuleInlineAsm().empty()) |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1315 | DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1316 | else |
| 1317 | DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" + |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1318 | SrcM->getModuleInlineAsm()); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1319 | } |
| 1320 | |
| 1321 | // Loop over all of the linked values to compute type mappings. |
| 1322 | computeTypeMapping(); |
| 1323 | |
| 1324 | std::reverse(Worklist.begin(), Worklist.end()); |
| 1325 | while (!Worklist.empty()) { |
| 1326 | GlobalValue *GV = Worklist.back(); |
| 1327 | Worklist.pop_back(); |
| 1328 | |
| 1329 | // Already mapped. |
| 1330 | if (ValueMap.find(GV) != ValueMap.end() || |
| 1331 | AliasValueMap.find(GV) != AliasValueMap.end()) |
| 1332 | continue; |
| 1333 | |
| 1334 | assert(!GV->isDeclaration()); |
Teresa Johnson | e5a6191 | 2015-12-17 17:14:09 +0000 | [diff] [blame] | 1335 | MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1336 | if (HasError) |
| 1337 | return true; |
| 1338 | } |
| 1339 | |
| 1340 | // Note that we are done linking global value bodies. This prevents |
| 1341 | // metadata linking from creating new references. |
| 1342 | DoneLinkingBodies = true; |
| 1343 | |
| 1344 | // Remap all of the named MDNodes in Src into the DstM module. We do this |
| 1345 | // after linking GlobalValues so that MDNodes that reference GlobalValues |
| 1346 | // are properly remapped. |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1347 | linkNamedMDNodes(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1348 | |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1349 | // Merge the module flags into the DstM module. |
| 1350 | if (linkModuleFlagsMetadata()) |
| 1351 | return true; |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1352 | |
| 1353 | return false; |
| 1354 | } |
| 1355 | |
| 1356 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P) |
| 1357 | : ETypes(E), IsPacked(P) {} |
| 1358 | |
| 1359 | IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST) |
| 1360 | : ETypes(ST->elements()), IsPacked(ST->isPacked()) {} |
| 1361 | |
| 1362 | bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const { |
| 1363 | if (IsPacked != That.IsPacked) |
| 1364 | return false; |
| 1365 | if (ETypes != That.ETypes) |
| 1366 | return false; |
| 1367 | return true; |
| 1368 | } |
| 1369 | |
| 1370 | bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const { |
| 1371 | return !this->operator==(That); |
| 1372 | } |
| 1373 | |
| 1374 | StructType *IRMover::StructTypeKeyInfo::getEmptyKey() { |
| 1375 | return DenseMapInfo<StructType *>::getEmptyKey(); |
| 1376 | } |
| 1377 | |
| 1378 | StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() { |
| 1379 | return DenseMapInfo<StructType *>::getTombstoneKey(); |
| 1380 | } |
| 1381 | |
| 1382 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) { |
| 1383 | return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()), |
| 1384 | Key.IsPacked); |
| 1385 | } |
| 1386 | |
| 1387 | unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) { |
| 1388 | return getHashValue(KeyTy(ST)); |
| 1389 | } |
| 1390 | |
| 1391 | bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS, |
| 1392 | const StructType *RHS) { |
| 1393 | if (RHS == getEmptyKey() || RHS == getTombstoneKey()) |
| 1394 | return false; |
| 1395 | return LHS == KeyTy(RHS); |
| 1396 | } |
| 1397 | |
| 1398 | bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS, |
| 1399 | const StructType *RHS) { |
| 1400 | if (RHS == getEmptyKey()) |
| 1401 | return LHS == getEmptyKey(); |
| 1402 | |
| 1403 | if (RHS == getTombstoneKey()) |
| 1404 | return LHS == getTombstoneKey(); |
| 1405 | |
| 1406 | return KeyTy(LHS) == KeyTy(RHS); |
| 1407 | } |
| 1408 | |
| 1409 | void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) { |
| 1410 | assert(!Ty->isOpaque()); |
| 1411 | NonOpaqueStructTypes.insert(Ty); |
| 1412 | } |
| 1413 | |
| 1414 | void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) { |
| 1415 | assert(!Ty->isOpaque()); |
| 1416 | NonOpaqueStructTypes.insert(Ty); |
| 1417 | bool Removed = OpaqueStructTypes.erase(Ty); |
| 1418 | (void)Removed; |
| 1419 | assert(Removed); |
| 1420 | } |
| 1421 | |
| 1422 | void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) { |
| 1423 | assert(Ty->isOpaque()); |
| 1424 | OpaqueStructTypes.insert(Ty); |
| 1425 | } |
| 1426 | |
| 1427 | StructType * |
| 1428 | IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes, |
| 1429 | bool IsPacked) { |
| 1430 | IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked); |
| 1431 | auto I = NonOpaqueStructTypes.find_as(Key); |
| 1432 | if (I == NonOpaqueStructTypes.end()) |
| 1433 | return nullptr; |
| 1434 | return *I; |
| 1435 | } |
| 1436 | |
| 1437 | bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) { |
| 1438 | if (Ty->isOpaque()) |
| 1439 | return OpaqueStructTypes.count(Ty); |
| 1440 | auto I = NonOpaqueStructTypes.find(Ty); |
| 1441 | if (I == NonOpaqueStructTypes.end()) |
| 1442 | return false; |
| 1443 | return *I == Ty; |
| 1444 | } |
| 1445 | |
Rafael Espindola | 9d2bfc4 | 2015-12-14 23:17:03 +0000 | [diff] [blame] | 1446 | IRMover::IRMover(Module &M) : Composite(M) { |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1447 | TypeFinder StructTypes; |
| 1448 | StructTypes.run(M, true); |
| 1449 | for (StructType *Ty : StructTypes) { |
| 1450 | if (Ty->isOpaque()) |
| 1451 | IdentifiedStructTypes.addOpaque(Ty); |
| 1452 | else |
| 1453 | IdentifiedStructTypes.addNonOpaque(Ty); |
| 1454 | } |
| 1455 | } |
| 1456 | |
| 1457 | bool IRMover::move( |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1458 | std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink, |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1459 | std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) { |
Rafael Espindola | 40358fb | 2016-02-16 18:50:12 +0000 | [diff] [blame] | 1460 | IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src), |
Teresa Johnson | b703c77 | 2016-03-29 18:24:19 +0000 | [diff] [blame] | 1461 | ValuesToLink, AddLazyFor); |
Teresa Johnson | bef5436 | 2015-12-18 19:28:59 +0000 | [diff] [blame] | 1462 | bool RetCode = TheIRLinker.run(); |
Rafael Espindola | caabe22 | 2015-12-10 14:19:35 +0000 | [diff] [blame] | 1463 | Composite.dropTriviallyDeadConstantArrays(); |
| 1464 | return RetCode; |
| 1465 | } |