blob: e4121fedc0a2d879c0e61fb7684f4f5a5bfd5b82 [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 {
Mehdi Amini33661072016-03-11 22:19:06 +0000348 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000349
350public:
Mehdi Amini33661072016-03-11 22:19:06 +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;
354};
355
356class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000357 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000358
359public:
Mehdi Amini33661072016-03-11 22:19:06 +0000360 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000361 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.
367class IRLinker {
368 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000369 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000370
Mehdi Amini33661072016-03-11 22:19:06 +0000371 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000372 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 Espindolacaabe222015-12-10 14:19:35 +0000393 /// Set to true when all global value body linking is complete (including
394 /// lazy linking). Used to prevent metadata linking from creating new
395 /// references.
396 bool DoneLinkingBodies = false;
397
398 bool HasError = false;
399
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000400 /// Flags to pass to value mapper invocations.
401 RemapFlags ValueMapperFlags = RF_MoveDistinctMDs | RF_IgnoreMissingLocals;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000402
Rafael Espindolacaabe222015-12-10 14:19:35 +0000403 /// Handles cloning of a global values from the source module into
404 /// the destination module, including setting the attributes and visibility.
405 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
406
407 /// Helper method for setting a message and returning an error code.
408 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000409 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000410 HasError = true;
411 return true;
412 }
413
414 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000415 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000416 }
417
418 /// Given a global in the source module, return the global in the
419 /// destination module that is being linked to, if any.
420 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
421 // If the source has no name it can't link. If it has local linkage,
422 // there is no name match-up going on.
423 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
424 return nullptr;
425
426 // Otherwise see if we have a match in the destination module's symtab.
427 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
428 if (!DGV)
429 return nullptr;
430
431 // If we found a global with the same name in the dest module, but it has
432 // internal linkage, we are really not doing any linkage here.
433 if (DGV->hasLocalLinkage())
434 return nullptr;
435
436 // Otherwise, we do in fact link to the destination global.
437 return DGV;
438 }
439
440 void computeTypeMapping();
441
442 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
443 const GlobalVariable *SrcGV);
444
Mehdi Amini33661072016-03-11 22:19:06 +0000445 /// Given the GlobaValue \p SGV in the source module, and the matching
446 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
447 /// into the destination module.
448 ///
449 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000450 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
451 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
452
453 bool linkModuleFlagsMetadata();
454
455 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
456 bool linkFunctionBody(Function &Dst, Function &Src);
457 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
458 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
459
460 /// Functions that take care of cloning a specific global value type
461 /// into the destination module.
462 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
463 Function *copyFunctionProto(const Function *SF);
464 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
465
466 void linkNamedMDNodes();
467
468public:
Rafael Espindola40358fb2016-02-16 18:50:12 +0000469 IRLinker(Module &DstM, IRMover::IdentifiedStructTypeSet &Set,
470 std::unique_ptr<Module> SrcM, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000471 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000472 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000473 GValMaterializer(*this), LValMaterializer(*this) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000474 for (GlobalValue *GV : ValuesToLink)
475 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000476 }
477
Rafael Espindolacaabe222015-12-10 14:19:35 +0000478 bool run();
479 Value *materializeDeclFor(Value *V, bool ForAlias);
480 void materializeInitFor(GlobalValue *New, GlobalValue *Old, bool ForAlias);
481};
482}
483
484/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
485/// table. This is good for all clients except for us. Go through the trouble
486/// to force this back.
487static void forceRenaming(GlobalValue *GV, StringRef Name) {
488 // If the global doesn't force its name or if it already has the right name,
489 // there is nothing for us to do.
490 if (GV->hasLocalLinkage() || GV->getName() == Name)
491 return;
492
493 Module *M = GV->getParent();
494
495 // If there is a conflict, rename the conflict.
496 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
497 GV->takeName(ConflictGV);
498 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
499 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
500 } else {
501 GV->setName(Name); // Force the name back
502 }
503}
504
505Value *GlobalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000506 return TheIRLinker.materializeDeclFor(V, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000507}
508
509void GlobalValueMaterializer::materializeInitFor(GlobalValue *New,
510 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000511 TheIRLinker.materializeInitFor(New, Old, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000512}
513
514Value *LocalValueMaterializer::materializeDeclFor(Value *V) {
Mehdi Amini33661072016-03-11 22:19:06 +0000515 return TheIRLinker.materializeDeclFor(V, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000516}
517
518void LocalValueMaterializer::materializeInitFor(GlobalValue *New,
519 GlobalValue *Old) {
Mehdi Amini33661072016-03-11 22:19:06 +0000520 TheIRLinker.materializeInitFor(New, Old, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000521}
522
523Value *IRLinker::materializeDeclFor(Value *V, bool ForAlias) {
524 auto *SGV = dyn_cast<GlobalValue>(V);
525 if (!SGV)
526 return nullptr;
527
528 return linkGlobalValueProto(SGV, ForAlias);
529}
530
531void IRLinker::materializeInitFor(GlobalValue *New, GlobalValue *Old,
532 bool ForAlias) {
533 // If we already created the body, just return.
534 if (auto *F = dyn_cast<Function>(New)) {
535 if (!F->isDeclaration())
536 return;
537 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
538 if (V->hasInitializer())
539 return;
540 } else {
541 auto *A = cast<GlobalAlias>(New);
542 if (A->getAliasee())
543 return;
544 }
545
546 if (ForAlias || shouldLink(New, *Old))
547 linkGlobalValueBody(*New, *Old);
548}
549
550/// Loop through the global variables in the src module and merge them into the
551/// dest module.
552GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
553 // No linking to be performed or linking from the source: simply create an
554 // identical version of the symbol over in the dest module... the
555 // initializer will be filled in later by LinkGlobalInits.
556 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000557 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000558 SGVar->isConstant(), GlobalValue::ExternalLinkage,
559 /*init*/ nullptr, SGVar->getName(),
560 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
561 SGVar->getType()->getAddressSpace());
562 NewDGV->setAlignment(SGVar->getAlignment());
563 return NewDGV;
564}
565
566/// Link the function in the source module into the destination module if
567/// needed, setting up mapping information.
568Function *IRLinker::copyFunctionProto(const Function *SF) {
569 // If there is no linkage to be performed or we are linking from the source,
570 // bring SF over.
571 return Function::Create(TypeMap.get(SF->getFunctionType()),
572 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
573}
574
575/// Set up prototypes for any aliases that come over from the source module.
576GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
577 // If there is no linkage to be performed or we're linking from the source,
578 // bring over SGA.
579 auto *Ty = TypeMap.get(SGA->getValueType());
580 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
581 GlobalValue::ExternalLinkage, SGA->getName(),
582 &DstM);
583}
584
585GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
586 bool ForDefinition) {
587 GlobalValue *NewGV;
588 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
589 NewGV = copyGlobalVariableProto(SGVar);
590 } else if (auto *SF = dyn_cast<Function>(SGV)) {
591 NewGV = copyFunctionProto(SF);
592 } else {
593 if (ForDefinition)
594 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
595 else
596 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000597 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000598 /*isConstant*/ false, GlobalValue::ExternalLinkage,
599 /*init*/ nullptr, SGV->getName(),
600 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
601 SGV->getType()->getAddressSpace());
602 }
603
604 if (ForDefinition)
605 NewGV->setLinkage(SGV->getLinkage());
606 else if (SGV->hasExternalWeakLinkage() || SGV->hasWeakLinkage() ||
607 SGV->hasLinkOnceLinkage())
608 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
609
610 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000611
612 // Remove these copied constants in case this stays a declaration, since
613 // they point to the source module. If the def is linked the values will
614 // be mapped in during linkFunctionBody.
615 if (auto *NewF = dyn_cast<Function>(NewGV)) {
616 NewF->setPersonalityFn(nullptr);
617 NewF->setPrefixData(nullptr);
618 NewF->setPrologueData(nullptr);
619 }
620
Rafael Espindolacaabe222015-12-10 14:19:35 +0000621 return NewGV;
622}
623
624/// Loop over all of the linked values to compute type mappings. For example,
625/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
626/// types 'Foo' but one got renamed when the module was loaded into the same
627/// LLVMContext.
628void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000629 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000630 GlobalValue *DGV = getLinkedToGlobal(&SGV);
631 if (!DGV)
632 continue;
633
634 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
635 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
636 continue;
637 }
638
639 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000640 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
641 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000642 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
643 }
644
Rafael Espindola40358fb2016-02-16 18:50:12 +0000645 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000646 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
647 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
648
Rafael Espindola40358fb2016-02-16 18:50:12 +0000649 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000650 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
651 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
652
653 // Incorporate types by name, scanning all the types in the source module.
654 // At this point, the destination module may have a type "%foo = { i32 }" for
655 // example. When the source module got loaded into the same LLVMContext, if
656 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000657 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000658 for (StructType *ST : Types) {
659 if (!ST->hasName())
660 continue;
661
662 // Check to see if there is a dot in the name followed by a digit.
663 size_t DotPos = ST->getName().rfind('.');
664 if (DotPos == 0 || DotPos == StringRef::npos ||
665 ST->getName().back() == '.' ||
666 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
667 continue;
668
669 // Check to see if the destination module has a struct with the prefix name.
670 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
671 if (!DST)
672 continue;
673
674 // Don't use it if this actually came from the source module. They're in
675 // the same LLVMContext after all. Also don't use it unless the type is
676 // actually used in the destination module. This can happen in situations
677 // like this:
678 //
679 // Module A Module B
680 // -------- --------
681 // %Z = type { %A } %B = type { %C.1 }
682 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
683 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
684 // %C = type { i8* } %B.3 = type { %C.1 }
685 //
686 // When we link Module B with Module A, the '%B' in Module B is
687 // used. However, that would then use '%C.1'. But when we process '%C.1',
688 // we prefer to take the '%C' version. So we are then left with both
689 // '%C.1' and '%C' being used for the same types. This leads to some
690 // variables using one type and some using the other.
691 if (TypeMap.DstStructTypesSet.hasType(DST))
692 TypeMap.addTypeMapping(DST, ST);
693 }
694
695 // Now that we have discovered all of the type equivalences, get a body for
696 // any 'opaque' types in the dest module that are now resolved.
697 TypeMap.linkDefinedTypeBodies();
698}
699
700static void getArrayElements(const Constant *C,
701 SmallVectorImpl<Constant *> &Dest) {
702 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
703
704 for (unsigned i = 0; i != NumElements; ++i)
705 Dest.push_back(C->getAggregateElement(i));
706}
707
708/// If there were any appending global variables, link them together now.
709/// Return true on error.
710Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
711 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000712 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000713 ->getElementType();
714
715 StringRef Name = SrcGV->getName();
716 bool IsNewStructor = false;
717 bool IsOldStructor = false;
718 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
719 if (cast<StructType>(EltTy)->getNumElements() == 3)
720 IsNewStructor = true;
721 else
722 IsOldStructor = true;
723 }
724
725 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
726 if (IsOldStructor) {
727 auto &ST = *cast<StructType>(EltTy);
728 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
729 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
730 }
731
732 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000733 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000734
735 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
736 emitError(
737 "Linking globals named '" + SrcGV->getName() +
738 "': can only link appending global with another appending global!");
739 return nullptr;
740 }
741
742 // Check to see that they two arrays agree on type.
743 if (EltTy != DstTy->getElementType()) {
744 emitError("Appending variables with different element types!");
745 return nullptr;
746 }
747 if (DstGV->isConstant() != SrcGV->isConstant()) {
748 emitError("Appending variables linked with different const'ness!");
749 return nullptr;
750 }
751
752 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
753 emitError(
754 "Appending variables with different alignment need to be linked!");
755 return nullptr;
756 }
757
758 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
759 emitError(
760 "Appending variables with different visibility need to be linked!");
761 return nullptr;
762 }
763
764 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
765 emitError(
766 "Appending variables with different unnamed_addr need to be linked!");
767 return nullptr;
768 }
769
770 if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
771 emitError(
772 "Appending variables with different section name need to be linked!");
773 return nullptr;
774 }
775 }
776
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000777 SmallVector<Constant *, 16> DstElements;
778 if (DstGV)
779 getArrayElements(DstGV->getInitializer(), DstElements);
780
Rafael Espindolacaabe222015-12-10 14:19:35 +0000781 SmallVector<Constant *, 16> SrcElements;
782 getArrayElements(SrcGV->getInitializer(), SrcElements);
783
784 if (IsNewStructor)
785 SrcElements.erase(
786 std::remove_if(SrcElements.begin(), SrcElements.end(),
787 [this](Constant *E) {
788 auto *Key = dyn_cast<GlobalValue>(
789 E->getAggregateElement(2)->stripPointerCasts());
790 if (!Key)
791 return false;
792 GlobalValue *DGV = getLinkedToGlobal(Key);
793 return !shouldLink(DGV, *Key);
794 }),
795 SrcElements.end());
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000796 uint64_t NewSize = DstElements.size() + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000797 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
798
799 // Create the new global variable.
800 GlobalVariable *NG = new GlobalVariable(
801 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
802 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
803 SrcGV->getType()->getAddressSpace());
804
805 NG->copyAttributesFrom(SrcGV);
806 forceRenaming(NG, SrcGV->getName());
807
808 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
809
810 // Stop recursion.
811 ValueMap[SrcGV] = Ret;
812
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000813 for (auto *V : SrcElements) {
814 Constant *NewV;
815 if (IsOldStructor) {
816 auto *S = cast<ConstantStruct>(V);
817 auto *E1 = MapValue(S->getOperand(0), ValueMap, ValueMapperFlags,
818 &TypeMap, &GValMaterializer);
819 auto *E2 = MapValue(S->getOperand(1), ValueMap, ValueMapperFlags,
820 &TypeMap, &GValMaterializer);
821 Value *Null = Constant::getNullValue(VoidPtrTy);
822 NewV =
823 ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
824 } else {
825 NewV =
826 MapValue(V, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
827 }
828 DstElements.push_back(NewV);
829 }
830
831 NG->setInitializer(ConstantArray::get(NewType, DstElements));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000832
833 // Replace any uses of the two global variables with uses of the new
834 // global.
835 if (DstGV) {
836 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
837 DstGV->eraseFromParent();
838 }
839
840 return Ret;
841}
842
Rafael Espindolacaabe222015-12-10 14:19:35 +0000843bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
844 if (ValuesToLink.count(&SGV))
845 return true;
846
847 if (SGV.hasLocalLinkage())
848 return true;
849
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000850 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000851 return false;
852
853 if (SGV.hasAvailableExternallyLinkage())
854 return true;
855
856 if (DoneLinkingBodies)
857 return false;
858
Mehdi Amini33661072016-03-11 22:19:06 +0000859
860 // Callback to the client to give a chance to lazily add the Global to the
861 // list of value to link.
862 bool LazilyAdded = false;
863 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
864 maybeAdd(&GV);
865 LazilyAdded = true;
866 });
867 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000868}
869
870Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
871 GlobalValue *DGV = getLinkedToGlobal(SGV);
872
873 bool ShouldLink = shouldLink(DGV, *SGV);
874
875 // just missing from map
876 if (ShouldLink) {
877 auto I = ValueMap.find(SGV);
878 if (I != ValueMap.end())
879 return cast<Constant>(I->second);
880
881 I = AliasValueMap.find(SGV);
882 if (I != AliasValueMap.end())
883 return cast<Constant>(I->second);
884 }
885
Mehdi Amini33661072016-03-11 22:19:06 +0000886 if (!ShouldLink && ForAlias)
887 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000888
889 // Handle the ultra special appending linkage case first.
890 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
891 if (SGV->hasAppendingLinkage())
892 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
893 cast<GlobalVariable>(SGV));
894
895 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000896 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000897 NewGV = DGV;
898 } else {
899 // If we are done linking global value bodies (i.e. we are performing
900 // metadata linking), don't link in the global value due to this
901 // reference, simply map it to null.
902 if (DoneLinkingBodies)
903 return nullptr;
904
905 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000906 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000907 forceRenaming(NewGV, SGV->getName());
908 }
909 if (ShouldLink || ForAlias) {
910 if (const Comdat *SC = SGV->getComdat()) {
911 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
912 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
913 DC->setSelectionKind(SC->getSelectionKind());
914 GO->setComdat(DC);
915 }
916 }
917 }
918
919 if (!ShouldLink && ForAlias)
920 NewGV->setLinkage(GlobalValue::InternalLinkage);
921
922 Constant *C = NewGV;
923 if (DGV)
924 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
925
926 if (DGV && NewGV != DGV) {
927 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
928 DGV->eraseFromParent();
929 }
930
931 return C;
932}
933
934/// Update the initializers in the Dest module now that all globals that may be
935/// referenced are in Dest.
936void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
937 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000938 Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap, ValueMapperFlags,
939 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000940}
941
942/// Copy the source function over into the dest function and fix up references
943/// to values. At this point we know that Dest is an external function, and
944/// that Src is not.
945bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
946 assert(Dst.isDeclaration() && !Src.isDeclaration());
947
948 // Materialize if needed.
949 if (std::error_code EC = Src.materialize())
950 return emitError(EC.message());
951
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000952 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000953 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000954 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000955 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000956 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000957 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000958 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000959
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000960 // Copy over the metadata attachments without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000961 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
962 Src.getAllMetadata(MDs);
963 for (const auto &I : MDs)
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000964 Dst.setMetadata(I.first, I.second);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000965
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000966 // Steal arguments and splice the body of Src into Dst.
967 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000968 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
969
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000970 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000971 RemapFunction(Dst, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000972 return false;
973}
974
975void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +0000976 Constant *Aliasee = Src.getAliasee();
977 Constant *Val = MapValue(Aliasee, AliasValueMap, ValueMapperFlags, &TypeMap,
978 &LValMaterializer);
979 Dst.setAliasee(Val);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000980}
981
982bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
983 if (auto *F = dyn_cast<Function>(&Src))
984 return linkFunctionBody(cast<Function>(Dst), *F);
985 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
986 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
987 return false;
988 }
989 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
990 return false;
991}
992
993/// Insert all of the named MDNodes in Src into the Dest module.
994void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000995 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
996 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000997 // Don't link module flags here. Do them separately.
998 if (&NMD == SrcModFlags)
999 continue;
1000 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1001 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001002 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +00001003 DestNMD->addOperand(MapMetadata(
1004 Op, ValueMap, ValueMapperFlags | RF_NullMapMissingGlobalValues,
1005 &TypeMap, &GValMaterializer));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001006 }
1007}
1008
1009/// Merge the linker flags in Src into the Dest module.
1010bool IRLinker::linkModuleFlagsMetadata() {
1011 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001012 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001013 if (!SrcModFlags)
1014 return false;
1015
1016 // If the destination module doesn't have module flags yet, then just copy
1017 // over the source module's flags.
1018 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1019 if (DstModFlags->getNumOperands() == 0) {
1020 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1021 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1022
1023 return false;
1024 }
1025
1026 // First build a map of the existing module flags and requirements.
1027 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1028 SmallSetVector<MDNode *, 16> Requirements;
1029 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1030 MDNode *Op = DstModFlags->getOperand(I);
1031 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1032 MDString *ID = cast<MDString>(Op->getOperand(1));
1033
1034 if (Behavior->getZExtValue() == Module::Require) {
1035 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1036 } else {
1037 Flags[ID] = std::make_pair(Op, I);
1038 }
1039 }
1040
1041 // Merge in the flags from the source module, and also collect its set of
1042 // requirements.
1043 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1044 MDNode *SrcOp = SrcModFlags->getOperand(I);
1045 ConstantInt *SrcBehavior =
1046 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1047 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1048 MDNode *DstOp;
1049 unsigned DstIndex;
1050 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1051 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1052
1053 // If this is a requirement, add it and continue.
1054 if (SrcBehaviorValue == Module::Require) {
1055 // If the destination module does not already have this requirement, add
1056 // it.
1057 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1058 DstModFlags->addOperand(SrcOp);
1059 }
1060 continue;
1061 }
1062
1063 // If there is no existing flag with this ID, just add it.
1064 if (!DstOp) {
1065 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1066 DstModFlags->addOperand(SrcOp);
1067 continue;
1068 }
1069
1070 // Otherwise, perform a merge.
1071 ConstantInt *DstBehavior =
1072 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1073 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1074
1075 // If either flag has override behavior, handle it first.
1076 if (DstBehaviorValue == Module::Override) {
1077 // Diagnose inconsistent flags which both have override behavior.
1078 if (SrcBehaviorValue == Module::Override &&
1079 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1080 emitError("linking module flags '" + ID->getString() +
1081 "': IDs have conflicting override values");
1082 }
1083 continue;
1084 } else if (SrcBehaviorValue == Module::Override) {
1085 // Update the destination flag to that of the source.
1086 DstModFlags->setOperand(DstIndex, SrcOp);
1087 Flags[ID].first = SrcOp;
1088 continue;
1089 }
1090
1091 // Diagnose inconsistent merge behavior types.
1092 if (SrcBehaviorValue != DstBehaviorValue) {
1093 emitError("linking module flags '" + ID->getString() +
1094 "': IDs have conflicting behaviors");
1095 continue;
1096 }
1097
1098 auto replaceDstValue = [&](MDNode *New) {
1099 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1100 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1101 DstModFlags->setOperand(DstIndex, Flag);
1102 Flags[ID].first = Flag;
1103 };
1104
1105 // Perform the merge for standard behavior types.
1106 switch (SrcBehaviorValue) {
1107 case Module::Require:
1108 case Module::Override:
1109 llvm_unreachable("not possible");
1110 case Module::Error: {
1111 // Emit an error if the values differ.
1112 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1113 emitError("linking module flags '" + ID->getString() +
1114 "': IDs have conflicting values");
1115 }
1116 continue;
1117 }
1118 case Module::Warning: {
1119 // Emit a warning if the values differ.
1120 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1121 emitWarning("linking module flags '" + ID->getString() +
1122 "': IDs have conflicting values");
1123 }
1124 continue;
1125 }
1126 case Module::Append: {
1127 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1128 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1129 SmallVector<Metadata *, 8> MDs;
1130 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1131 MDs.append(DstValue->op_begin(), DstValue->op_end());
1132 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1133
1134 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1135 break;
1136 }
1137 case Module::AppendUnique: {
1138 SmallSetVector<Metadata *, 16> Elts;
1139 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1140 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1141 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1142 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1143
1144 replaceDstValue(MDNode::get(DstM.getContext(),
1145 makeArrayRef(Elts.begin(), Elts.end())));
1146 break;
1147 }
1148 }
1149 }
1150
1151 // Check all of the requirements.
1152 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1153 MDNode *Requirement = Requirements[I];
1154 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1155 Metadata *ReqValue = Requirement->getOperand(1);
1156
1157 MDNode *Op = Flags[Flag].first;
1158 if (!Op || Op->getOperand(2) != ReqValue) {
1159 emitError("linking module flags '" + Flag->getString() +
1160 "': does not have the required value");
1161 continue;
1162 }
1163 }
1164
1165 return HasError;
1166}
1167
1168// This function returns true if the triples match.
1169static bool triplesMatch(const Triple &T0, const Triple &T1) {
1170 // If vendor is apple, ignore the version number.
1171 if (T0.getVendor() == Triple::Apple)
1172 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1173 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1174
1175 return T0 == T1;
1176}
1177
1178// This function returns the merged triple.
1179static std::string mergeTriples(const Triple &SrcTriple,
1180 const Triple &DstTriple) {
1181 // If vendor is apple, pick the triple with the larger version number.
1182 if (SrcTriple.getVendor() == Triple::Apple)
1183 if (DstTriple.isOSVersionLT(SrcTriple))
1184 return SrcTriple.str();
1185
1186 return DstTriple.str();
1187}
1188
1189bool IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001190 // Ensure metadata materialized before value mapping.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001191 if (SrcM->getMaterializer() && SrcM->getMaterializer()->materializeMetadata())
Teresa Johnson0556e222016-03-10 18:47:03 +00001192 return true;
1193
Rafael Espindolacaabe222015-12-10 14:19:35 +00001194 // Inherit the target data from the source module if the destination module
1195 // doesn't have one already.
1196 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001197 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001198
Rafael Espindola40358fb2016-02-16 18:50:12 +00001199 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001200 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001201 SrcM->getModuleIdentifier() + "' is '" +
1202 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001203 DstM.getModuleIdentifier() + "' is '" +
1204 DstM.getDataLayoutStr() + "'\n");
1205 }
1206
1207 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001208 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1209 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001210
Rafael Espindola40358fb2016-02-16 18:50:12 +00001211 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001212
Rafael Espindola40358fb2016-02-16 18:50:12 +00001213 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001214 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001215 SrcM->getModuleIdentifier() + "' is '" +
1216 SrcM->getTargetTriple() + "' whereas '" +
1217 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1218 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001219
1220 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1221
1222 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001223 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001224 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001225 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001226 else
1227 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001228 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001229 }
1230
1231 // Loop over all of the linked values to compute type mappings.
1232 computeTypeMapping();
1233
1234 std::reverse(Worklist.begin(), Worklist.end());
1235 while (!Worklist.empty()) {
1236 GlobalValue *GV = Worklist.back();
1237 Worklist.pop_back();
1238
1239 // Already mapped.
1240 if (ValueMap.find(GV) != ValueMap.end() ||
1241 AliasValueMap.find(GV) != AliasValueMap.end())
1242 continue;
1243
1244 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith6fe1ff22016-04-16 02:05:33 +00001245 MapValue(GV, ValueMap, ValueMapperFlags, &TypeMap, &GValMaterializer);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001246 if (HasError)
1247 return true;
1248 }
1249
1250 // Note that we are done linking global value bodies. This prevents
1251 // metadata linking from creating new references.
1252 DoneLinkingBodies = true;
1253
1254 // Remap all of the named MDNodes in Src into the DstM module. We do this
1255 // after linking GlobalValues so that MDNodes that reference GlobalValues
1256 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001257 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001258
Teresa Johnsonb703c772016-03-29 18:24:19 +00001259 // Merge the module flags into the DstM module.
1260 if (linkModuleFlagsMetadata())
1261 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001262
1263 return false;
1264}
1265
1266IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1267 : ETypes(E), IsPacked(P) {}
1268
1269IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1270 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1271
1272bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1273 if (IsPacked != That.IsPacked)
1274 return false;
1275 if (ETypes != That.ETypes)
1276 return false;
1277 return true;
1278}
1279
1280bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1281 return !this->operator==(That);
1282}
1283
1284StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1285 return DenseMapInfo<StructType *>::getEmptyKey();
1286}
1287
1288StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1289 return DenseMapInfo<StructType *>::getTombstoneKey();
1290}
1291
1292unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1293 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1294 Key.IsPacked);
1295}
1296
1297unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1298 return getHashValue(KeyTy(ST));
1299}
1300
1301bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1302 const StructType *RHS) {
1303 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1304 return false;
1305 return LHS == KeyTy(RHS);
1306}
1307
1308bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1309 const StructType *RHS) {
1310 if (RHS == getEmptyKey())
1311 return LHS == getEmptyKey();
1312
1313 if (RHS == getTombstoneKey())
1314 return LHS == getTombstoneKey();
1315
1316 return KeyTy(LHS) == KeyTy(RHS);
1317}
1318
1319void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1320 assert(!Ty->isOpaque());
1321 NonOpaqueStructTypes.insert(Ty);
1322}
1323
1324void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1325 assert(!Ty->isOpaque());
1326 NonOpaqueStructTypes.insert(Ty);
1327 bool Removed = OpaqueStructTypes.erase(Ty);
1328 (void)Removed;
1329 assert(Removed);
1330}
1331
1332void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1333 assert(Ty->isOpaque());
1334 OpaqueStructTypes.insert(Ty);
1335}
1336
1337StructType *
1338IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1339 bool IsPacked) {
1340 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1341 auto I = NonOpaqueStructTypes.find_as(Key);
1342 if (I == NonOpaqueStructTypes.end())
1343 return nullptr;
1344 return *I;
1345}
1346
1347bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1348 if (Ty->isOpaque())
1349 return OpaqueStructTypes.count(Ty);
1350 auto I = NonOpaqueStructTypes.find(Ty);
1351 if (I == NonOpaqueStructTypes.end())
1352 return false;
1353 return *I == Ty;
1354}
1355
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001356IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001357 TypeFinder StructTypes;
1358 StructTypes.run(M, true);
1359 for (StructType *Ty : StructTypes) {
1360 if (Ty->isOpaque())
1361 IdentifiedStructTypes.addOpaque(Ty);
1362 else
1363 IdentifiedStructTypes.addNonOpaque(Ty);
1364 }
1365}
1366
1367bool IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001368 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001369 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Rafael Espindola40358fb2016-02-16 18:50:12 +00001370 IRLinker TheIRLinker(Composite, IdentifiedStructTypes, std::move(Src),
Teresa Johnsonb703c772016-03-29 18:24:19 +00001371 ValuesToLink, AddLazyFor);
Teresa Johnsonbef54362015-12-18 19:28:59 +00001372 bool RetCode = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001373 Composite.dropTriviallyDeadConstantArrays();
1374 return RetCode;
1375}