blob: 9c122f9af055a1ad1ebc4053da1449bbcbd0390c [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"
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +000020#include "llvm/Support/Error.h"
Rafael Espindolacaabe222015-12-10 14:19:35 +000021#include "llvm/Transforms/Utils/Cloning.h"
Benjamin Kramer82de7d32016-05-27 14:27:24 +000022#include <utility>
Rafael Espindolacaabe222015-12-10 14:19:35 +000023using namespace llvm;
24
25//===----------------------------------------------------------------------===//
26// TypeMap implementation.
27//===----------------------------------------------------------------------===//
28
29namespace {
30class TypeMapTy : public ValueMapTypeRemapper {
31 /// This is a mapping from a source type to a destination type to use.
32 DenseMap<Type *, Type *> MappedTypes;
33
34 /// When checking to see if two subgraphs are isomorphic, we speculatively
35 /// add types to MappedTypes, but keep track of them here in case we need to
36 /// roll back.
37 SmallVector<Type *, 16> SpeculativeTypes;
38
39 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
40
41 /// This is a list of non-opaque structs in the source module that are mapped
42 /// to an opaque struct in the destination module.
43 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
44
45 /// This is the set of opaque types in the destination modules who are
46 /// getting a body from the source module.
47 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
48
49public:
50 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
51 : DstStructTypesSet(DstStructTypesSet) {}
52
53 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
54 /// Indicate that the specified type in the destination module is conceptually
55 /// equivalent to the specified type in the source module.
56 void addTypeMapping(Type *DstTy, Type *SrcTy);
57
58 /// Produce a body for an opaque type in the dest module from a type
59 /// definition in the source module.
60 void linkDefinedTypeBodies();
61
62 /// Return the mapped type to use for the specified input type from the
63 /// source module.
64 Type *get(Type *SrcTy);
65 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
66
67 void finishType(StructType *DTy, StructType *STy, ArrayRef<Type *> ETypes);
68
69 FunctionType *get(FunctionType *T) {
70 return cast<FunctionType>(get((Type *)T));
71 }
72
73private:
74 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
75
76 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
77};
78}
79
80void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
81 assert(SpeculativeTypes.empty());
82 assert(SpeculativeDstOpaqueTypes.empty());
83
84 // Check to see if these types are recursively isomorphic and establish a
85 // mapping between them if so.
86 if (!areTypesIsomorphic(DstTy, SrcTy)) {
87 // Oops, they aren't isomorphic. Just discard this request by rolling out
88 // any speculative mappings we've established.
89 for (Type *Ty : SpeculativeTypes)
90 MappedTypes.erase(Ty);
91
92 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
93 SpeculativeDstOpaqueTypes.size());
94 for (StructType *Ty : SpeculativeDstOpaqueTypes)
95 DstResolvedOpaqueTypes.erase(Ty);
96 } else {
97 for (Type *Ty : SpeculativeTypes)
98 if (auto *STy = dyn_cast<StructType>(Ty))
99 if (STy->hasName())
100 STy->setName("");
101 }
102 SpeculativeTypes.clear();
103 SpeculativeDstOpaqueTypes.clear();
104}
105
106/// Recursively walk this pair of types, returning true if they are isomorphic,
107/// false if they are not.
108bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
109 // Two types with differing kinds are clearly not isomorphic.
110 if (DstTy->getTypeID() != SrcTy->getTypeID())
111 return false;
112
113 // If we have an entry in the MappedTypes table, then we have our answer.
114 Type *&Entry = MappedTypes[SrcTy];
115 if (Entry)
116 return Entry == DstTy;
117
118 // Two identical types are clearly isomorphic. Remember this
119 // non-speculatively.
120 if (DstTy == SrcTy) {
121 Entry = DstTy;
122 return true;
123 }
124
125 // Okay, we have two types with identical kinds that we haven't seen before.
126
127 // If this is an opaque struct type, special case it.
128 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
129 // Mapping an opaque type to any struct, just keep the dest struct.
130 if (SSTy->isOpaque()) {
131 Entry = DstTy;
132 SpeculativeTypes.push_back(SrcTy);
133 return true;
134 }
135
136 // Mapping a non-opaque source type to an opaque dest. If this is the first
137 // type that we're mapping onto this destination type then we succeed. Keep
138 // the dest, but fill it in later. If this is the second (different) type
139 // that we're trying to map onto the same opaque type then we fail.
140 if (cast<StructType>(DstTy)->isOpaque()) {
141 // We can only map one source type onto the opaque destination type.
142 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
143 return false;
144 SrcDefinitionsToResolve.push_back(SSTy);
145 SpeculativeTypes.push_back(SrcTy);
146 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
147 Entry = DstTy;
148 return true;
149 }
150 }
151
152 // If the number of subtypes disagree between the two types, then we fail.
153 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
154 return false;
155
156 // Fail if any of the extra properties (e.g. array size) of the type disagree.
157 if (isa<IntegerType>(DstTy))
158 return false; // bitwidth disagrees.
159 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
160 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
161 return false;
162
163 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
164 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
165 return false;
166 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
167 StructType *SSTy = cast<StructType>(SrcTy);
168 if (DSTy->isLiteral() != SSTy->isLiteral() ||
169 DSTy->isPacked() != SSTy->isPacked())
170 return false;
171 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
172 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
173 return false;
174 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
175 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
176 return false;
177 }
178
179 // Otherwise, we speculate that these two types will line up and recursively
180 // check the subelements.
181 Entry = DstTy;
182 SpeculativeTypes.push_back(SrcTy);
183
184 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
185 if (!areTypesIsomorphic(DstTy->getContainedType(I),
186 SrcTy->getContainedType(I)))
187 return false;
188
189 // If everything seems to have lined up, then everything is great.
190 return true;
191}
192
193void TypeMapTy::linkDefinedTypeBodies() {
194 SmallVector<Type *, 16> Elements;
195 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
196 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
197 assert(DstSTy->isOpaque());
198
199 // Map the body of the source type over to a new body for the dest type.
200 Elements.resize(SrcSTy->getNumElements());
201 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
202 Elements[I] = get(SrcSTy->getElementType(I));
203
204 DstSTy->setBody(Elements, SrcSTy->isPacked());
205 DstStructTypesSet.switchToNonOpaque(DstSTy);
206 }
207 SrcDefinitionsToResolve.clear();
208 DstResolvedOpaqueTypes.clear();
209}
210
211void TypeMapTy::finishType(StructType *DTy, StructType *STy,
212 ArrayRef<Type *> ETypes) {
213 DTy->setBody(ETypes, STy->isPacked());
214
215 // Steal STy's name.
216 if (STy->hasName()) {
217 SmallString<16> TmpName = STy->getName();
218 STy->setName("");
219 DTy->setName(TmpName);
220 }
221
222 DstStructTypesSet.addNonOpaque(DTy);
223}
224
225Type *TypeMapTy::get(Type *Ty) {
226 SmallPtrSet<StructType *, 8> Visited;
227 return get(Ty, Visited);
228}
229
230Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
231 // If we already have an entry for this type, return it.
232 Type **Entry = &MappedTypes[Ty];
233 if (*Entry)
234 return *Entry;
235
236 // These are types that LLVM itself will unique.
237 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
238
239#ifndef NDEBUG
240 if (!IsUniqued) {
241 for (auto &Pair : MappedTypes) {
242 assert(!(Pair.first != Ty && Pair.second == Ty) &&
243 "mapping to a source type");
244 }
245 }
246#endif
247
248 if (!IsUniqued && !Visited.insert(cast<StructType>(Ty)).second) {
249 StructType *DTy = StructType::create(Ty->getContext());
250 return *Entry = DTy;
251 }
252
253 // If this is not a recursive type, then just map all of the elements and
254 // then rebuild the type from inside out.
255 SmallVector<Type *, 4> ElementTypes;
256
257 // If there are no element types to map, then the type is itself. This is
258 // true for the anonymous {} struct, things like 'float', integers, etc.
259 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
260 return *Entry = Ty;
261
262 // Remap all of the elements, keeping track of whether any of them change.
263 bool AnyChange = false;
264 ElementTypes.resize(Ty->getNumContainedTypes());
265 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
266 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
267 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
268 }
269
270 // If we found our type while recursively processing stuff, just use it.
271 Entry = &MappedTypes[Ty];
272 if (*Entry) {
273 if (auto *DTy = dyn_cast<StructType>(*Entry)) {
274 if (DTy->isOpaque()) {
275 auto *STy = cast<StructType>(Ty);
276 finishType(DTy, STy, ElementTypes);
277 }
278 }
279 return *Entry;
280 }
281
282 // If all of the element types mapped directly over and the type is not
283 // a nomed struct, then the type is usable as-is.
284 if (!AnyChange && IsUniqued)
285 return *Entry = Ty;
286
287 // Otherwise, rebuild a modified type.
288 switch (Ty->getTypeID()) {
289 default:
290 llvm_unreachable("unknown derived type to remap");
291 case Type::ArrayTyID:
292 return *Entry = ArrayType::get(ElementTypes[0],
293 cast<ArrayType>(Ty)->getNumElements());
294 case Type::VectorTyID:
295 return *Entry = VectorType::get(ElementTypes[0],
296 cast<VectorType>(Ty)->getNumElements());
297 case Type::PointerTyID:
298 return *Entry = PointerType::get(ElementTypes[0],
299 cast<PointerType>(Ty)->getAddressSpace());
300 case Type::FunctionTyID:
301 return *Entry = FunctionType::get(ElementTypes[0],
302 makeArrayRef(ElementTypes).slice(1),
303 cast<FunctionType>(Ty)->isVarArg());
304 case Type::StructTyID: {
305 auto *STy = cast<StructType>(Ty);
306 bool IsPacked = STy->isPacked();
307 if (IsUniqued)
308 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
309
310 // If the type is opaque, we can just use it directly.
311 if (STy->isOpaque()) {
312 DstStructTypesSet.addOpaque(STy);
313 return *Entry = Ty;
314 }
315
316 if (StructType *OldT =
317 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
318 STy->setName("");
319 return *Entry = OldT;
320 }
321
322 if (!AnyChange) {
323 DstStructTypesSet.addNonOpaque(STy);
324 return *Entry = Ty;
325 }
326
327 StructType *DTy = StructType::create(Ty->getContext());
328 finishType(DTy, STy, ElementTypes);
329 return *Entry = DTy;
330 }
331 }
332}
333
334LinkDiagnosticInfo::LinkDiagnosticInfo(DiagnosticSeverity Severity,
335 const Twine &Msg)
336 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
337void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
338
339//===----------------------------------------------------------------------===//
Teresa Johnsonbef54362015-12-18 19:28:59 +0000340// IRLinker implementation.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000341//===----------------------------------------------------------------------===//
342
343namespace {
344class IRLinker;
345
346/// Creates prototypes for functions that are lazily linked on the fly. This
347/// speeds up linking for modules with many/ lazily linked functions of which
348/// few get used.
349class GlobalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000350 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000351
352public:
Mehdi Amini33661072016-03-11 22:19:06 +0000353 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000354 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000355};
356
357class LocalValueMaterializer final : public ValueMaterializer {
Mehdi Amini33661072016-03-11 22:19:06 +0000358 IRLinker &TheIRLinker;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000359
360public:
Mehdi Amini33661072016-03-11 22:19:06 +0000361 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000362 Value *materialize(Value *V) override;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000363};
364
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000365/// Type of the Metadata map in \a ValueToValueMapTy.
366typedef DenseMap<const Metadata *, TrackingMDRef> MDMapT;
367
Rafael Espindolacaabe222015-12-10 14:19:35 +0000368/// This is responsible for keeping track of the state used for moving data
369/// from SrcM to DstM.
370class IRLinker {
371 Module &DstM;
Rafael Espindola40358fb2016-02-16 18:50:12 +0000372 std::unique_ptr<Module> SrcM;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000373
Mehdi Amini33661072016-03-11 22:19:06 +0000374 /// See IRMover::move().
Rafael Espindolacaabe222015-12-10 14:19:35 +0000375 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor;
376
377 TypeMapTy TypeMap;
378 GlobalValueMaterializer GValMaterializer;
379 LocalValueMaterializer LValMaterializer;
380
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000381 /// A metadata map that's shared between IRLinker instances.
382 MDMapT &SharedMDs;
383
Rafael Espindolacaabe222015-12-10 14:19:35 +0000384 /// Mapping of values from what they used to be in Src, to what they are now
385 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
386 /// due to the use of Value handles which the Linker doesn't actually need,
387 /// but this allows us to reuse the ValueMapper code.
388 ValueToValueMapTy ValueMap;
389 ValueToValueMapTy AliasValueMap;
390
391 DenseSet<GlobalValue *> ValuesToLink;
392 std::vector<GlobalValue *> Worklist;
393
394 void maybeAdd(GlobalValue *GV) {
395 if (ValuesToLink.insert(GV).second)
396 Worklist.push_back(GV);
397 }
398
Rafael Espindolacaabe222015-12-10 14:19:35 +0000399 /// Set to true when all global value body linking is complete (including
400 /// lazy linking). Used to prevent metadata linking from creating new
401 /// references.
402 bool DoneLinkingBodies = false;
403
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000404 /// The Error encountered during materialization. We use an Optional here to
405 /// avoid needing to manage an unconsumed success value.
406 Optional<Error> FoundError;
407 void setError(Error E) {
408 if (E)
409 FoundError = std::move(E);
410 }
411
412 /// Most of the errors produced by this module are inconvertible StringErrors.
413 /// This convenience function lets us return one of those more easily.
414 Error stringErr(const Twine &T) {
415 return make_error<StringError>(T, inconvertibleErrorCode());
416 }
Rafael Espindolacaabe222015-12-10 14:19:35 +0000417
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000418 /// Entry point for mapping values and alternate context for mapping aliases.
419 ValueMapper Mapper;
420 unsigned AliasMCID;
Teresa Johnsone5a61912015-12-17 17:14:09 +0000421
Rafael Espindolacaabe222015-12-10 14:19:35 +0000422 /// Handles cloning of a global values from the source module into
423 /// the destination module, including setting the attributes and visibility.
424 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
425
Rafael Espindolacaabe222015-12-10 14:19:35 +0000426 void emitWarning(const Twine &Message) {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000427 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
Rafael Espindolacaabe222015-12-10 14:19:35 +0000428 }
429
430 /// Given a global in the source module, return the global in the
431 /// destination module that is being linked to, if any.
432 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
433 // If the source has no name it can't link. If it has local linkage,
434 // there is no name match-up going on.
435 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
436 return nullptr;
437
438 // Otherwise see if we have a match in the destination module's symtab.
439 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
440 if (!DGV)
441 return nullptr;
442
443 // If we found a global with the same name in the dest module, but it has
444 // internal linkage, we are really not doing any linkage here.
445 if (DGV->hasLocalLinkage())
446 return nullptr;
447
448 // Otherwise, we do in fact link to the destination global.
449 return DGV;
450 }
451
452 void computeTypeMapping();
453
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000454 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
455 const GlobalVariable *SrcGV);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000456
Mehdi Amini33661072016-03-11 22:19:06 +0000457 /// Given the GlobaValue \p SGV in the source module, and the matching
458 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
459 /// into the destination module.
460 ///
461 /// Note this code may call the client-provided \p AddLazyFor.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000462 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000463 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000464
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000465 Error linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000466
467 void linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000468 Error linkFunctionBody(Function &Dst, Function &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000469 void linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000470 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000471
472 /// Functions that take care of cloning a specific global value type
473 /// into the destination module.
474 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
475 Function *copyFunctionProto(const Function *SF);
476 GlobalValue *copyGlobalAliasProto(const GlobalAlias *SGA);
477
478 void linkNamedMDNodes();
479
480public:
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +0000481 IRLinker(Module &DstM, MDMapT &SharedMDs,
482 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
483 ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +0000484 std::function<void(GlobalValue &, IRMover::ValueAdder)> AddLazyFor)
Benjamin Kramer82de7d32016-05-27 14:27:24 +0000485 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
486 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
487 SharedMDs(SharedMDs),
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000488 Mapper(ValueMap, RF_MoveDistinctMDs | RF_IgnoreMissingLocals, &TypeMap,
489 &GValMaterializer),
490 AliasMCID(Mapper.registerAlternateMappingContext(AliasValueMap,
491 &LValMaterializer)) {
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000492 ValueMap.getMDMap() = std::move(SharedMDs);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000493 for (GlobalValue *GV : ValuesToLink)
494 maybeAdd(GV);
Teresa Johnsoncc428572015-12-30 19:32:24 +0000495 }
Duncan P. N. Exon Smitha4810fa2016-04-19 16:57:24 +0000496 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
Teresa Johnsoncc428572015-12-30 19:32:24 +0000497
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000498 Error run();
Mehdi Amini53a66722016-05-25 21:01:51 +0000499 Value *materialize(Value *V, bool ForAlias);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000500};
501}
502
503/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
504/// table. This is good for all clients except for us. Go through the trouble
505/// to force this back.
506static void forceRenaming(GlobalValue *GV, StringRef Name) {
507 // If the global doesn't force its name or if it already has the right name,
508 // there is nothing for us to do.
509 if (GV->hasLocalLinkage() || GV->getName() == Name)
510 return;
511
512 Module *M = GV->getParent();
513
514 // If there is a conflict, rename the conflict.
515 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
516 GV->takeName(ConflictGV);
517 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
518 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
519 } else {
520 GV->setName(Name); // Force the name back
521 }
522}
523
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000524Value *GlobalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000525 return TheIRLinker.materialize(SGV, false);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000526}
527
Mehdi Aminicc8c1072016-05-25 21:03:21 +0000528Value *LocalValueMaterializer::materialize(Value *SGV) {
Mehdi Amini53a66722016-05-25 21:01:51 +0000529 return TheIRLinker.materialize(SGV, true);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000530}
531
Mehdi Amini53a66722016-05-25 21:01:51 +0000532Value *IRLinker::materialize(Value *V, bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000533 auto *SGV = dyn_cast<GlobalValue>(V);
534 if (!SGV)
535 return nullptr;
536
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000537 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForAlias);
538 if (!NewProto) {
539 setError(NewProto.takeError());
540 return nullptr;
541 }
542 if (!*NewProto)
543 return nullptr;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000544
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000545 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
Mehdi Amini53a66722016-05-25 21:01:51 +0000546 if (!New)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000547 return *NewProto;
Mehdi Amini53a66722016-05-25 21:01:51 +0000548
Rafael Espindolacaabe222015-12-10 14:19:35 +0000549 // If we already created the body, just return.
550 if (auto *F = dyn_cast<Function>(New)) {
551 if (!F->isDeclaration())
Mehdi Amini53a66722016-05-25 21:01:51 +0000552 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000553 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
Duncan P. N. Exon Smith0fdaf8c2016-04-17 19:40:20 +0000554 if (V->hasInitializer() || V->hasAppendingLinkage())
Mehdi Amini53a66722016-05-25 21:01:51 +0000555 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000556 } else {
557 auto *A = cast<GlobalAlias>(New);
558 if (A->getAliasee())
Mehdi Amini53a66722016-05-25 21:01:51 +0000559 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000560 }
561
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000562 // When linking a global for an alias, it will always be linked. However we
563 // need to check if it was not already scheduled to satify a reference from a
564 // regular global value initializer. We know if it has been schedule if the
565 // "New" GlobalValue that is mapped here for the alias is the same as the one
566 // already mapped. If there is an entry in the ValueMap but the value is
567 // different, it means that the value already had a definition in the
568 // destination module (linkonce for instance), but we need a new definition
569 // for the alias ("New" will be different.
Mehdi Amini53a66722016-05-25 21:01:51 +0000570 if (ForAlias && ValueMap.lookup(SGV) == New)
571 return New;
Mehdi Amini3d4f3a02016-05-25 21:00:44 +0000572
Mehdi Amini53a66722016-05-25 21:01:51 +0000573 if (ForAlias || shouldLink(New, *SGV))
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000574 setError(linkGlobalValueBody(*New, *SGV));
Mehdi Amini53a66722016-05-25 21:01:51 +0000575
576 return New;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000577}
578
579/// Loop through the global variables in the src module and merge them into the
580/// dest module.
581GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
582 // No linking to be performed or linking from the source: simply create an
583 // identical version of the symbol over in the dest module... the
584 // initializer will be filled in later by LinkGlobalInits.
585 GlobalVariable *NewDGV =
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000586 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000587 SGVar->isConstant(), GlobalValue::ExternalLinkage,
588 /*init*/ nullptr, SGVar->getName(),
589 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
590 SGVar->getType()->getAddressSpace());
591 NewDGV->setAlignment(SGVar->getAlignment());
592 return NewDGV;
593}
594
595/// Link the function in the source module into the destination module if
596/// needed, setting up mapping information.
597Function *IRLinker::copyFunctionProto(const Function *SF) {
598 // If there is no linkage to be performed or we are linking from the source,
599 // bring SF over.
600 return Function::Create(TypeMap.get(SF->getFunctionType()),
601 GlobalValue::ExternalLinkage, SF->getName(), &DstM);
602}
603
604/// Set up prototypes for any aliases that come over from the source module.
605GlobalValue *IRLinker::copyGlobalAliasProto(const GlobalAlias *SGA) {
606 // If there is no linkage to be performed or we're linking from the source,
607 // bring over SGA.
608 auto *Ty = TypeMap.get(SGA->getValueType());
609 return GlobalAlias::create(Ty, SGA->getType()->getPointerAddressSpace(),
610 GlobalValue::ExternalLinkage, SGA->getName(),
611 &DstM);
612}
613
614GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
615 bool ForDefinition) {
616 GlobalValue *NewGV;
617 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
618 NewGV = copyGlobalVariableProto(SGVar);
619 } else if (auto *SF = dyn_cast<Function>(SGV)) {
620 NewGV = copyFunctionProto(SF);
621 } else {
622 if (ForDefinition)
623 NewGV = copyGlobalAliasProto(cast<GlobalAlias>(SGV));
624 else
625 NewGV = new GlobalVariable(
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000626 DstM, TypeMap.get(SGV->getValueType()),
Rafael Espindolacaabe222015-12-10 14:19:35 +0000627 /*isConstant*/ false, GlobalValue::ExternalLinkage,
628 /*init*/ nullptr, SGV->getName(),
629 /*insertbefore*/ nullptr, SGV->getThreadLocalMode(),
630 SGV->getType()->getAddressSpace());
631 }
632
633 if (ForDefinition)
634 NewGV->setLinkage(SGV->getLinkage());
Mehdi Amini113adde2016-04-19 16:11:05 +0000635 else if (SGV->hasExternalWeakLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000636 NewGV->setLinkage(GlobalValue::ExternalWeakLinkage);
637
638 NewGV->copyAttributesFrom(SGV);
Teresa Johnson5fe40052016-01-12 00:24:24 +0000639
Reid Klecknerc0a03632016-05-25 18:36:22 +0000640 // Don't copy the comdat, it's from the original module. We'll handle it
641 // later.
642 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV))
643 NewGO->setComdat(nullptr);
644
Teresa Johnson5fe40052016-01-12 00:24:24 +0000645 // Remove these copied constants in case this stays a declaration, since
646 // they point to the source module. If the def is linked the values will
647 // be mapped in during linkFunctionBody.
648 if (auto *NewF = dyn_cast<Function>(NewGV)) {
649 NewF->setPersonalityFn(nullptr);
650 NewF->setPrefixData(nullptr);
651 NewF->setPrologueData(nullptr);
652 }
653
Rafael Espindolacaabe222015-12-10 14:19:35 +0000654 return NewGV;
655}
656
657/// Loop over all of the linked values to compute type mappings. For example,
658/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
659/// types 'Foo' but one got renamed when the module was loaded into the same
660/// LLVMContext.
661void IRLinker::computeTypeMapping() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000662 for (GlobalValue &SGV : SrcM->globals()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000663 GlobalValue *DGV = getLinkedToGlobal(&SGV);
664 if (!DGV)
665 continue;
666
667 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
668 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
669 continue;
670 }
671
672 // Unify the element type of appending arrays.
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000673 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
674 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000675 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
676 }
677
Rafael Espindola40358fb2016-02-16 18:50:12 +0000678 for (GlobalValue &SGV : *SrcM)
Rafael Espindolacaabe222015-12-10 14:19:35 +0000679 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
680 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
681
Rafael Espindola40358fb2016-02-16 18:50:12 +0000682 for (GlobalValue &SGV : SrcM->aliases())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000683 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
684 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
685
686 // Incorporate types by name, scanning all the types in the source module.
687 // At this point, the destination module may have a type "%foo = { i32 }" for
688 // example. When the source module got loaded into the same LLVMContext, if
689 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
Rafael Espindola40358fb2016-02-16 18:50:12 +0000690 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000691 for (StructType *ST : Types) {
692 if (!ST->hasName())
693 continue;
694
695 // Check to see if there is a dot in the name followed by a digit.
696 size_t DotPos = ST->getName().rfind('.');
697 if (DotPos == 0 || DotPos == StringRef::npos ||
698 ST->getName().back() == '.' ||
699 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
700 continue;
701
702 // Check to see if the destination module has a struct with the prefix name.
703 StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
704 if (!DST)
705 continue;
706
707 // Don't use it if this actually came from the source module. They're in
708 // the same LLVMContext after all. Also don't use it unless the type is
709 // actually used in the destination module. This can happen in situations
710 // like this:
711 //
712 // Module A Module B
713 // -------- --------
714 // %Z = type { %A } %B = type { %C.1 }
715 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
716 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
717 // %C = type { i8* } %B.3 = type { %C.1 }
718 //
719 // When we link Module B with Module A, the '%B' in Module B is
720 // used. However, that would then use '%C.1'. But when we process '%C.1',
721 // we prefer to take the '%C' version. So we are then left with both
722 // '%C.1' and '%C' being used for the same types. This leads to some
723 // variables using one type and some using the other.
724 if (TypeMap.DstStructTypesSet.hasType(DST))
725 TypeMap.addTypeMapping(DST, ST);
726 }
727
728 // Now that we have discovered all of the type equivalences, get a body for
729 // any 'opaque' types in the dest module that are now resolved.
730 TypeMap.linkDefinedTypeBodies();
731}
732
733static void getArrayElements(const Constant *C,
734 SmallVectorImpl<Constant *> &Dest) {
735 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
736
737 for (unsigned i = 0; i != NumElements; ++i)
738 Dest.push_back(C->getAggregateElement(i));
739}
740
741/// If there were any appending global variables, link them together now.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000742Expected<Constant *>
743IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
744 const GlobalVariable *SrcGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000745 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
Rafael Espindolacaabe222015-12-10 14:19:35 +0000746 ->getElementType();
747
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000748 // FIXME: This upgrade is done during linking to support the C API. Once the
749 // old form is deprecated, we should move this upgrade to
750 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
751 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000752 StringRef Name = SrcGV->getName();
753 bool IsNewStructor = false;
754 bool IsOldStructor = false;
755 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
756 if (cast<StructType>(EltTy)->getNumElements() == 3)
757 IsNewStructor = true;
758 else
759 IsOldStructor = true;
760 }
761
762 PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
763 if (IsOldStructor) {
764 auto &ST = *cast<StructType>(EltTy);
765 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
766 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
767 }
768
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000769 uint64_t DstNumElements = 0;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000770 if (DstGV) {
Manuel Jacob5f6eaac2016-01-16 20:30:46 +0000771 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000772 DstNumElements = DstTy->getNumElements();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000773
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000774 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
775 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000776 "Linking globals named '" + SrcGV->getName() +
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000777 "': can only link appending global with another appending "
778 "global!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000779
780 // Check to see that they two arrays agree on type.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000781 if (EltTy != DstTy->getElementType())
782 return stringErr("Appending variables with different element types!");
783 if (DstGV->isConstant() != SrcGV->isConstant())
784 return stringErr("Appending variables linked with different const'ness!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000785
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000786 if (DstGV->getAlignment() != SrcGV->getAlignment())
787 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000788 "Appending variables with different alignment need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000789
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000790 if (DstGV->getVisibility() != SrcGV->getVisibility())
791 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000792 "Appending variables with different visibility need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000793
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000794 if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
795 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000796 "Appending variables with different unnamed_addr need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000797
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000798 if (DstGV->getSection() != SrcGV->getSection())
799 return stringErr(
Rafael Espindolacaabe222015-12-10 14:19:35 +0000800 "Appending variables with different section name need to be linked!");
Rafael Espindolacaabe222015-12-10 14:19:35 +0000801 }
802
Rafael Espindolacaabe222015-12-10 14:19:35 +0000803 SmallVector<Constant *, 16> SrcElements;
804 getArrayElements(SrcGV->getInitializer(), SrcElements);
805
806 if (IsNewStructor)
807 SrcElements.erase(
808 std::remove_if(SrcElements.begin(), SrcElements.end(),
809 [this](Constant *E) {
810 auto *Key = dyn_cast<GlobalValue>(
811 E->getAggregateElement(2)->stripPointerCasts());
812 if (!Key)
813 return false;
814 GlobalValue *DGV = getLinkedToGlobal(Key);
815 return !shouldLink(DGV, *Key);
816 }),
817 SrcElements.end());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000818 uint64_t NewSize = DstNumElements + SrcElements.size();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000819 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
820
821 // Create the new global variable.
822 GlobalVariable *NG = new GlobalVariable(
823 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
824 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
825 SrcGV->getType()->getAddressSpace());
826
827 NG->copyAttributesFrom(SrcGV);
828 forceRenaming(NG, SrcGV->getName());
829
830 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
831
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000832 Mapper.scheduleMapAppendingVariable(*NG,
833 DstGV ? DstGV->getInitializer() : nullptr,
834 IsOldStructor, SrcElements);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000835
836 // Replace any uses of the two global variables with uses of the new
837 // global.
838 if (DstGV) {
839 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
840 DstGV->eraseFromParent();
841 }
842
843 return Ret;
844}
845
Rafael Espindolacaabe222015-12-10 14:19:35 +0000846bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
Davide Italiano95339652016-06-07 14:55:04 +0000847 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
Rafael Espindolacaabe222015-12-10 14:19:35 +0000848 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
Davide Italiano95339652016-06-07 14:55:04 +0000856 if (SGV.isDeclaration() || DoneLinkingBodies)
Rafael Espindola15ca14c2016-04-21 14:56:33 +0000857 return false;
Mehdi Amini33661072016-03-11 22:19:06 +0000858
859 // Callback to the client to give a chance to lazily add the Global to the
860 // list of value to link.
861 bool LazilyAdded = false;
862 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
863 maybeAdd(&GV);
864 LazilyAdded = true;
865 });
866 return LazilyAdded;
Rafael Espindolacaabe222015-12-10 14:19:35 +0000867}
868
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000869Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
870 bool ForAlias) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000871 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 Smith39423b02016-04-16 02:29:55 +0000938 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000939}
940
941/// Copy the source function over into the dest function and fix up references
942/// to values. At this point we know that Dest is an external function, and
943/// that Src is not.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000944Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000945 assert(Dst.isDeclaration() && !Src.isDeclaration());
946
947 // Materialize if needed.
948 if (std::error_code EC = Src.materialize())
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000949 return errorCodeToError(EC);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000950
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000951 // Link in the operands without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000952 if (Src.hasPrefixData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000953 Dst.setPrefixData(Src.getPrefixData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000954 if (Src.hasPrologueData())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000955 Dst.setPrologueData(Src.getPrologueData());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000956 if (Src.hasPersonalityFn())
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000957 Dst.setPersonalityFn(Src.getPersonalityFn());
Rafael Espindolacaabe222015-12-10 14:19:35 +0000958
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000959 // Copy over the metadata attachments without remapping.
Rafael Espindolacaabe222015-12-10 14:19:35 +0000960 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
961 Src.getAllMetadata(MDs);
962 for (const auto &I : MDs)
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000963 Dst.setMetadata(I.first, I.second);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000964
Duncan P. N. Exon Smithbdfc9842016-04-06 06:38:15 +0000965 // Steal arguments and splice the body of Src into Dst.
966 Dst.stealArgumentListFrom(Src);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000967 Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
968
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000969 // Everything has been moved over. Remap it.
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000970 Mapper.scheduleRemapFunction(Dst);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000971 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000972}
973
974void IRLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000975 Mapper.scheduleMapGlobalAliasee(Dst, *Src.getAliasee(), AliasMCID);
Rafael Espindolacaabe222015-12-10 14:19:35 +0000976}
977
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000978Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000979 if (auto *F = dyn_cast<Function>(&Src))
980 return linkFunctionBody(cast<Function>(Dst), *F);
981 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
982 linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000983 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000984 }
985 linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +0000986 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +0000987}
988
989/// Insert all of the named MDNodes in Src into the Dest module.
990void IRLinker::linkNamedMDNodes() {
Rafael Espindola40358fb2016-02-16 18:50:12 +0000991 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
992 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +0000993 // Don't link module flags here. Do them separately.
994 if (&NMD == SrcModFlags)
995 continue;
996 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
997 // Add Src elements into Dest node.
Duncan P. N. Exon Smith8a15dab2016-04-15 23:32:44 +0000998 for (const MDNode *Op : NMD.operands())
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +0000999 DestNMD->addOperand(Mapper.mapMDNode(*Op));
Rafael Espindolacaabe222015-12-10 14:19:35 +00001000 }
1001}
1002
1003/// Merge the linker flags in Src into the Dest module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001004Error IRLinker::linkModuleFlagsMetadata() {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001005 // If the source module has no module flags, we are done.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001006 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001007 if (!SrcModFlags)
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001008 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001009
1010 // If the destination module doesn't have module flags yet, then just copy
1011 // over the source module's flags.
1012 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1013 if (DstModFlags->getNumOperands() == 0) {
1014 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1015 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1016
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001017 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001018 }
1019
1020 // First build a map of the existing module flags and requirements.
1021 DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags;
1022 SmallSetVector<MDNode *, 16> Requirements;
1023 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1024 MDNode *Op = DstModFlags->getOperand(I);
1025 ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0));
1026 MDString *ID = cast<MDString>(Op->getOperand(1));
1027
1028 if (Behavior->getZExtValue() == Module::Require) {
1029 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1030 } else {
1031 Flags[ID] = std::make_pair(Op, I);
1032 }
1033 }
1034
1035 // Merge in the flags from the source module, and also collect its set of
1036 // requirements.
1037 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1038 MDNode *SrcOp = SrcModFlags->getOperand(I);
1039 ConstantInt *SrcBehavior =
1040 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1041 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1042 MDNode *DstOp;
1043 unsigned DstIndex;
1044 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1045 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1046
1047 // If this is a requirement, add it and continue.
1048 if (SrcBehaviorValue == Module::Require) {
1049 // If the destination module does not already have this requirement, add
1050 // it.
1051 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1052 DstModFlags->addOperand(SrcOp);
1053 }
1054 continue;
1055 }
1056
1057 // If there is no existing flag with this ID, just add it.
1058 if (!DstOp) {
1059 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1060 DstModFlags->addOperand(SrcOp);
1061 continue;
1062 }
1063
1064 // Otherwise, perform a merge.
1065 ConstantInt *DstBehavior =
1066 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1067 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1068
1069 // If either flag has override behavior, handle it first.
1070 if (DstBehaviorValue == Module::Override) {
1071 // Diagnose inconsistent flags which both have override behavior.
1072 if (SrcBehaviorValue == Module::Override &&
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001073 SrcOp->getOperand(2) != DstOp->getOperand(2))
1074 return stringErr("linking module flags '" + ID->getString() +
1075 "': IDs have conflicting override values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001076 continue;
1077 } else if (SrcBehaviorValue == Module::Override) {
1078 // Update the destination flag to that of the source.
1079 DstModFlags->setOperand(DstIndex, SrcOp);
1080 Flags[ID].first = SrcOp;
1081 continue;
1082 }
1083
1084 // Diagnose inconsistent merge behavior types.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001085 if (SrcBehaviorValue != DstBehaviorValue)
1086 return stringErr("linking module flags '" + ID->getString() +
1087 "': IDs have conflicting behaviors");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001088
1089 auto replaceDstValue = [&](MDNode *New) {
1090 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1091 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1092 DstModFlags->setOperand(DstIndex, Flag);
1093 Flags[ID].first = Flag;
1094 };
1095
1096 // Perform the merge for standard behavior types.
1097 switch (SrcBehaviorValue) {
1098 case Module::Require:
1099 case Module::Override:
1100 llvm_unreachable("not possible");
1101 case Module::Error: {
1102 // Emit an error if the values differ.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001103 if (SrcOp->getOperand(2) != DstOp->getOperand(2))
1104 return stringErr("linking module flags '" + ID->getString() +
1105 "': IDs have conflicting values");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001106 continue;
1107 }
1108 case Module::Warning: {
1109 // Emit a warning if the values differ.
1110 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1111 emitWarning("linking module flags '" + ID->getString() +
1112 "': IDs have conflicting values");
1113 }
1114 continue;
1115 }
1116 case Module::Append: {
1117 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1118 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1119 SmallVector<Metadata *, 8> MDs;
1120 MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands());
1121 MDs.append(DstValue->op_begin(), DstValue->op_end());
1122 MDs.append(SrcValue->op_begin(), SrcValue->op_end());
1123
1124 replaceDstValue(MDNode::get(DstM.getContext(), MDs));
1125 break;
1126 }
1127 case Module::AppendUnique: {
1128 SmallSetVector<Metadata *, 16> Elts;
1129 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1130 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1131 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1132 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1133
1134 replaceDstValue(MDNode::get(DstM.getContext(),
1135 makeArrayRef(Elts.begin(), Elts.end())));
1136 break;
1137 }
1138 }
1139 }
1140
1141 // Check all of the requirements.
1142 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1143 MDNode *Requirement = Requirements[I];
1144 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1145 Metadata *ReqValue = Requirement->getOperand(1);
1146
1147 MDNode *Op = Flags[Flag].first;
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001148 if (!Op || Op->getOperand(2) != ReqValue)
1149 return stringErr("linking module flags '" + Flag->getString() +
1150 "': does not have the required value");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001151 }
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001152 return Error::success();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001153}
1154
1155// This function returns true if the triples match.
1156static bool triplesMatch(const Triple &T0, const Triple &T1) {
1157 // If vendor is apple, ignore the version number.
1158 if (T0.getVendor() == Triple::Apple)
1159 return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
1160 T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
1161
1162 return T0 == T1;
1163}
1164
1165// This function returns the merged triple.
1166static std::string mergeTriples(const Triple &SrcTriple,
1167 const Triple &DstTriple) {
1168 // If vendor is apple, pick the triple with the larger version number.
1169 if (SrcTriple.getVendor() == Triple::Apple)
1170 if (DstTriple.isOSVersionLT(SrcTriple))
1171 return SrcTriple.str();
1172
1173 return DstTriple.str();
1174}
1175
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001176Error IRLinker::run() {
Teresa Johnson0556e222016-03-10 18:47:03 +00001177 // Ensure metadata materialized before value mapping.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001178 if (SrcM->getMaterializer())
1179 if (std::error_code EC = SrcM->getMaterializer()->materializeMetadata())
1180 return errorCodeToError(EC);
Teresa Johnson0556e222016-03-10 18:47:03 +00001181
Rafael Espindolacaabe222015-12-10 14:19:35 +00001182 // Inherit the target data from the source module if the destination module
1183 // doesn't have one already.
1184 if (DstM.getDataLayout().isDefault())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001185 DstM.setDataLayout(SrcM->getDataLayout());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001186
Rafael Espindola40358fb2016-02-16 18:50:12 +00001187 if (SrcM->getDataLayout() != DstM.getDataLayout()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001188 emitWarning("Linking two modules of different data layouts: '" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001189 SrcM->getModuleIdentifier() + "' is '" +
1190 SrcM->getDataLayoutStr() + "' whereas '" +
Rafael Espindolacaabe222015-12-10 14:19:35 +00001191 DstM.getModuleIdentifier() + "' is '" +
1192 DstM.getDataLayoutStr() + "'\n");
1193 }
1194
1195 // Copy the target triple from the source to dest if the dest's is empty.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001196 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1197 DstM.setTargetTriple(SrcM->getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001198
Rafael Espindola40358fb2016-02-16 18:50:12 +00001199 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001200
Rafael Espindola40358fb2016-02-16 18:50:12 +00001201 if (!SrcM->getTargetTriple().empty() && !triplesMatch(SrcTriple, DstTriple))
Rafael Espindolacaabe222015-12-10 14:19:35 +00001202 emitWarning("Linking two modules of different target triples: " +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001203 SrcM->getModuleIdentifier() + "' is '" +
1204 SrcM->getTargetTriple() + "' whereas '" +
1205 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1206 "'\n");
Rafael Espindolacaabe222015-12-10 14:19:35 +00001207
1208 DstM.setTargetTriple(mergeTriples(SrcTriple, DstTriple));
1209
1210 // Append the module inline asm string.
Rafael Espindola40358fb2016-02-16 18:50:12 +00001211 if (!SrcM->getModuleInlineAsm().empty()) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001212 if (DstM.getModuleInlineAsm().empty())
Rafael Espindola40358fb2016-02-16 18:50:12 +00001213 DstM.setModuleInlineAsm(SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001214 else
1215 DstM.setModuleInlineAsm(DstM.getModuleInlineAsm() + "\n" +
Rafael Espindola40358fb2016-02-16 18:50:12 +00001216 SrcM->getModuleInlineAsm());
Rafael Espindolacaabe222015-12-10 14:19:35 +00001217 }
1218
1219 // Loop over all of the linked values to compute type mappings.
1220 computeTypeMapping();
1221
1222 std::reverse(Worklist.begin(), Worklist.end());
1223 while (!Worklist.empty()) {
1224 GlobalValue *GV = Worklist.back();
1225 Worklist.pop_back();
1226
1227 // Already mapped.
1228 if (ValueMap.find(GV) != ValueMap.end() ||
1229 AliasValueMap.find(GV) != AliasValueMap.end())
1230 continue;
1231
1232 assert(!GV->isDeclaration());
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001233 Mapper.mapValue(*GV);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001234 if (FoundError)
1235 return std::move(*FoundError);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001236 }
1237
1238 // Note that we are done linking global value bodies. This prevents
1239 // metadata linking from creating new references.
1240 DoneLinkingBodies = true;
Duncan P. N. Exon Smith39423b02016-04-16 02:29:55 +00001241 Mapper.addFlags(RF_NullMapMissingGlobalValues);
Rafael Espindolacaabe222015-12-10 14:19:35 +00001242
1243 // Remap all of the named MDNodes in Src into the DstM module. We do this
1244 // after linking GlobalValues so that MDNodes that reference GlobalValues
1245 // are properly remapped.
Teresa Johnsonb703c772016-03-29 18:24:19 +00001246 linkNamedMDNodes();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001247
Teresa Johnsonb703c772016-03-29 18:24:19 +00001248 // Merge the module flags into the DstM module.
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001249 return linkModuleFlagsMetadata();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001250}
1251
1252IRMover::StructTypeKeyInfo::KeyTy::KeyTy(ArrayRef<Type *> E, bool P)
1253 : ETypes(E), IsPacked(P) {}
1254
1255IRMover::StructTypeKeyInfo::KeyTy::KeyTy(const StructType *ST)
1256 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1257
1258bool IRMover::StructTypeKeyInfo::KeyTy::operator==(const KeyTy &That) const {
Davide Italiano95339652016-06-07 14:55:04 +00001259 return IsPacked == That.IsPacked && ETypes == That.ETypes;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001260}
1261
1262bool IRMover::StructTypeKeyInfo::KeyTy::operator!=(const KeyTy &That) const {
1263 return !this->operator==(That);
1264}
1265
1266StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1267 return DenseMapInfo<StructType *>::getEmptyKey();
1268}
1269
1270StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1271 return DenseMapInfo<StructType *>::getTombstoneKey();
1272}
1273
1274unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1275 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1276 Key.IsPacked);
1277}
1278
1279unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1280 return getHashValue(KeyTy(ST));
1281}
1282
1283bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1284 const StructType *RHS) {
1285 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1286 return false;
1287 return LHS == KeyTy(RHS);
1288}
1289
1290bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1291 const StructType *RHS) {
Davide Italiano95339652016-06-07 14:55:04 +00001292 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1293 return LHS == RHS;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001294 return KeyTy(LHS) == KeyTy(RHS);
1295}
1296
1297void IRMover::IdentifiedStructTypeSet::addNonOpaque(StructType *Ty) {
1298 assert(!Ty->isOpaque());
1299 NonOpaqueStructTypes.insert(Ty);
1300}
1301
1302void IRMover::IdentifiedStructTypeSet::switchToNonOpaque(StructType *Ty) {
1303 assert(!Ty->isOpaque());
1304 NonOpaqueStructTypes.insert(Ty);
1305 bool Removed = OpaqueStructTypes.erase(Ty);
1306 (void)Removed;
1307 assert(Removed);
1308}
1309
1310void IRMover::IdentifiedStructTypeSet::addOpaque(StructType *Ty) {
1311 assert(Ty->isOpaque());
1312 OpaqueStructTypes.insert(Ty);
1313}
1314
1315StructType *
1316IRMover::IdentifiedStructTypeSet::findNonOpaque(ArrayRef<Type *> ETypes,
1317 bool IsPacked) {
1318 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1319 auto I = NonOpaqueStructTypes.find_as(Key);
Davide Italiano95339652016-06-07 14:55:04 +00001320 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001321}
1322
1323bool IRMover::IdentifiedStructTypeSet::hasType(StructType *Ty) {
1324 if (Ty->isOpaque())
1325 return OpaqueStructTypes.count(Ty);
1326 auto I = NonOpaqueStructTypes.find(Ty);
Davide Italiano95339652016-06-07 14:55:04 +00001327 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001328}
1329
Rafael Espindola9d2bfc42015-12-14 23:17:03 +00001330IRMover::IRMover(Module &M) : Composite(M) {
Rafael Espindolacaabe222015-12-10 14:19:35 +00001331 TypeFinder StructTypes;
1332 StructTypes.run(M, true);
1333 for (StructType *Ty : StructTypes) {
1334 if (Ty->isOpaque())
1335 IdentifiedStructTypes.addOpaque(Ty);
1336 else
1337 IdentifiedStructTypes.addNonOpaque(Ty);
1338 }
1339}
1340
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001341Error IRMover::move(
Rafael Espindola40358fb2016-02-16 18:50:12 +00001342 std::unique_ptr<Module> Src, ArrayRef<GlobalValue *> ValuesToLink,
Teresa Johnsonb703c772016-03-29 18:24:19 +00001343 std::function<void(GlobalValue &, ValueAdder Add)> AddLazyFor) {
Duncan P. N. Exon Smith565a0aa2016-04-17 23:30:31 +00001344 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1345 std::move(Src), ValuesToLink, AddLazyFor);
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001346 Error E = TheIRLinker.run();
Rafael Espindolacaabe222015-12-10 14:19:35 +00001347 Composite.dropTriviallyDeadConstantArrays();
Peter Collingbourne1eaa97f2016-05-27 05:21:35 +00001348 return E;
Rafael Espindolacaabe222015-12-10 14:19:35 +00001349}