blob: 97242b7037d027ca19015dafdaca110122054548 [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;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000353};
354
355class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000356 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000357
358public:
Mehdi Amini33661072016-03-11 22:19:06 +0000359 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Rafael Espindolacaabe222015-12-10 14:19:35 +0000360 Value *materializeDeclFor(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000361};
362
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000363/// Type of the Metadata map in \a ValueToValueMapTy.
364typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
365
Rafael Espindolacaabe222015-12-10 14:19:35 +0000366/// This is responsible for keeping track of the state used for moving data
367/// from SrcM to DstM.
368class IRLinker {
369 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000370 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000371
Mehdi Amini33661072016-03-11 22:19:06 +0000372 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000373 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
374
375 TypeMapTy TypeMap;
376 GlobalValueMaterializer GValMaterializer;
377 LocalValueMaterializer LValMaterializer;
378
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000379 /// A metadata map that's shared between IRLinker instances.
380 MDMapT &SharedMDs;
381
Rafael Espindolacaabe222015-12-10 14:19:35 +0000382 /// Mapping of values from what they used to be in Src, to what they are now
383 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
384 /// due to the use of Value handles which the Linker doesn't actually need,
385 /// but this allows us to reuse the ValueMapper code.
386 ValueToValueMapTy ValueMap;
387 ValueToValueMapTy AliasValueMap;
388
389 DenseSet<GlobalValue *> ValuesToLink;
390 std::vector<GlobalValue *> Worklist;
391
392 void maybeAdd(GlobalValue *GV) {
393 if (ValuesToLink.insert(GV).second)
394 Worklist.push_back(GV);
395 }
396
Rafael Espindolacaabe222015-12-10 14:19:35 +0000397 /// Set to true when all global value body linking is complete (including
398 /// lazy linking). Used to prevent metadata linking from creating new
399 /// references.
400 bool DoneLinkingBodies = false;
401
402 bool HasError = false;
403
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000404 /// Entry point for mapping values and alternate context for mapping aliases.
405 ValueMapper Mapper;
406 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000407
Rafael Espindolacaabe222015-12-10 14:19:35 +0000408 /// Handles cloning of a global values from the source module into
409 /// the destination module, including setting the attributes and visibility.
410 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
411
412 /// Helper method for setting a message and returning an error code.
413 bool emitError(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000414 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Error, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000415 HasError = true;
416 return true;
417 }
418
419 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000420 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000421 }
422
423 /// Given a global in the source module, return the global in the
424 /// destination module that is being linked to, if any.
425 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
426 // If the source has no name it can't link. If it has local linkage,
427 // there is no name match-up going on.
428 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
429 return nullptr;
430
431 // Otherwise see if we have a match in the destination module's symtab.
432 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
433 if (!DGV)
434 return nullptr;
435
436 // If we found a global with the same name in the dest module, but it has
437 // internal linkage, we are really not doing any linkage here.
438 if (DGV->hasLocalLinkage())
439 return nullptr;
440
441 // Otherwise, we do in fact link to the destination global.
442 return DGV;
443 }
444
445 void computeTypeMapping();
446
447 Constant *linkAppendingVarProto(GlobalVariable *DstGV,
448 const GlobalVariable *SrcGV);
449
Mehdi Amini33661072016-03-11 22:19:06 +0000450 /// Given the GlobaValue \p SGV in the source module, and the matching
451 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
452 /// into the destination module.
453 ///
454 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000455 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
456 Constant *linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
457
458 bool linkModuleFlagsMetadata();
459
460 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
461 bool linkFunctionBody(Function &Dst, Function &Src);
462 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
463 bool linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
464
465 /// Functions that take care of cloning a specific global value type
466 /// into the destination module.
467 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
468 Function *copyFunctionProto(const Function *SF);
469 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
470
471 void linkNamedMDNodes();
472
473public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000474 IRLinker(Module &DstM, MDMapT &SharedMDs,
475 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
476 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000477 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Rafael Espindola40358fb2016-02-16 18:50:12 +0000478 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(AddLazyFor), TypeMap(Set),
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000479 GValMaterializer(*this), LValMaterializer(*this), SharedMDs(SharedMDs),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000480 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
481 &GValMaterializer),
482 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
483 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000484 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000485 for (GlobalValue *GV : ValuesToLink)
486 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000487 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000488 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000489
Rafael Espindolacaabe222015-12-10 14:19:35 +0000490 bool run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000491 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000492};
493}
494
495/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
496/// table. This is good for all clients except for us. Go through the trouble
497/// to force this back.
498static void forceRenaming(GlobalValue *GV, StringRef Name) {
499 // If the global doesn't force its name or if it already has the right name,
500 // there is nothing for us to do.
501 if (GV->hasLocalLinkage() || GV->getName() == Name)
502 return;
503
504 Module *M = GV->getParent();
505
506 // If there is a conflict, rename the conflict.
507 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
508 GV->takeName(ConflictGV);
509 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
510 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
511 } else {
512 GV->setName(Name); // Force the name back
513 }
514}
515
Mehdi Amini53a66722016-05-25 21:01:51 +0000516Value *GlobalValueMaterializer::materializeDeclFor(Value *SGV) {
517 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000518}
519
Mehdi Amini53a66722016-05-25 21:01:51 +0000520Value *LocalValueMaterializer::materializeDeclFor(Value *SGV) {
521 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000522}
523
Mehdi Amini53a66722016-05-25 21:01:51 +0000524Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000525 auto *SGV = dyn_cast<GlobalValue>(V);
526 if (!SGV)
527 return nullptr;
528
Mehdi Amini53a66722016-05-25 21:01:51 +0000529 Constant *NewProto = linkGlobalValueProto(SGV, ForAlias);
530 if (!NewProto)
531 return NewProto;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000532
Mehdi Amini53a66722016-05-25 21:01:51 +0000533 GlobalValue *New = dyn_cast<GlobalValue>(NewProto);
534 if (!New)
535 return NewProto;
536
Rafael Espindolacaabe222015-12-10 14:19:35 +0000537 // If we already created the body, just return.
538 if (auto *F = dyn_cast<Function>(New)) {
539 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000540 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000541 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000542 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000543 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000544 } else {
545 auto *A = cast<GlobalAlias>(New);
546 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000547 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000548 }
549
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000550 // When linking a global for an alias, it will always be linked. However we
551 // need to check if it was not already scheduled to satify a reference from a
552 // regular global value initializer. We know if it has been schedule if the
553 // "New" GlobalValue that is mapped here for the alias is the same as the one
554 // already mapped. If there is an entry in the ValueMap but the value is
555 // different, it means that the value already had a definition in the
556 // destination module (linkonce for instance), but we need a new definition
557 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000558 if (ForAlias && ValueMap.lookup(SGV) == New)
559 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000560
Mehdi Amini53a66722016-05-25 21:01:51 +0000561 if (ForAlias || shouldLink(New, *SGV))
562 linkGlobalValueBody(*New, *SGV);
563
564 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000565}
566
567/// Loop through the global variables in the src module and merge them into the
568/// dest module.
569GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
570 // No linking to be performed or linking from the source: simply create an
571 // identical version of the symbol over in the dest module... the
572 // initializer will be filled in later by LinkGlobalInits.
573 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000574 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000575 SGVar->isConstant(), GlobalValue::ExternalLinkage,
576 /*init*/ nullptr, SGVar->getName(),
577 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
578 SGVar->getType()->getAddressSpace());
579 NewDGV->setAlignment(SGVar->getAlignment());
580 return NewDGV;
581}
582
583/// Link the function in the source module into the destination module if
584/// needed, setting up mapping information.
585Function *IRLinker::copyFunctionProto(const Function *SF) {
586 // If there is no linkage to be performed or we are linking from the source,
587 // bring SF over.
588 return Function::Create(TypeMap.get(SF->getFunctionType()),
589 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
590}
591
592/// Set up prototypes for any aliases that come over from the source module.
593GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
594 // If there is no linkage to be performed or we're linking from the source,
595 // bring over SGA.
596 auto *Ty = TypeMap.get(SGA->getValueType());
597 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
598 GlobalValue::ExternalLinkage, SGA->getName(),
599 &DstM);
600}
601
602GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
603 bool ForDefinition) {
604 GlobalValue *NewGV;
605 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
606 NewGV = copyGlobalVariableProto(SGVar);
607 } else if (auto *SF = dyn_cast<Function>(SGV)) {
608 NewGV = copyFunctionProto(SF);
609 } else {
610 if (ForDefinition)
611 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
612 else
613 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000614 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000615 /*isConstant*/ false, GlobalValue::ExternalLinkage,
616 /*init*/ nullptr, SGV->getName(),
617 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
618 SGV->getType()->getAddressSpace());
619 }
620
621 if (ForDefinition)
622 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000623 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000624 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
625
626 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000627
Reid Klecknerc0a03632016-05-25 18:36:22 +0000628 // Don't copy the comdat, it's from the original module. We'll handle it
629 // later.
630 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV))
631 NewGO->setComdat(nullptr);
632
Teresa Johnson5fe40052016-01-12 00:24:24 +0000633 // Remove these copied constants in case this stays a declaration, since
634 // they point to the source module. If the def is linked the values will
635 // be mapped in during linkFunctionBody.
636 if (auto *NewF = dyn_cast<Function>(NewGV)) {
637 NewF->setPersonalityFn(nullptr);
638 NewF->setPrefixData(nullptr);
639 NewF->setPrologueData(nullptr);
640 }
641
Rafael Espindolacaabe222015-12-10 14:19:35 +0000642 return NewGV;
643}
644
645/// Loop over all of the linked values to compute type mappings. For example,
646/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
647/// types 'Foo' but one got renamed when the module was loaded into the same
648/// LLVMContext.
649void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000650 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000651 GlobalValue *DGV = getLinkedToGlobal(&SGV);
652 if (!DGV)
653 continue;
654
655 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
656 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
657 continue;
658 }
659
660 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000661 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
662 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000663 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
664 }
665
Rafael Espindola40358fb2016-02-16 18:50:12 +0000666 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000667 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
668 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
669
Rafael Espindola40358fb2016-02-16 18:50:12 +0000670 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000671 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
672 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
673
674 // Incorporate types by name, scanning all the types in the source module.
675 // At this point, the destination module may have a type "%foo = { i32 }" for
676 // example. When the source module got loaded into the same LLVMContext, if
677 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000678 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000679 for (StructType *ST : Types) {
680 if (!ST->hasName())
681 continue;
682
683 // Check to see if there is a dot in the name followed by a digit.
684 size_t DotPos = ST->getName().rfind('.');
685 if (DotPos == 0 || DotPos == StringRef::npos ||
686 ST->getName().back() == '.' ||
687 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
688 continue;
689
690 // Check to see if the destination module has a struct with the prefix name.
691 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
692 if (!DST)
693 continue;
694
695 // Don't use it if this actually came from the source module. They're in
696 // the same LLVMContext after all. Also don't use it unless the type is
697 // actually used in the destination module. This can happen in situations
698 // like this:
699 //
700 // Module A Module B
701 // -------- --------
702 // %Z = type { %A } %B = type { %C.1 }
703 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
704 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
705 // %C = type { i8* } %B.3 = type { %C.1 }
706 //
707 // When we link Module B with Module A, the '%B' in Module B is
708 // used. However, that would then use '%C.1'. But when we process '%C.1',
709 // we prefer to take the '%C' version. So we are then left with both
710 // '%C.1' and '%C' being used for the same types. This leads to some
711 // variables using one type and some using the other.
712 if (TypeMap.DstStructTypesSet.hasType(DST))
713 TypeMap.addTypeMapping(DST, ST);
714 }
715
716 // Now that we have discovered all of the type equivalences, get a body for
717 // any 'opaque' types in the dest module that are now resolved.
718 TypeMap.linkDefinedTypeBodies();
719}
720
721static void getArrayElements(const Constant *C,
722 SmallVectorImpl<Constant *> &Dest) {
723 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
724
725 for (unsigned i = 0; i != NumElements; ++i)
726 Dest.push_back(C->getAggregateElement(i));
727}
728
729/// If there were any appending global variables, link them together now.
730/// Return true on error.
731Constant *IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
732 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000733 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000734 ->getElementType();
735
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000736 // FIXME: This upgrade is done during linking to support the C API. Once the
737 // old form is deprecated, we should move this upgrade to
738 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
739 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000740 StringRef Name = SrcGV->getName();
741 bool IsNewStructor = false;
742 bool IsOldStructor = false;
743 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
744 if (cast<StructType>(EltTy)->getNumElements() == 3)
745 IsNewStructor = true;
746 else
747 IsOldStructor = true;
748 }
749
750 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
751 if (IsOldStructor) {
752 auto &ST = *cast<StructType>(EltTy);
753 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
754 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
755 }
756
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000757 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000758 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000759 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000760 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000761
762 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
763 emitError(
764 "Linking globals named '" + SrcGV->getName() +
765 "': can only link appending global with another appending global!");
766 return nullptr;
767 }
768
769 // Check to see that they two arrays agree on type.
770 if (EltTy != DstTy->getElementType()) {
771 emitError("Appending variables with different element types!");
772 return nullptr;
773 }
774 if (DstGV->isConstant() != SrcGV->isConstant()) {
775 emitError("Appending variables linked with different const'ness!");
776 return nullptr;
777 }
778
779 if (DstGV->getAlignment() != SrcGV->getAlignment()) {
780 emitError(
781 "Appending variables with different alignment need to be linked!");
782 return nullptr;
783 }
784
785 if (DstGV->getVisibility() != SrcGV->getVisibility()) {
786 emitError(
787 "Appending variables with different visibility need to be linked!");
788 return nullptr;
789 }
790
791 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
792 emitError(
793 "Appending variables with different unnamed_addr need to be linked!");
794 return nullptr;
795 }
796
Rafael Espindola83658d62016-05-11 18:21:59 +0000797 if (DstGV->getSection() != SrcGV->getSection()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000798 emitError(
799 "Appending variables with different section name need to be linked!");
800 return nullptr;
801 }
802 }
803
Rafael Espindolacaabe222015-12-10 14:19:35 +0000804 SmallVector<Constant *, 16> SrcElements;
805 getArrayElements(SrcGV->getInitializer(), SrcElements);
806
807 if (IsNewStructor)
808 SrcElements.erase(
809 std::remove_if(SrcElements.begin(), SrcElements.end(),
810 [this](Constant *E) {
811 auto *Key = dyn_cast<GlobalValue>(
812 E->getAggregateElement(2)->stripPointerCasts());
813 if (!Key)
814 return false;
815 GlobalValue *DGV = getLinkedToGlobal(Key);
816 return !shouldLink(DGV, *Key);
817 }),
818 SrcElements.end());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000819 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000820 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
821
822 // Create the new global variable.
823 GlobalVariable *NG = new GlobalVariable(
824 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
825 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
826 SrcGV->getType()->getAddressSpace());
827
828 NG->copyAttributesFrom(SrcGV);
829 forceRenaming(NG, SrcGV->getName());
830
831 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
832
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000833 Mapper.scheduleMapAppendingVariable(*NG,
834 DstGV ? DstGV->getInitializer() : nullptr,
835 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000836
837 // Replace any uses of the two global variables with uses of the new
838 // global.
839 if (DstGV) {
840 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
841 DstGV->eraseFromParent();
842 }
843
844 return Ret;
845}
846
Rafael Espindolacaabe222015-12-10 14:19:35 +0000847bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
848 if (ValuesToLink.count(&SGV))
849 return true;
850
851 if (SGV.hasLocalLinkage())
852 return true;
853
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000854 if (DGV && !DGV->isDeclarationForLinker())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000855 return false;
856
857 if (SGV.hasAvailableExternallyLinkage())
858 return true;
859
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000860 if (SGV.isDeclaration())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000861 return false;
862
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000863 if (DoneLinkingBodies)
864 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000865
866 // Callback to the client to give a chance to lazily add the Global to the
867 // list of value to link.
868 bool LazilyAdded = false;
869 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
870 maybeAdd(&GV);
871 LazilyAdded = true;
872 });
873 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000874}
875
876Constant *IRLinker::linkGlobalValueProto(GlobalValue *SGV, bool ForAlias) {
877 GlobalValue *DGV = getLinkedToGlobal(SGV);
878
879 bool ShouldLink = shouldLink(DGV, *SGV);
880
881 // just missing from map
882 if (ShouldLink) {
883 auto I = ValueMap.find(SGV);
884 if (I != ValueMap.end())
885 return cast<Constant>(I->second);
886
887 I = AliasValueMap.find(SGV);
888 if (I != AliasValueMap.end())
889 return cast<Constant>(I->second);
890 }
891
Mehdi Amini33661072016-03-11 22:19:06 +0000892 if (!ShouldLink && ForAlias)
893 DGV = nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000894
895 // Handle the ultra special appending linkage case first.
896 assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
897 if (SGV->hasAppendingLinkage())
898 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
899 cast<GlobalVariable>(SGV));
900
901 GlobalValue *NewGV;
Rafael Espindola55a7ae52016-01-20 22:38:23 +0000902 if (DGV && !ShouldLink) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000903 NewGV = DGV;
904 } else {
905 // If we are done linking global value bodies (i.e. we are performing
906 // metadata linking), don't link in the global value due to this
907 // reference, simply map it to null.
908 if (DoneLinkingBodies)
909 return nullptr;
910
911 NewGV = copyGlobalValueProto(SGV, ShouldLink);
Evgeniy Stepanov9fb70f52016-01-20 22:05:50 +0000912 if (ShouldLink || !ForAlias)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000913 forceRenaming(NewGV, SGV->getName());
914 }
915 if (ShouldLink || ForAlias) {
916 if (const Comdat *SC = SGV->getComdat()) {
917 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
918 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
919 DC->setSelectionKind(SC->getSelectionKind());
920 GO->setComdat(DC);
921 }
922 }
923 }
924
925 if (!ShouldLink && ForAlias)
926 NewGV->setLinkage(GlobalValue::InternalLinkage);
927
928 Constant *C = NewGV;
929 if (DGV)
930 C = ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
931
932 if (DGV && NewGV != DGV) {
933 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
934 DGV->eraseFromParent();
935 }
936
937 return C;
938}
939
940/// Update the initializers in the Dest module now that all globals that may be
941/// referenced are in Dest.
942void IRLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
943 // Figure out what the initializer looks like in the dest module.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000944 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000945}
946
947/// Copy the source function over into the dest function and fix up references
948/// to values. At this point we know that Dest is an external function, and
949/// that Src is not.
950bool IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
951 assert(Dst.isDeclaration() && !Src.isDeclaration());
952
953 // Materialize if needed.
954 if (std::error_code EC = Src.materialize())
955 return emitError(EC.message());
956
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000957 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000958 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000959 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000960 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000961 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000962 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000963 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000964
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000965 // Copy over the metadata attachments without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000966 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
967 Src.getAllMetadata(MDs);
968 for (const auto &I : MDs)
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000969 Dst.setMetadata(I.first, I.second);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000970
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000971 // Steal arguments and splice the body of Src into Dst.
972 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000973 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
974
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000975 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000976 Mapper.scheduleRemapFunction(Dst);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000977 return false;
978}
979
980void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000981 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000982}
983
984bool IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
985 if (auto *F = dyn_cast<Function>(&Src))
986 return linkFunctionBody(cast<Function>(Dst), *F);
987 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
988 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
989 return false;
990 }
991 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
992 return false;
993}
994
995/// Insert all of the named MDNodes in Src into the Dest module.
996void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000997 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
998 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000999 // Don't link module flags here. Do them separately.
1000 if (&NMD == SrcModFlags)
1001 continue;
1002 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1003 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +00001004 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001005 DestNMD->addOperand(Mapper.mapMDNode(*Op));
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 Smith39423b02016-04-16 02:29:55 +00001245 Mapper.mapValue(*GV);
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;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001253 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001254
1255 // Remap all of the named MDNodes in Src into the DstM module. We do this
1256 // after linking GlobalValues so that MDNodes that reference GlobalValues
1257 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001258 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001259
Teresa Johnsonb703c772016-03-29 18:24:19 +00001260 // Merge the module flags into the DstM module.
1261 if (linkModuleFlagsMetadata())
1262 return true;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001263
1264 return false;
1265}
1266
1267IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1268 : ETypes(E), IsPacked(P) {}
1269
1270IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1271 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1272
1273bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
1274 if (IsPacked != That.IsPacked)
1275 return false;
1276 if (ETypes != That.ETypes)
1277 return false;
1278 return true;
1279}
1280
1281bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1282 return !this->operator==(That);
1283}
1284
1285StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1286 return DenseMapInfo<StructType *>::getEmptyKey();
1287}
1288
1289StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1290 return DenseMapInfo<StructType *>::getTombstoneKey();
1291}
1292
1293unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1294 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1295 Key.IsPacked);
1296}
1297
1298unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1299 return getHashValue(KeyTy(ST));
1300}
1301
1302bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1303 const StructType *RHS) {
1304 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1305 return false;
1306 return LHS == KeyTy(RHS);
1307}
1308
1309bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1310 const StructType *RHS) {
1311 if (RHS == getEmptyKey())
1312 return LHS == getEmptyKey();
1313
1314 if (RHS == getTombstoneKey())
1315 return LHS == getTombstoneKey();
1316
1317 return KeyTy(LHS) == KeyTy(RHS);
1318}
1319
1320void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1321 assert(!Ty->isOpaque());
1322 NonOpaqueStructTypes.insert(Ty);
1323}
1324
1325void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1326 assert(!Ty->isOpaque());
1327 NonOpaqueStructTypes.insert(Ty);
1328 bool Removed = OpaqueStructTypes.erase(Ty);
1329 (void)Removed;
1330 assert(Removed);
1331}
1332
1333void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1334 assert(Ty->isOpaque());
1335 OpaqueStructTypes.insert(Ty);
1336}
1337
1338StructType *
1339IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1340 bool IsPacked) {
1341 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1342 auto I = NonOpaqueStructTypes.find_as(Key);
1343 if (I == NonOpaqueStructTypes.end())
1344 return nullptr;
1345 return *I;
1346}
1347
1348bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1349 if (Ty->isOpaque())
1350 return OpaqueStructTypes.count(Ty);
1351 auto I = NonOpaqueStructTypes.find(Ty);
1352 if (I == NonOpaqueStructTypes.end())
1353 return false;
1354 return *I == Ty;
1355}
1356
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001357IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001358 TypeFinder StructTypes;
1359 StructTypes.run(M, true);
1360 for (StructType *Ty : StructTypes) {
1361 if (Ty->isOpaque())
1362 IdentifiedStructTypes.addOpaque(Ty);
1363 else
1364 IdentifiedStructTypes.addNonOpaque(Ty);
1365 }
1366}
1367
1368bool IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001369 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001370 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001371 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1372 std::move(Src), ValuesToLink, AddLazyFor);
Teresa Johnsonbef54362015-12-18 19:28:59 +00001373 bool RetCode = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001374 Composite.dropTriviallyDeadConstantArrays();
1375 return RetCode;
1376}