blob: 8f018234439e530b4aafa8584a2b101dae52fee2 [file] [log] [blame]
Rafael Espindolacaabe222015-12-10 14:19:35 +00001//===- 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 Johnson0e7c82c2015-12-18 17:51:37 +000016#include "llvm/IR/DebugInfo.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000017#include "llvm/IR/DiagnosticPrinter.h"
Teresa Johnsone5a61912015-12-17 17:14:09 +000018#include "llvm/IR/GVMaterializer.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000019#include "llvm/IR/TypeFinder.h"
20#include "llvm/Transforms/Utils/Cloning.h"
21using namespace llvm;
22
23//===----------------------------------------------------------------------===//
24// TypeMap implementation.
25//===----------------------------------------------------------------------===//
26
27namespace {
28class 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
47public:
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
71private:
72 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
73
74 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
75};
76}
77
78void 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.
106bool 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
191void 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
209void 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
223Type *TypeMapTy::get(Type *Ty) {
224 SmallPtrSet<StructType *, 8> Visited;
225 return get(Ty, Visited);
226}
227
228Type *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
332LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
333 const Twine &Msg)
334 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
335void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
336
337//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000338// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000339//===----------------------------------------------------------------------===//
340
341namespace {
342class 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.
347class GlobalValueMaterializer final : public ValueMaterializer {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000348 IRLinker *TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000349
350public:
Teresa Johnsonbef54362015-12-18 19:28:59 +0000351 GlobalValueMaterializer(IRLinker *TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000352 Value *materializeDeclFor(Value *V) override;
353 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000354 Metadata *mapTemporaryMetadata(Metadata *MD) override;
355 void replaceTemporaryMetadata(const Metadata *OrigMD,
356 Metadata *NewMD) override;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000357 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000358};
359
360class LocalValueMaterializer final : public ValueMaterializer {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000361 IRLinker *TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000362
363public:
Teresa Johnsonbef54362015-12-18 19:28:59 +0000364 LocalValueMaterializer(IRLinker *TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000365 Value *materializeDeclFor(Value *V) override;
366 void materializeInitFor(GlobalValue *New, GlobalValue *Old) override;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000367 Metadata *mapTemporaryMetadata(Metadata *MD) override;
368 void replaceTemporaryMetadata(const Metadata *OrigMD,
369 Metadata *NewMD) override;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000370 bool isMetadataNeeded(Metadata *MD) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000371};
372
373/// This is responsible for keeping track of the state used for moving data
374/// from SrcM to DstM.
375class IRLinker {
376 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000377 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000378
379 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
380
381 TypeMapTy TypeMap;
382 GlobalValueMaterializer GValMaterializer;
383 LocalValueMaterializer LValMaterializer;
384
385 /// Mapping of values from what they used to be in Src, to what they are now
386 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
387 /// due to the use of Value handles which the Linker doesn't actually need,
388 /// but this allows us to reuse the ValueMapper code.
389 ValueToValueMapTy ValueMap;
390 ValueToValueMapTy AliasValueMap;
391
392 DenseSet<GlobalValue *> ValuesToLink;
393 std::vector<GlobalValue *> Worklist;
394
395 void maybeAdd(GlobalValue *GV) {
396 if (ValuesToLink.insert(GV).second)
397 Worklist.push_back(GV);
398 }
399
Rafael Espindolacaabe222015-12-10 14:19:35 +0000400 /// Set to true when all global value body linking is complete (including
401 /// lazy linking). Used to prevent metadata linking from creating new
402 /// references.
403 bool DoneLinkingBodies = false;
404
405 bool HasError = false;
406
Teresa Johnsone5a61912015-12-17 17:14:09 +0000407 /// Flag indicating that we are just linking metadata (after function
408 /// importing).
409 bool IsMetadataLinkingPostpass;
410
411 /// Flags to pass to value mapper invocations.
412 RemapFlags ValueMapperFlags = RF_MoveDistinctMDs;
413
414 /// Association between metadata values created during bitcode parsing and
415 /// the value id. Used to correlate temporary metadata created during
416 /// function importing with the final metadata parsed during the subsequent
417 /// metadata linking postpass.
Teresa Johnson61b406e2015-12-29 23:00:22 +0000418 DenseMap<const Metadata *, unsigned> MetadataToIDs;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000419
420 /// Association between metadata value id and temporary metadata that
421 /// remains unmapped after function importing. Saved during function
422 /// importing and consumed during the metadata linking postpass.
423 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap;
424
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000425 /// Set of subprogram metadata that does not need to be linked into the
426 /// destination module, because the functions were not imported directly
427 /// or via an inlined body in an imported function.
428 SmallPtrSet<const Metadata *, 16> UnneededSubprograms;
429
Rafael Espindolacaabe222015-12-10 14:19:35 +0000430 /// Handles cloning of a global values from the source module into
431 /// the destination module, including setting the attributes and visibility.
432 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
433
434 /// Helper method for setting a message and returning an error code.
435 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000436 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000437 HasError = true;
438 return true;
439 }
440
441 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000442 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000443 }
444
Teresa Johnsone5a61912015-12-17 17:14:09 +0000445 /// Check whether we should be linking metadata from the source module.
446 bool shouldLinkMetadata() {
447 // ValIDToTempMDMap will be non-null when we are importing or otherwise want
448 // to link metadata lazily, and then when linking the metadata.
449 // We only want to return true for the former case.
450 return ValIDToTempMDMap == nullptr || IsMetadataLinkingPostpass;
451 }
452
Rafael Espindolacaabe222015-12-10 14:19:35 +0000453 /// Given a global in the source module, return the global in the
454 /// destination module that is being linked to, if any.
455 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
456 // If the source has no name it can't link. If it has local linkage,
457 // there is no name match-up going on.
458 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
459 return nullptr;
460
461 // Otherwise see if we have a match in the destination module's symtab.
462 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
463 if (!DGV)
464 return nullptr;
465
466 // If we found a global with the same name in the dest module, but it has
467 // internal linkage, we are really not doing any linkage here.
468 if (DGV->hasLocalLinkage())
469 return nullptr;
470
471 // Otherwise, we do in fact link to the destination global.
472 return DGV;
473 }
474
475 void computeTypeMapping();
476
477 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
478 const GlobalVariable *SrcGV);
479
480 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
481 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
482
483 bool linkModuleFlagsMetadata();
484
485 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
486 bool linkFunctionBody(Function &Dst, Function &Src);
487 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
488 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
489
490 /// Functions that take care of cloning a specific global value type
491 /// into the destination module.
492 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
493 Function *copyFunctionProto(const Function *SF);
494 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
495
496 void linkNamedMDNodes();
497
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000498 /// Populate the UnneededSubprograms set with the DISubprogram metadata
499 /// from the source module that we don't need to link into the dest module,
500 /// because the functions were not imported directly or via an inlined body
501 /// in an imported function.
Rafael Espindola394524d2016-01-21 00:00:53 +0000502 void findNeededSubprograms();
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000503
Teresa Johnson71d12d22016-01-25 22:04:56 +0000504 /// Recursive helper for findNeededSubprograms to locate any DISubprogram
505 /// reached from the given Node, marking any found as needed.
506 void findReachedSubprograms(const MDNode *Node,
507 SmallPtrSet<const MDNode *, 16> &Visited);
508
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000509 /// The value mapper leaves nulls in the list of subprograms for any
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +0000510 /// in the UnneededSubprograms map. Strip those out of the mapped
511 /// compile unit.
512 void stripNullSubprograms(DICompileUnit *CU);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000513
Rafael Espindolacaabe222015-12-10 14:19:35 +0000514public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000515 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set,
516 std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsone5a61912015-12-17 17:14:09 +0000517 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor,
518 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap = nullptr,
519 bool IsMetadataLinkingPostpass = false)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000520 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Teresa Johnsone5a61912015-12-17 17:14:09 +0000521 GValMaterializer(this), LValMaterializer(this),
522 IsMetadataLinkingPostpass(IsMetadataLinkingPostpass),
523 ValIDToTempMDMap(ValIDToTempMDMap) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000524 for (GlobalValue *GV : ValuesToLink)
525 maybeAdd(GV);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000526
527 // If appropriate, tell the value mapper that it can expect to see
528 // temporary metadata.
529 if (!shouldLinkMetadata())
530 ValueMapperFlags = ValueMapperFlags | RF_HaveUnmaterializedMetadata;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000531 }
532
Teresa Johnsoncc428572015-12-30 19:32:24 +0000533 ~IRLinker() {
534 // In the case where we are not linking metadata, we unset the CanReplace
535 // flag on all temporary metadata in the MetadataToIDs map to ensure
536 // none was replaced while being a map key. Now that we are destructing
537 // the map, set the flag back to true, so that it is replaceable during
538 // metadata linking.
539 if (!shouldLinkMetadata()) {
540 for (auto MDI : MetadataToIDs) {
541 Metadata *MD = const_cast<Metadata *>(MDI.first);
542 MDNode *Node = dyn_cast<MDNode>(MD);
543 assert((Node && Node->isTemporary()) &&
544 "Found non-temp metadata in map when not linking metadata");
545 Node->setCanReplace(true);
546 }
547 }
548 }
549
Rafael Espindolacaabe222015-12-10 14:19:35 +0000550 bool run();
551 Value *materializeDeclFor(Value *V, bool ForAlias);
552 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000553
554 /// Save the mapping between the given temporary metadata and its metadata
555 /// value id. Used to support metadata linking as a postpass for function
556 /// importing.
557 Metadata *mapTemporaryMetadata(Metadata *MD);
558
559 /// Replace any temporary metadata saved for the source metadata's id with
560 /// the new non-temporary metadata. Used when metadata linking as a postpass
561 /// for function importing.
562 void replaceTemporaryMetadata(const Metadata *OrigMD, Metadata *NewMD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000563
564 /// Indicates whether we need to map the given metadata into the destination
565 /// module. Used to prevent linking of metadata only needed by functions not
566 /// linked into the dest module.
567 bool isMetadataNeeded(Metadata *MD);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000568};
569}
570
571/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
572/// table. This is good for all clients except for us. Go through the trouble
573/// to force this back.
574static void forceRenaming(GlobalValue *GV, StringRef Name) {
575 // If the global doesn't force its name or if it already has the right name,
576 // there is nothing for us to do.
577 if (GV->hasLocalLinkage() || GV->getName() == Name)
578 return;
579
580 Module *M = GV->getParent();
581
582 // If there is a conflict, rename the conflict.
583 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
584 GV->takeName(ConflictGV);
585 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
586 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
587 } else {
588 GV->setName(Name); // Force the name back
589 }
590}
591
592Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000593 return TheIRLinker->materializeDeclFor(V, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000594}
595
596void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
597 GlobalValue *Old) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000598 TheIRLinker->materializeInitFor(New, Old, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000599}
600
Teresa Johnsone5a61912015-12-17 17:14:09 +0000601Metadata *GlobalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000602 return TheIRLinker->mapTemporaryMetadata(MD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000603}
604
605void GlobalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
606 Metadata *NewMD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000607 TheIRLinker->replaceTemporaryMetadata(OrigMD, NewMD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000608}
609
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000610bool GlobalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000611 return TheIRLinker->isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000612}
613
Rafael Espindolacaabe222015-12-10 14:19:35 +0000614Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000615 return TheIRLinker->materializeDeclFor(V, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000616}
617
618void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
619 GlobalValue *Old) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000620 TheIRLinker->materializeInitFor(New, Old, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000621}
622
Teresa Johnsone5a61912015-12-17 17:14:09 +0000623Metadata *LocalValueMaterializer::mapTemporaryMetadata(Metadata *MD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000624 return TheIRLinker->mapTemporaryMetadata(MD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000625}
626
627void LocalValueMaterializer::replaceTemporaryMetadata(const Metadata *OrigMD,
628 Metadata *NewMD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000629 TheIRLinker->replaceTemporaryMetadata(OrigMD, NewMD);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000630}
631
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000632bool LocalValueMaterializer::isMetadataNeeded(Metadata *MD) {
Teresa Johnsonbef54362015-12-18 19:28:59 +0000633 return TheIRLinker->isMetadataNeeded(MD);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000634}
635
Rafael Espindolacaabe222015-12-10 14:19:35 +0000636Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
637 auto *SGV = dyn_cast<GlobalValue>(V);
638 if (!SGV)
639 return nullptr;
640
641 return linkGlobalValueProto(SGV, ForAlias);
642}
643
644void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
645 bool ForAlias) {
646 // If we already created the body, just return.
647 if (auto *F = dyn_cast<Function>(New)) {
648 if (!F->isDeclaration())
649 return;
650 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
651 if (V->hasInitializer())
652 return;
653 } else {
654 auto *A = cast<GlobalAlias>(New);
655 if (A->getAliasee())
656 return;
657 }
658
659 if (ForAlias || shouldLink(New, *Old))
660 linkGlobalValueBody(*New, *Old);
661}
662
Teresa Johnsone5a61912015-12-17 17:14:09 +0000663Metadata *IRLinker::mapTemporaryMetadata(Metadata *MD) {
664 if (!ValIDToTempMDMap)
665 return nullptr;
666 // If this temporary metadata has a value id recorded during function
667 // parsing, record that in the ValIDToTempMDMap if one was provided.
Teresa Johnson6f508af2016-01-21 16:46:40 +0000668 auto I = MetadataToIDs.find(MD);
Teresa Johnsonf5aa64f2016-01-21 17:16:53 +0000669 if (I == MetadataToIDs.end())
670 return nullptr;
671 unsigned Idx = I->second;
672 MDNode *Node = cast<MDNode>(MD);
673 assert(Node->isTemporary());
674 // If we created a temp MD when importing a different function from
675 // this module, reuse the same temporary metadata.
676 auto IterBool = ValIDToTempMDMap->insert(std::make_pair(Idx, Node));
677 return IterBool.first->second;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000678}
679
680void IRLinker::replaceTemporaryMetadata(const Metadata *OrigMD,
681 Metadata *NewMD) {
682 if (!ValIDToTempMDMap)
683 return;
684#ifndef NDEBUG
685 auto *N = dyn_cast_or_null<MDNode>(NewMD);
686 assert(!N || !N->isTemporary());
687#endif
688 // If a mapping between metadata value ids and temporary metadata
689 // created during function importing was provided, and the source
690 // metadata has a value id recorded during metadata parsing, replace
691 // the temporary metadata with the final mapped metadata now.
Teresa Johnson6f508af2016-01-21 16:46:40 +0000692 auto I = MetadataToIDs.find(OrigMD);
Teresa Johnsonf5aa64f2016-01-21 17:16:53 +0000693 if (I == MetadataToIDs.end())
694 return;
695 unsigned Idx = I->second;
696 auto VI = ValIDToTempMDMap->find(Idx);
697 // Nothing to do if we didn't need to create a temporary metadata during
698 // function importing.
699 if (VI == ValIDToTempMDMap->end())
700 return;
701 MDNode *TempMD = VI->second;
702 TempMD->replaceAllUsesWith(NewMD);
703 MDNode::deleteTemporary(TempMD);
704 ValIDToTempMDMap->erase(VI);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000705}
706
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000707bool IRLinker::isMetadataNeeded(Metadata *MD) {
708 // Currently only DISubprogram metadata is marked as being unneeded.
709 if (UnneededSubprograms.empty())
710 return true;
711 MDNode *Node = dyn_cast<MDNode>(MD);
712 if (!Node)
713 return true;
714 DISubprogram *SP = getDISubprogram(Node);
715 if (!SP)
716 return true;
717 return !UnneededSubprograms.count(SP);
718}
719
Rafael Espindolacaabe222015-12-10 14:19:35 +0000720/// Loop through the global variables in the src module and merge them into the
721/// dest module.
722GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
723 // No linking to be performed or linking from the source: simply create an
724 // identical version of the symbol over in the dest module... the
725 // initializer will be filled in later by LinkGlobalInits.
726 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000727 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000728 SGVar->isConstant(), GlobalValue::ExternalLinkage,
729 /*init*/ nullptr, SGVar->getName(),
730 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
731 SGVar->getType()->getAddressSpace());
732 NewDGV->setAlignment(SGVar->getAlignment());
733 return NewDGV;
734}
735
736/// Link the function in the source module into the destination module if
737/// needed, setting up mapping information.
738Function *IRLinker::copyFunctionProto(const Function *SF) {
739 // If there is no linkage to be performed or we are linking from the source,
740 // bring SF over.
741 return Function::Create(TypeMap.get(SF->getFunctionType()),
742 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
743}
744
745/// Set up prototypes for any aliases that come over from the source module.
746GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
747 // If there is no linkage to be performed or we're linking from the source,
748 // bring over SGA.
749 auto *Ty = TypeMap.get(SGA->getValueType());
750 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
751 GlobalValue::ExternalLinkage, SGA->getName(),
752 &DstM);
753}
754
755GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
756 bool ForDefinition) {
757 GlobalValue *NewGV;
758 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
759 NewGV = copyGlobalVariableProto(SGVar);
760 } else if (auto *SF = dyn_cast<Function>(SGV)) {
761 NewGV = copyFunctionProto(SF);
762 } else {
763 if (ForDefinition)
764 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
765 else
766 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000767 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000768 /*isConstant*/ false, GlobalValue::ExternalLinkage,
769 /*init*/ nullptr, SGV->getName(),
770 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
771 SGV->getType()->getAddressSpace());
772 }
773
774 if (ForDefinition)
775 NewGV->setLinkage(SGV->getLinkage());
776 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
777 SGV->hasLinkOnceLinkage())
778 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
779
780 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000781
782 // Remove these copied constants in case this stays a declaration, since
783 // they point to the source module. If the def is linked the values will
784 // be mapped in during linkFunctionBody.
785 if (auto *NewF = dyn_cast<Function>(NewGV)) {
786 NewF->setPersonalityFn(nullptr);
787 NewF->setPrefixData(nullptr);
788 NewF->setPrologueData(nullptr);
789 }
790
Rafael Espindolacaabe222015-12-10 14:19:35 +0000791 return NewGV;
792}
793
794/// Loop over all of the linked values to compute type mappings. For example,
795/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
796/// types 'Foo' but one got renamed when the module was loaded into the same
797/// LLVMContext.
798void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000799 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000800 GlobalValue *DGV = getLinkedToGlobal(&SGV);
801 if (!DGV)
802 continue;
803
804 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
805 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
806 continue;
807 }
808
809 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000810 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
811 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000812 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
813 }
814
Rafael Espindola40358fb2016-02-16 18:50:12 +0000815 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000816 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
817 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
818
Rafael Espindola40358fb2016-02-16 18:50:12 +0000819 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000820 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
821 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
822
823 // Incorporate types by name, scanning all the types in the source module.
824 // At this point, the destination module may have a type "%foo = { i32 }" for
825 // example. When the source module got loaded into the same LLVMContext, if
826 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000827 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000828 for (StructType *ST : Types) {
829 if (!ST->hasName())
830 continue;
831
832 // Check to see if there is a dot in the name followed by a digit.
833 size_t DotPos = ST->getName().rfind('.');
834 if (DotPos == 0 || DotPos == StringRef::npos ||
835 ST->getName().back() == '.' ||
836 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
837 continue;
838
839 // Check to see if the destination module has a struct with the prefix name.
840 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
841 if (!DST)
842 continue;
843
844 // Don't use it if this actually came from the source module. They're in
845 // the same LLVMContext after all. Also don't use it unless the type is
846 // actually used in the destination module. This can happen in situations
847 // like this:
848 //
849 // Module A Module B
850 // -------- --------
851 // %Z = type { %A } %B = type { %C.1 }
852 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
853 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
854 // %C = type { i8* } %B.3 = type { %C.1 }
855 //
856 // When we link Module B with Module A, the '%B' in Module B is
857 // used. However, that would then use '%C.1'. But when we process '%C.1',
858 // we prefer to take the '%C' version. So we are then left with both
859 // '%C.1' and '%C' being used for the same types. This leads to some
860 // variables using one type and some using the other.
861 if (TypeMap.DstStructTypesSet.hasType(DST))
862 TypeMap.addTypeMapping(DST, ST);
863 }
864
865 // Now that we have discovered all of the type equivalences, get a body for
866 // any 'opaque' types in the dest module that are now resolved.
867 TypeMap.linkDefinedTypeBodies();
868}
869
870static void getArrayElements(const Constant *C,
871 SmallVectorImpl<Constant *> &Dest) {
872 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
873
874 for (unsigned i = 0; i != NumElements; ++i)
875 Dest.push_back(C->getAggregateElement(i));
876}
877
878/// If there were any appending global variables, link them together now.
879/// Return true on error.
880Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
881 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000882 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000883 ->getElementType();
884
885 StringRef Name = SrcGV->getName();
886 bool IsNewStructor = false;
887 bool IsOldStructor = false;
888 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
889 if (cast<StructType>(EltTy)->getNumElements() == 3)
890 IsNewStructor = true;
891 else
892 IsOldStructor = true;
893 }
894
895 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
896 if (IsOldStructor) {
897 auto &ST = *cast<StructType>(EltTy);
898 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
899 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
900 }
901
902 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000903 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000904
905 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
906 emitError(
907 "Linking globals named '" + SrcGV->getName() +
908 "': can only link appending global with another appending global!");
909 return nullptr;
910 }
911
912 // Check to see that they two arrays agree on type.
913 if (EltTy != DstTy->getElementType()) {
914 emitError("Appending variables with different element types!");
915 return nullptr;
916 }
917 if (DstGV->isConstant() != SrcGV->isConstant()) {
918 emitError("Appending variables linked with different const'ness!");
919 return nullptr;
920 }
921
922 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
923 emitError(
924 "Appending variables with different alignment need to be linked!");
925 return nullptr;
926 }
927
928 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
929 emitError(
930 "Appending variables with different visibility need to be linked!");
931 return nullptr;
932 }
933
934 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
935 emitError(
936 "Appending variables with different unnamed_addr need to be linked!");
937 return nullptr;
938 }
939
940 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
941 emitError(
942 "Appending variables with different section name need to be linked!");
943 return nullptr;
944 }
945 }
946
947 SmallVector<Constant *, 16> DstElements;
948 if (DstGV)
949 getArrayElements(DstGV->getInitializer(), DstElements);
950
951 SmallVector<Constant *, 16> SrcElements;
952 getArrayElements(SrcGV->getInitializer(), SrcElements);
953
954 if (IsNewStructor)
955 SrcElements.erase(
956 std::remove_if(SrcElements.begin(), SrcElements.end(),
957 [this](Constant *E) {
958 auto *Key = dyn_cast<GlobalValue>(
959 E->getAggregateElement(2)->stripPointerCasts());
960 if (!Key)
961 return false;
962 GlobalValue *DGV = getLinkedToGlobal(Key);
963 return !shouldLink(DGV, *Key);
964 }),
965 SrcElements.end());
966 uint64_t NewSize = DstElements.size() + SrcElements.size();
967 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
968
969 // Create the new global variable.
970 GlobalVariable *NG = new GlobalVariable(
971 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
972 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
973 SrcGV->getType()->getAddressSpace());
974
975 NG->copyAttributesFrom(SrcGV);
976 forceRenaming(NG, SrcGV->getName());
977
978 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
979
980 // Stop recursion.
981 ValueMap[SrcGV] = Ret;
982
983 for (auto *V : SrcElements) {
984 Constant *NewV;
985 if (IsOldStructor) {
986 auto *S = cast<ConstantStruct>(V);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000987 auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000988 &TypeMap, &GValMaterializer);
Teresa Johnsone5a61912015-12-17 17:14:09 +0000989 auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +0000990 &TypeMap, &GValMaterializer);
991 Value *Null = Constant::getNullValue(VoidPtrTy);
992 NewV =
993 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
994 } else {
Teresa Johnsone5a61912015-12-17 17:14:09 +0000995 NewV =
996 MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000997 }
998 DstElements.push_back(NewV);
999 }
1000
1001 NG->setInitializer(ConstantArray::get(NewType, DstElements));
1002
1003 // Replace any uses of the two global variables with uses of the new
1004 // global.
1005 if (DstGV) {
1006 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
1007 DstGV->eraseFromParent();
1008 }
1009
1010 return Ret;
1011}
1012
Rafael Espindolacaabe222015-12-10 14:19:35 +00001013bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
Teresa Johnsone5a61912015-12-17 17:14:09 +00001014 // Already imported all the values. Just map to the Dest value
1015 // in case it is referenced in the metadata.
1016 if (IsMetadataLinkingPostpass) {
1017 assert(!ValuesToLink.count(&SGV) &&
1018 "Source value unexpectedly requested for link during metadata link");
1019 return false;
1020 }
1021
Rafael Espindolacaabe222015-12-10 14:19:35 +00001022 if (ValuesToLink.count(&SGV))
1023 return true;
1024
1025 if (SGV.hasLocalLinkage())
1026 return true;
1027
Rafael Espindola55a7ae52016-01-20 22:38:23 +00001028 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +00001029 return false;
1030
1031 if (SGV.hasAvailableExternallyLinkage())
1032 return true;
1033
1034 if (DoneLinkingBodies)
1035 return false;
1036
1037 AddLazyFor(SGV, [this](GlobalValue &GV) { maybeAdd(&GV); });
1038 return ValuesToLink.count(&SGV);
1039}
1040
1041Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
1042 GlobalValue *DGV = getLinkedToGlobal(SGV);
1043
1044 bool ShouldLink = shouldLink(DGV, *SGV);
1045
1046 // just missing from map
1047 if (ShouldLink) {
1048 auto I = ValueMap.find(SGV);
1049 if (I != ValueMap.end())
1050 return cast<Constant>(I->second);
1051
1052 I = AliasValueMap.find(SGV);
1053 if (I != AliasValueMap.end())
1054 return cast<Constant>(I->second);
1055 }
1056
1057 DGV = nullptr;
1058 if (ShouldLink || !ForAlias)
1059 DGV = getLinkedToGlobal(SGV);
1060
1061 // Handle the ultra special appending linkage case first.
1062 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
1063 if (SGV->hasAppendingLinkage())
1064 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1065 cast<GlobalVariable>(SGV));
1066
1067 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +00001068 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001069 NewGV = DGV;
1070 } else {
1071 // If we are done linking global value bodies (i.e. we are performing
1072 // metadata linking), don't link in the global value due to this
1073 // reference, simply map it to null.
1074 if (DoneLinkingBodies)
1075 return nullptr;
1076
1077 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +00001078 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +00001079 forceRenaming(NewGV, SGV->getName());
1080 }
1081 if (ShouldLink || ForAlias) {
1082 if (const Comdat *SC = SGV->getComdat()) {
1083 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1084 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1085 DC->setSelectionKind(SC->getSelectionKind());
1086 GO->setComdat(DC);
1087 }
1088 }
1089 }
1090
1091 if (!ShouldLink && ForAlias)
1092 NewGV->setLinkage(GlobalValue::InternalLinkage);
1093
1094 Constant *C = NewGV;
1095 if (DGV)
1096 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
1097
1098 if (DGV && NewGV != DGV) {
1099 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
1100 DGV->eraseFromParent();
1101 }
1102
1103 return C;
1104}
1105
1106/// Update the initializers in the Dest module now that all globals that may be
1107/// referenced are in Dest.
1108void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
1109 // Figure out what the initializer looks like in the dest module.
Teresa Johnsone5a61912015-12-17 17:14:09 +00001110 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags,
1111 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001112}
1113
1114/// Copy the source function over into the dest function and fix up references
1115/// to values. At this point we know that Dest is an external function, and
1116/// that Src is not.
1117bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1118 assert(Dst.isDeclaration() && !Src.isDeclaration());
1119
1120 // Materialize if needed.
1121 if (std::error_code EC = Src.materialize())
1122 return emitError(EC.message());
1123
Teresa Johnsone5a61912015-12-17 17:14:09 +00001124 if (!shouldLinkMetadata())
1125 // This is only supported for lazy links. Do after materialization of
1126 // a function and before remapping metadata on instructions below
1127 // in RemapInstruction, as the saved mapping is used to handle
1128 // the temporary metadata hanging off instructions.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001129 SrcM->getMaterializer()->saveMetadataList(MetadataToIDs,
1130 /* OnlyTempMD = */ true);
Teresa Johnsone5a61912015-12-17 17:14:09 +00001131
Rafael Espindolacaabe222015-12-10 14:19:35 +00001132 // Link in the prefix data.
1133 if (Src.hasPrefixData())
Teresa Johnsone5a61912015-12-17 17:14:09 +00001134 Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap, ValueMapperFlags,
1135 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001136
1137 // Link in the prologue data.
1138 if (Src.hasPrologueData())
1139 Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001140 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001141 &GValMaterializer));
1142
1143 // Link in the personality function.
1144 if (Src.hasPersonalityFn())
1145 Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001146 ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001147 &GValMaterializer));
1148
1149 // Go through and convert function arguments over, remembering the mapping.
1150 Function::arg_iterator DI = Dst.arg_begin();
1151 for (Argument &Arg : Src.args()) {
1152 DI->setName(Arg.getName()); // Copy the name over.
1153
1154 // Add a mapping to our mapping.
1155 ValueMap[&Arg] = &*DI;
1156 ++DI;
1157 }
1158
1159 // Copy over the metadata attachments.
1160 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
1161 Src.getAllMetadata(MDs);
1162 for (const auto &I : MDs)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001163 Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, ValueMapperFlags,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001164 &TypeMap, &GValMaterializer));
1165
1166 // Splice the body of the source function into the dest function.
1167 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
1168
1169 // At this point, all of the instructions and values of the function are now
1170 // copied over. The only problem is that they are still referencing values in
1171 // the Source function as operands. Loop through all of the operands of the
1172 // functions and patch them up to point to the local versions.
1173 for (BasicBlock &BB : Dst)
1174 for (Instruction &I : BB)
Teresa Johnsone5a61912015-12-17 17:14:09 +00001175 RemapInstruction(&I, ValueMap, RF_IgnoreMissingEntries | ValueMapperFlags,
1176 &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001177
1178 // There is no need to map the arguments anymore.
1179 for (Argument &Arg : Src.args())
1180 ValueMap.erase(&Arg);
1181
Rafael Espindolacaabe222015-12-10 14:19:35 +00001182 return false;
1183}
1184
1185void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
1186 Constant *Aliasee = Src.getAliasee();
Teresa Johnsone5a61912015-12-17 17:14:09 +00001187 Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap,
Rafael Espindolacaabe222015-12-10 14:19:35 +00001188 &LValMaterializer);
1189 Dst.setAliasee(Val);
1190}
1191
1192bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1193 if (auto *F = dyn_cast<Function>(&Src))
1194 return linkFunctionBody(cast<Function>(Dst), *F);
1195 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1196 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
1197 return false;
1198 }
1199 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
1200 return false;
1201}
1202
Teresa Johnson71d12d22016-01-25 22:04:56 +00001203void IRLinker::findReachedSubprograms(
1204 const MDNode *Node, SmallPtrSet<const MDNode *, 16> &Visited) {
1205 if (!Visited.insert(Node).second)
1206 return;
1207 DISubprogram *SP = getDISubprogram(Node);
1208 if (SP)
1209 UnneededSubprograms.erase(SP);
1210 for (auto &Op : Node->operands()) {
1211 const MDNode *OpN = dyn_cast_or_null<MDNode>(Op.get());
1212 if (!OpN)
1213 continue;
1214 findReachedSubprograms(OpN, Visited);
1215 }
1216}
1217
Rafael Espindola394524d2016-01-21 00:00:53 +00001218void IRLinker::findNeededSubprograms() {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001219 // Track unneeded nodes to make it simpler to handle the case
1220 // where we are checking if an already-mapped SP is needed.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001221 NamedMDNode *CompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001222 if (!CompileUnits)
1223 return;
1224 for (unsigned I = 0, E = CompileUnits->getNumOperands(); I != E; ++I) {
1225 auto *CU = cast<DICompileUnit>(CompileUnits->getOperand(I));
1226 assert(CU && "Expected valid compile unit");
Teresa Johnsonb9515582016-01-07 00:06:27 +00001227 // Ensure that we don't remove subprograms referenced by DIImportedEntity.
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001228 // It is not legal to have a DIImportedEntity with a null entity or scope.
Teresa Johnsonf07db002016-01-25 21:29:55 +00001229 // Using getDISubprogram handles the case where the subprogram is reached
1230 // via an intervening DILexicalBlock.
Teresa Johnsonb9515582016-01-07 00:06:27 +00001231 // FIXME: The DISubprogram for functions not linked in but kept due to
1232 // being referenced by a DIImportedEntity should also get their
1233 // IsDefinition flag is unset.
1234 SmallPtrSet<DISubprogram *, 8> ImportedEntitySPs;
1235 for (auto *IE : CU->getImportedEntities()) {
Teresa Johnsonf07db002016-01-25 21:29:55 +00001236 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getEntity())))
Teresa Johnsonb9515582016-01-07 00:06:27 +00001237 ImportedEntitySPs.insert(SP);
Teresa Johnsonf07db002016-01-25 21:29:55 +00001238 if (auto *SP = getDISubprogram(dyn_cast<MDNode>(IE->getScope())))
Ahmed Bougachaa7324a22016-01-07 03:14:59 +00001239 ImportedEntitySPs.insert(SP);
Teresa Johnsonb9515582016-01-07 00:06:27 +00001240 }
Teresa Johnsond213aa42015-12-22 01:17:19 +00001241 for (auto *Op : CU->getSubprograms()) {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001242 // Unless we were doing function importing and deferred metadata linking,
1243 // any needed SPs should have been mapped as they would be reached
1244 // from the function linked in (either on the function itself for linked
1245 // function bodies, or from DILocation on inlined instructions).
1246 assert(!(ValueMap.MD()[Op] && IsMetadataLinkingPostpass) &&
1247 "DISubprogram shouldn't be mapped yet");
Teresa Johnsonb9515582016-01-07 00:06:27 +00001248 if (!ValueMap.MD()[Op] && !ImportedEntitySPs.count(Op))
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001249 UnneededSubprograms.insert(Op);
1250 }
1251 }
1252 if (!IsMetadataLinkingPostpass)
1253 return;
1254 // In the case of metadata linking as a postpass (e.g. for function
Teresa Johnson71d12d22016-01-25 22:04:56 +00001255 // importing), see which MD from the source has an associated
1256 // temporary metadata node, which means that any DISubprogram
1257 // reached from that MD was needed by an imported function.
1258 SmallPtrSet<const MDNode *, 16> Visited;
Teresa Johnson61b406e2015-12-29 23:00:22 +00001259 for (auto MDI : MetadataToIDs) {
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001260 const MDNode *Node = dyn_cast<MDNode>(MDI.first);
1261 if (!Node)
1262 continue;
Teresa Johnson71d12d22016-01-25 22:04:56 +00001263 if (!ValIDToTempMDMap->count(MDI.second))
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001264 continue;
Teresa Johnson71d12d22016-01-25 22:04:56 +00001265 // Find any SP needed recursively from this needed Node.
1266 findReachedSubprograms(Node, Visited);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001267 }
1268}
1269
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001270// Squash null subprograms from the given compile unit's subprogram list.
1271void IRLinker::stripNullSubprograms(DICompileUnit *CU) {
1272 // There won't be any nulls if we didn't have any subprograms marked
1273 // as unneeded.
1274 if (UnneededSubprograms.empty())
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001275 return;
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001276 SmallVector<Metadata *, 16> NewSPs;
1277 NewSPs.reserve(CU->getSubprograms().size());
1278 bool FoundNull = false;
1279 for (DISubprogram *SP : CU->getSubprograms()) {
1280 if (!SP) {
1281 FoundNull = true;
1282 continue;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001283 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001284 NewSPs.push_back(SP);
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001285 }
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001286 if (FoundNull)
1287 CU->replaceSubprograms(MDTuple::get(CU->getContext(), NewSPs));
Teresa Johnson0e7c82c2015-12-18 17:51:37 +00001288}
1289
Rafael Espindolacaabe222015-12-10 14:19:35 +00001290/// Insert all of the named MDNodes in Src into the Dest module.
1291void IRLinker::linkNamedMDNodes() {
Rafael Espindola394524d2016-01-21 00:00:53 +00001292 findNeededSubprograms();
Rafael Espindola40358fb2016-02-16 18:50:12 +00001293 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1294 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001295 // Don't link module flags here. Do them separately.
1296 if (&NMD == SrcModFlags)
1297 continue;
1298 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1299 // Add Src elements into Dest node.
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001300 for (const MDNode *op : NMD.operands()) {
1301 MDNode *DestMD = MapMetadata(
Teresa Johnsone5a61912015-12-17 17:14:09 +00001302 op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues,
Teresa Johnsonbeb43ba2016-01-28 15:08:09 +00001303 &TypeMap, &GValMaterializer);
1304 // For each newly mapped compile unit remove any null subprograms,
1305 // which occur when findNeededSubprograms identified any as unneeded
1306 // in the dest module.
1307 if (auto *CU = dyn_cast<DICompileUnit>(DestMD))
1308 stripNullSubprograms(CU);
1309 DestNMD->addOperand(DestMD);
1310 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001311 }
1312}
1313
1314/// Merge the linker flags in Src into the Dest module.
1315bool IRLinker::linkModuleFlagsMetadata() {
1316 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001317 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001318 if (!SrcModFlags)
1319 return false;
1320
1321 // If the destination module doesn't have module flags yet, then just copy
1322 // over the source module's flags.
1323 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1324 if (DstModFlags->getNumOperands() == 0) {
1325 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1326 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1327
1328 return false;
1329 }
1330
1331 // First build a map of the existing module flags and requirements.
1332 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1333 SmallSetVector<MDNode *, 16> Requirements;
1334 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1335 MDNode *Op = DstModFlags->getOperand(I);
1336 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1337 MDString *ID = cast<MDString>(Op->getOperand(1));
1338
1339 if (Behavior->getZExtValue() == Module::Require) {
1340 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1341 } else {
1342 Flags[ID] = std::make_pair(Op, I);
1343 }
1344 }
1345
1346 // Merge in the flags from the source module, and also collect its set of
1347 // requirements.
1348 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1349 MDNode *SrcOp = SrcModFlags->getOperand(I);
1350 ConstantInt *SrcBehavior =
1351 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1352 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1353 MDNode *DstOp;
1354 unsigned DstIndex;
1355 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1356 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1357
1358 // If this is a requirement, add it and continue.
1359 if (SrcBehaviorValue == Module::Require) {
1360 // If the destination module does not already have this requirement, add
1361 // it.
1362 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1363 DstModFlags->addOperand(SrcOp);
1364 }
1365 continue;
1366 }
1367
1368 // If there is no existing flag with this ID, just add it.
1369 if (!DstOp) {
1370 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1371 DstModFlags->addOperand(SrcOp);
1372 continue;
1373 }
1374
1375 // Otherwise, perform a merge.
1376 ConstantInt *DstBehavior =
1377 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1378 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1379
1380 // If either flag has override behavior, handle it first.
1381 if (DstBehaviorValue == Module::Override) {
1382 // Diagnose inconsistent flags which both have override behavior.
1383 if (SrcBehaviorValue == Module::Override &&
1384 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1385 emitError("linking module flags '" + ID->getString() +
1386 "': IDs have conflicting override values");
1387 }
1388 continue;
1389 } else if (SrcBehaviorValue == Module::Override) {
1390 // Update the destination flag to that of the source.
1391 DstModFlags->setOperand(DstIndex, SrcOp);
1392 Flags[ID].first = SrcOp;
1393 continue;
1394 }
1395
1396 // Diagnose inconsistent merge behavior types.
1397 if (SrcBehaviorValue != DstBehaviorValue) {
1398 emitError("linking module flags '" + ID->getString() +
1399 "': IDs have conflicting behaviors");
1400 continue;
1401 }
1402
1403 auto replaceDstValue = [&](MDNode *New) {
1404 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1405 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1406 DstModFlags->setOperand(DstIndex, Flag);
1407 Flags[ID].first = Flag;
1408 };
1409
1410 // Perform the merge for standard behavior types.
1411 switch (SrcBehaviorValue) {
1412 case Module::Require:
1413 case Module::Override:
1414 llvm_unreachable("not possible");
1415 case Module::Error: {
1416 // Emit an error if the values differ.
1417 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1418 emitError("linking module flags '" + ID->getString() +
1419 "': IDs have conflicting values");
1420 }
1421 continue;
1422 }
1423 case Module::Warning: {
1424 // Emit a warning if the values differ.
1425 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1426 emitWarning("linking module flags '" + ID->getString() +
1427 "': IDs have conflicting values");
1428 }
1429 continue;
1430 }
1431 case Module::Append: {
1432 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1433 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1434 SmallVector<Metadata *, 8> MDs;
1435 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1436 MDs.append(DstValue->op_begin(), DstValue->op_end());
1437 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1438
1439 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1440 break;
1441 }
1442 case Module::AppendUnique: {
1443 SmallSetVector<Metadata *, 16> Elts;
1444 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1445 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1446 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1447 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1448
1449 replaceDstValue(MDNode::get(DstM.getContext(),
1450 makeArrayRef(Elts.begin(), Elts.end())));
1451 break;
1452 }
1453 }
1454 }
1455
1456 // Check all of the requirements.
1457 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1458 MDNode *Requirement = Requirements[I];
1459 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1460 Metadata *ReqValue = Requirement->getOperand(1);
1461
1462 MDNode *Op = Flags[Flag].first;
1463 if (!Op || Op->getOperand(2) != ReqValue) {
1464 emitError("linking module flags '" + Flag->getString() +
1465 "': does not have the required value");
1466 continue;
1467 }
1468 }
1469
1470 return HasError;
1471}
1472
1473// This function returns true if the triples match.
1474static bool triplesMatch(const Triple &T0, const Triple &T1) {
1475 // If vendor is apple, ignore the version number.
1476 if (T0.getVendor() == Triple::Apple)
1477 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1478 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1479
1480 return T0 == T1;
1481}
1482
1483// This function returns the merged triple.
1484static std::string mergeTriples(const Triple &SrcTriple,
1485 const Triple &DstTriple) {
1486 // If vendor is apple, pick the triple with the larger version number.
1487 if (SrcTriple.getVendor() == Triple::Apple)
1488 if (DstTriple.isOSVersionLT(SrcTriple))
1489 return SrcTriple.str();
1490
1491 return DstTriple.str();
1492}
1493
1494bool IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001495 // Ensure metadata materialized before value mapping.
1496 if (shouldLinkMetadata() && SrcM->getMaterializer())
1497 if (SrcM->getMaterializer()->materializeMetadata())
1498 return true;
1499
Rafael Espindolacaabe222015-12-10 14:19:35 +00001500 // Inherit the target data from the source module if the destination module
1501 // doesn't have one already.
1502 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001503 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001504
Rafael Espindola40358fb2016-02-16 18:50:12 +00001505 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001506 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001507 SrcM->getModuleIdentifier() + "' is '" +
1508 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001509 DstM.getModuleIdentifier() + "' is '" +
1510 DstM.getDataLayoutStr() + "'\n");
1511 }
1512
1513 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001514 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1515 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001516
Rafael Espindola40358fb2016-02-16 18:50:12 +00001517 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001518
Rafael Espindola40358fb2016-02-16 18:50:12 +00001519 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001520 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001521 SrcM->getModuleIdentifier() + "' is '" +
1522 SrcM->getTargetTriple() + "' whereas '" +
1523 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1524 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001525
1526 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1527
1528 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001529 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001530 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001531 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001532 else
1533 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001534 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001535 }
1536
1537 // Loop over all of the linked values to compute type mappings.
1538 computeTypeMapping();
1539
1540 std::reverse(Worklist.begin(), Worklist.end());
1541 while (!Worklist.empty()) {
1542 GlobalValue *GV = Worklist.back();
1543 Worklist.pop_back();
1544
1545 // Already mapped.
1546 if (ValueMap.find(GV) != ValueMap.end() ||
1547 AliasValueMap.find(GV) != AliasValueMap.end())
1548 continue;
1549
1550 assert(!GV->isDeclaration());
Teresa Johnsone5a61912015-12-17 17:14:09 +00001551 MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001552 if (HasError)
1553 return true;
1554 }
1555
1556 // Note that we are done linking global value bodies. This prevents
1557 // metadata linking from creating new references.
1558 DoneLinkingBodies = true;
1559
1560 // Remap all of the named MDNodes in Src into the DstM module. We do this
1561 // after linking GlobalValues so that MDNodes that reference GlobalValues
1562 // are properly remapped.
Teresa Johnsone5a61912015-12-17 17:14:09 +00001563 if (shouldLinkMetadata()) {
1564 // Even if just linking metadata we should link decls above in case
1565 // any are referenced by metadata. IRLinker::shouldLink ensures that
1566 // we don't actually link anything from source.
Teresa Johnson0556e222016-03-10 18:47:03 +00001567 if (IsMetadataLinkingPostpass)
Rafael Espindola40358fb2016-02-16 18:50:12 +00001568 SrcM->getMaterializer()->saveMetadataList(MetadataToIDs,
1569 /* OnlyTempMD = */ false);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001570
Teresa Johnsone5a61912015-12-17 17:14:09 +00001571 linkNamedMDNodes();
1572
1573 if (IsMetadataLinkingPostpass) {
1574 // Handle anything left in the ValIDToTempMDMap, such as metadata nodes
1575 // not reached by the dbg.cu NamedMD (i.e. only reached from
1576 // instructions).
Teresa Johnson61b406e2015-12-29 23:00:22 +00001577 // Walk the MetadataToIDs once to find the set of new (imported) MD
Teresa Johnsone5a61912015-12-17 17:14:09 +00001578 // that still has corresponding temporary metadata, and invoke metadata
1579 // mapping on each one.
Teresa Johnson61b406e2015-12-29 23:00:22 +00001580 for (auto MDI : MetadataToIDs) {
Teresa Johnsone5a61912015-12-17 17:14:09 +00001581 if (!ValIDToTempMDMap->count(MDI.second))
1582 continue;
1583 MapMetadata(MDI.first, ValueMap, ValueMapperFlags, &TypeMap,
1584 &GValMaterializer);
1585 }
1586 assert(ValIDToTempMDMap->empty());
1587 }
1588
1589 // Merge the module flags into the DstM module.
1590 if (linkModuleFlagsMetadata())
1591 return true;
1592 }
Rafael Espindolacaabe222015-12-10 14:19:35 +00001593
1594 return false;
1595}
1596
1597IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1598 : ETypes(E), IsPacked(P) {}
1599
1600IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1601 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1602
1603bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1604 if (IsPacked != That.IsPacked)
1605 return false;
1606 if (ETypes != That.ETypes)
1607 return false;
1608 return true;
1609}
1610
1611bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1612 return !this->operator==(That);
1613}
1614
1615StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1616 return DenseMapInfo<StructType *>::getEmptyKey();
1617}
1618
1619StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1620 return DenseMapInfo<StructType *>::getTombstoneKey();
1621}
1622
1623unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1624 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1625 Key.IsPacked);
1626}
1627
1628unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1629 return getHashValue(KeyTy(ST));
1630}
1631
1632bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1633 const StructType *RHS) {
1634 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1635 return false;
1636 return LHS == KeyTy(RHS);
1637}
1638
1639bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1640 const StructType *RHS) {
1641 if (RHS == getEmptyKey())
1642 return LHS == getEmptyKey();
1643
1644 if (RHS == getTombstoneKey())
1645 return LHS == getTombstoneKey();
1646
1647 return KeyTy(LHS) == KeyTy(RHS);
1648}
1649
1650void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1651 assert(!Ty->isOpaque());
1652 NonOpaqueStructTypes.insert(Ty);
1653}
1654
1655void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1656 assert(!Ty->isOpaque());
1657 NonOpaqueStructTypes.insert(Ty);
1658 bool Removed = OpaqueStructTypes.erase(Ty);
1659 (void)Removed;
1660 assert(Removed);
1661}
1662
1663void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1664 assert(Ty->isOpaque());
1665 OpaqueStructTypes.insert(Ty);
1666}
1667
1668StructType *
1669IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1670 bool IsPacked) {
1671 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1672 auto I = NonOpaqueStructTypes.find_as(Key);
1673 if (I == NonOpaqueStructTypes.end())
1674 return nullptr;
1675 return *I;
1676}
1677
1678bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1679 if (Ty->isOpaque())
1680 return OpaqueStructTypes.count(Ty);
1681 auto I = NonOpaqueStructTypes.find(Ty);
1682 if (I == NonOpaqueStructTypes.end())
1683 return false;
1684 return *I == Ty;
1685}
1686
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001687IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001688 TypeFinder StructTypes;
1689 StructTypes.run(M, true);
1690 for (StructType *Ty : StructTypes) {
1691 if (Ty->isOpaque())
1692 IdentifiedStructTypes.addOpaque(Ty);
1693 else
1694 IdentifiedStructTypes.addNonOpaque(Ty);
1695 }
1696}
1697
1698bool IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001699 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsone5a61912015-12-17 17:14:09 +00001700 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor,
1701 DenseMap<unsigned, MDNode *> *ValIDToTempMDMap,
1702 bool IsMetadataLinkingPostpass) {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001703 IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src),
1704 ValuesToLink, AddLazyFor, ValIDToTempMDMap,
1705 IsMetadataLinkingPostpass);
Teresa Johnsonbef54362015-12-18 19:28:59 +00001706 bool RetCode = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001707 Composite.dropTriviallyDeadConstantArrays();
1708 return RetCode;
1709}