LLVM 20.0.0git
IRMover.cpp
Go to the documentation of this file.
1//===- lib/Linker/IRMover.cpp ---------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
10#include "LinkDiagnosticInfo.h"
11#include "llvm/ADT/ScopeExit.h"
12#include "llvm/ADT/SetVector.h"
15#include "llvm/IR/AutoUpgrade.h"
16#include "llvm/IR/Constants.h"
19#include "llvm/IR/Function.h"
21#include "llvm/IR/GlobalValue.h"
22#include "llvm/IR/Instruction.h"
24#include "llvm/IR/Intrinsics.h"
25#include "llvm/IR/Module.h"
26#include "llvm/IR/PseudoProbe.h"
27#include "llvm/IR/TypeFinder.h"
29#include "llvm/Support/Error.h"
30#include "llvm/Support/Path.h"
33#include <optional>
34#include <utility>
35using namespace llvm;
36
37/// Most of the errors produced by this module are inconvertible StringErrors.
38/// This convenience function lets us return one of those more easily.
39static Error stringErr(const Twine &T) {
40 return make_error<StringError>(T, inconvertibleErrorCode());
41}
42
43//===----------------------------------------------------------------------===//
44// TypeMap implementation.
45//===----------------------------------------------------------------------===//
46
47namespace {
48class TypeMapTy : public ValueMapTypeRemapper {
49 /// This is a mapping from a source type to a destination type to use.
50 DenseMap<Type *, Type *> MappedTypes;
51
52 /// When checking to see if two subgraphs are isomorphic, we speculatively
53 /// add types to MappedTypes, but keep track of them here in case we need to
54 /// roll back.
55 SmallVector<Type *, 16> SpeculativeTypes;
56
57 SmallVector<StructType *, 16> SpeculativeDstOpaqueTypes;
58
59 /// This is a list of non-opaque structs in the source module that are mapped
60 /// to an opaque struct in the destination module.
61 SmallVector<StructType *, 16> SrcDefinitionsToResolve;
62
63 /// This is the set of opaque types in the destination modules who are
64 /// getting a body from the source module.
65 SmallPtrSet<StructType *, 16> DstResolvedOpaqueTypes;
66
67public:
68 TypeMapTy(IRMover::IdentifiedStructTypeSet &DstStructTypesSet)
69 : DstStructTypesSet(DstStructTypesSet) {}
70
71 IRMover::IdentifiedStructTypeSet &DstStructTypesSet;
72 /// Indicate that the specified type in the destination module is conceptually
73 /// equivalent to the specified type in the source module.
74 void addTypeMapping(Type *DstTy, Type *SrcTy);
75
76 /// Produce a body for an opaque type in the dest module from a type
77 /// definition in the source module.
78 Error linkDefinedTypeBodies();
79
80 /// Return the mapped type to use for the specified input type from the
81 /// source module.
82 Type *get(Type *SrcTy);
83 Type *get(Type *SrcTy, SmallPtrSet<StructType *, 8> &Visited);
84
86 return cast<FunctionType>(get((Type *)T));
87 }
88
89private:
90 Type *remapType(Type *SrcTy) override { return get(SrcTy); }
91
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
93};
94}
95
96void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 assert(SpeculativeTypes.empty());
98 assert(SpeculativeDstOpaqueTypes.empty());
99
100 // Check to see if these types are recursively isomorphic and establish a
101 // mapping between them if so.
102 if (!areTypesIsomorphic(DstTy, SrcTy)) {
103 // Oops, they aren't isomorphic. Just discard this request by rolling out
104 // any speculative mappings we've established.
105 for (Type *Ty : SpeculativeTypes)
106 MappedTypes.erase(Ty);
107
108 SrcDefinitionsToResolve.resize(SrcDefinitionsToResolve.size() -
109 SpeculativeDstOpaqueTypes.size());
110 for (StructType *Ty : SpeculativeDstOpaqueTypes)
111 DstResolvedOpaqueTypes.erase(Ty);
112 } else {
113 // SrcTy and DstTy are recursively ismorphic. We clear names of SrcTy
114 // and all its descendants to lower amount of renaming in LLVM context
115 // Renaming occurs because we load all source modules to the same context
116 // and declaration with existing name gets renamed (i.e Foo -> Foo.42).
117 // As a result we may get several different types in the destination
118 // module, which are in fact the same.
119 for (Type *Ty : SpeculativeTypes)
120 if (auto *STy = dyn_cast<StructType>(Ty))
121 if (STy->hasName())
122 STy->setName("");
123 }
124 SpeculativeTypes.clear();
125 SpeculativeDstOpaqueTypes.clear();
126}
127
128/// Recursively walk this pair of types, returning true if they are isomorphic,
129/// false if they are not.
130bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
131 // Two types with differing kinds are clearly not isomorphic.
132 if (DstTy->getTypeID() != SrcTy->getTypeID())
133 return false;
134
135 // If we have an entry in the MappedTypes table, then we have our answer.
136 Type *&Entry = MappedTypes[SrcTy];
137 if (Entry)
138 return Entry == DstTy;
139
140 // Two identical types are clearly isomorphic. Remember this
141 // non-speculatively.
142 if (DstTy == SrcTy) {
143 Entry = DstTy;
144 return true;
145 }
146
147 // Okay, we have two types with identical kinds that we haven't seen before.
148
149 // If this is an opaque struct type, special case it.
150 if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
151 // Mapping an opaque type to any struct, just keep the dest struct.
152 if (SSTy->isOpaque()) {
153 Entry = DstTy;
154 SpeculativeTypes.push_back(SrcTy);
155 return true;
156 }
157
158 // Mapping a non-opaque source type to an opaque dest. If this is the first
159 // type that we're mapping onto this destination type then we succeed. Keep
160 // the dest, but fill it in later. If this is the second (different) type
161 // that we're trying to map onto the same opaque type then we fail.
162 if (cast<StructType>(DstTy)->isOpaque()) {
163 // We can only map one source type onto the opaque destination type.
164 if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)).second)
165 return false;
166 SrcDefinitionsToResolve.push_back(SSTy);
167 SpeculativeTypes.push_back(SrcTy);
168 SpeculativeDstOpaqueTypes.push_back(cast<StructType>(DstTy));
169 Entry = DstTy;
170 return true;
171 }
172 }
173
174 // If the number of subtypes disagree between the two types, then we fail.
175 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
176 return false;
177
178 // Fail if any of the extra properties (e.g. array size) of the type disagree.
179 if (isa<IntegerType>(DstTy))
180 return false; // bitwidth disagrees.
181 if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
182 if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
183 return false;
184 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
185 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
186 return false;
187 } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
188 StructType *SSTy = cast<StructType>(SrcTy);
189 if (DSTy->isLiteral() != SSTy->isLiteral() ||
190 DSTy->isPacked() != SSTy->isPacked())
191 return false;
192 } else if (auto *DArrTy = dyn_cast<ArrayType>(DstTy)) {
193 if (DArrTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
194 return false;
195 } else if (auto *DVecTy = dyn_cast<VectorType>(DstTy)) {
196 if (DVecTy->getElementCount() != cast<VectorType>(SrcTy)->getElementCount())
197 return false;
198 }
199
200 // Otherwise, we speculate that these two types will line up and recursively
201 // check the subelements.
202 Entry = DstTy;
203 SpeculativeTypes.push_back(SrcTy);
204
205 for (unsigned I = 0, E = SrcTy->getNumContainedTypes(); I != E; ++I)
206 if (!areTypesIsomorphic(DstTy->getContainedType(I),
207 SrcTy->getContainedType(I)))
208 return false;
209
210 // If everything seems to have lined up, then everything is great.
211 return true;
212}
213
214Error TypeMapTy::linkDefinedTypeBodies() {
216 for (StructType *SrcSTy : SrcDefinitionsToResolve) {
217 StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
218 assert(DstSTy->isOpaque());
219
220 // Map the body of the source type over to a new body for the dest type.
221 Elements.resize(SrcSTy->getNumElements());
222 for (unsigned I = 0, E = Elements.size(); I != E; ++I)
223 Elements[I] = get(SrcSTy->getElementType(I));
224
225 if (auto E = DstSTy->setBodyOrError(Elements, SrcSTy->isPacked()))
226 return E;
227 DstStructTypesSet.switchToNonOpaque(DstSTy);
228 }
229 SrcDefinitionsToResolve.clear();
230 DstResolvedOpaqueTypes.clear();
231 return Error::success();
232}
233
234Type *TypeMapTy::get(Type *Ty) {
236 return get(Ty, Visited);
237}
238
239Type *TypeMapTy::get(Type *Ty, SmallPtrSet<StructType *, 8> &Visited) {
240 // If we already have an entry for this type, return it.
241 Type **Entry = &MappedTypes[Ty];
242 if (*Entry)
243 return *Entry;
244
245 // These are types that LLVM itself will unique.
246 bool IsUniqued = !isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral();
247
248 if (!IsUniqued) {
249#ifndef NDEBUG
250 for (auto &Pair : MappedTypes) {
251 assert(!(Pair.first != Ty && Pair.second == Ty) &&
252 "mapping to a source type");
253 }
254#endif
255
256 if (!Visited.insert(cast<StructType>(Ty)).second) {
258 return *Entry = DTy;
259 }
260 }
261
262 // If this is not a recursive type, then just map all of the elements and
263 // then rebuild the type from inside out.
264 SmallVector<Type *, 4> ElementTypes;
265
266 // If there are no element types to map, then the type is itself. This is
267 // true for the anonymous {} struct, things like 'float', integers, etc.
268 if (Ty->getNumContainedTypes() == 0 && IsUniqued)
269 return *Entry = Ty;
270
271 // Remap all of the elements, keeping track of whether any of them change.
272 bool AnyChange = false;
273 ElementTypes.resize(Ty->getNumContainedTypes());
274 for (unsigned I = 0, E = Ty->getNumContainedTypes(); I != E; ++I) {
275 ElementTypes[I] = get(Ty->getContainedType(I), Visited);
276 AnyChange |= ElementTypes[I] != Ty->getContainedType(I);
277 }
278
279 // Refresh Entry after recursively processing stuff.
280 Entry = &MappedTypes[Ty];
281 assert(!*Entry && "Recursive type!");
282
283 // If all of the element types mapped directly over and the type is not
284 // a named struct, then the type is usable as-is.
285 if (!AnyChange && IsUniqued)
286 return *Entry = Ty;
287
288 // Otherwise, rebuild a modified type.
289 switch (Ty->getTypeID()) {
290 default:
291 llvm_unreachable("unknown derived type to remap");
292 case Type::ArrayTyID:
293 return *Entry = ArrayType::get(ElementTypes[0],
294 cast<ArrayType>(Ty)->getNumElements());
297 return *Entry = VectorType::get(ElementTypes[0],
298 cast<VectorType>(Ty)->getElementCount());
300 return *Entry = PointerType::get(ElementTypes[0],
301 cast<PointerType>(Ty)->getAddressSpace());
303 return *Entry = FunctionType::get(ElementTypes[0],
304 ArrayRef(ElementTypes).slice(1),
305 cast<FunctionType>(Ty)->isVarArg());
306 case Type::StructTyID: {
307 auto *STy = cast<StructType>(Ty);
308 bool IsPacked = STy->isPacked();
309 if (IsUniqued)
310 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
311
312 // If the type is opaque, we can just use it directly.
313 if (STy->isOpaque()) {
314 DstStructTypesSet.addOpaque(STy);
315 return *Entry = Ty;
316 }
317
318 if (StructType *OldT =
319 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
320 STy->setName("");
321 return *Entry = OldT;
322 }
323
324 if (!AnyChange) {
325 DstStructTypesSet.addNonOpaque(STy);
326 return *Entry = Ty;
327 }
328
329 StructType *DTy =
330 StructType::create(Ty->getContext(), ElementTypes, "", STy->isPacked());
331
332 // Steal STy's name.
333 if (STy->hasName()) {
334 SmallString<16> TmpName = STy->getName();
335 STy->setName("");
336 DTy->setName(TmpName);
337 }
338
339 DstStructTypesSet.addNonOpaque(DTy);
340 return *Entry = DTy;
341 }
342 }
343}
344
346 const Twine &Msg)
347 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
348void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
349
350//===----------------------------------------------------------------------===//
351// IRLinker implementation.
352//===----------------------------------------------------------------------===//
353
354namespace {
355class IRLinker;
356
357/// Creates prototypes for functions that are lazily linked on the fly. This
358/// speeds up linking for modules with many/ lazily linked functions of which
359/// few get used.
360class GlobalValueMaterializer final : public ValueMaterializer {
361 IRLinker &TheIRLinker;
362
363public:
364 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
365 Value *materialize(Value *V) override;
366};
367
368class LocalValueMaterializer final : public ValueMaterializer {
369 IRLinker &TheIRLinker;
370
371public:
372 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
373 Value *materialize(Value *V) override;
374};
375
376/// Type of the Metadata map in \a ValueToValueMapTy.
378
379/// This is responsible for keeping track of the state used for moving data
380/// from SrcM to DstM.
381class IRLinker {
382 Module &DstM;
383 std::unique_ptr<Module> SrcM;
384
385 /// See IRMover::move().
386 IRMover::LazyCallback AddLazyFor;
387
388 TypeMapTy TypeMap;
389 GlobalValueMaterializer GValMaterializer;
390 LocalValueMaterializer LValMaterializer;
391
392 /// A metadata map that's shared between IRLinker instances.
393 MDMapT &SharedMDs;
394
395 /// Mapping of values from what they used to be in Src, to what they are now
396 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
397 /// due to the use of Value handles which the Linker doesn't actually need,
398 /// but this allows us to reuse the ValueMapper code.
400 ValueToValueMapTy IndirectSymbolValueMap;
401
402 DenseSet<GlobalValue *> ValuesToLink;
403 std::vector<GlobalValue *> Worklist;
404 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
405
406 /// Set of globals with eagerly copied metadata that may require remapping.
407 /// This remapping is performed after metadata linking.
408 DenseSet<GlobalObject *> UnmappedMetadata;
409
410 void maybeAdd(GlobalValue *GV) {
411 if (ValuesToLink.insert(GV).second)
412 Worklist.push_back(GV);
413 }
414
415 /// Whether we are importing globals for ThinLTO, as opposed to linking the
416 /// source module. If this flag is set, it means that we can rely on some
417 /// other object file to define any non-GlobalValue entities defined by the
418 /// source module. This currently causes us to not link retained types in
419 /// debug info metadata and module inline asm.
420 bool IsPerformingImport;
421
422 /// Set to true when all global value body linking is complete (including
423 /// lazy linking). Used to prevent metadata linking from creating new
424 /// references.
425 bool DoneLinkingBodies = false;
426
427 /// The Error encountered during materialization. We use an Optional here to
428 /// avoid needing to manage an unconsumed success value.
429 std::optional<Error> FoundError;
430 void setError(Error E) {
431 if (E)
432 FoundError = std::move(E);
433 }
434
435 /// Entry point for mapping values and alternate context for mapping aliases.
436 ValueMapper Mapper;
437 unsigned IndirectSymbolMCID;
438
439 /// Handles cloning of a global values from the source module into
440 /// the destination module, including setting the attributes and visibility.
441 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
442
443 void emitWarning(const Twine &Message) {
444 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
445 }
446
447 /// Given a global in the source module, return the global in the
448 /// destination module that is being linked to, if any.
449 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
450 // If the source has no name it can't link. If it has local linkage,
451 // there is no name match-up going on.
452 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
453 return nullptr;
454
455 // Otherwise see if we have a match in the destination module's symtab.
456 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
457 if (!DGV)
458 return nullptr;
459
460 // If we found a global with the same name in the dest module, but it has
461 // internal linkage, we are really not doing any linkage here.
462 if (DGV->hasLocalLinkage())
463 return nullptr;
464
465 // If we found an intrinsic declaration with mismatching prototypes, we
466 // probably had a nameclash. Don't use that version.
467 if (auto *FDGV = dyn_cast<Function>(DGV))
468 if (FDGV->isIntrinsic())
469 if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
470 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
471 return nullptr;
472
473 // Otherwise, we do in fact link to the destination global.
474 return DGV;
475 }
476
477 void computeTypeMapping();
478
479 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
480 const GlobalVariable *SrcGV);
481
482 /// Given the GlobaValue \p SGV in the source module, and the matching
483 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
484 /// into the destination module.
485 ///
486 /// Note this code may call the client-provided \p AddLazyFor.
487 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
488 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
489 bool ForIndirectSymbol);
490
491 Error linkModuleFlagsMetadata();
492
493 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
494 Error linkFunctionBody(Function &Dst, Function &Src);
495 void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
496 void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
497 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
498
499 /// Replace all types in the source AttributeList with the
500 /// corresponding destination type.
501 AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
502
503 /// Functions that take care of cloning a specific global value type
504 /// into the destination module.
505 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
506 Function *copyFunctionProto(const Function *SF);
507 GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
508
509 /// Perform "replace all uses with" operations. These work items need to be
510 /// performed as part of materialization, but we postpone them to happen after
511 /// materialization is done. The materializer called by ValueMapper is not
512 /// expected to delete constants, as ValueMapper is holding pointers to some
513 /// of them, but constant destruction may be indirectly triggered by RAUW.
514 /// Hence, the need to move this out of the materialization call chain.
515 void flushRAUWWorklist();
516
517 /// When importing for ThinLTO, prevent importing of types listed on
518 /// the DICompileUnit that we don't need a copy of in the importing
519 /// module.
520 void prepareCompileUnitsForImport();
521 void linkNamedMDNodes();
522
523 /// Update attributes while linking.
524 void updateAttributes(GlobalValue &GV);
525
526public:
527 IRLinker(Module &DstM, MDMapT &SharedMDs,
528 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
529 ArrayRef<GlobalValue *> ValuesToLink,
530 IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
531 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
532 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
533 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
535 &TypeMap, &GValMaterializer),
536 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
537 IndirectSymbolValueMap, &LValMaterializer)) {
538 ValueMap.getMDMap() = std::move(SharedMDs);
539 for (GlobalValue *GV : ValuesToLink)
540 maybeAdd(GV);
541 if (IsPerformingImport)
542 prepareCompileUnitsForImport();
543 }
544 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
545
546 Error run();
547 Value *materialize(Value *V, bool ForIndirectSymbol);
548};
549}
550
551/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
552/// table. This is good for all clients except for us. Go through the trouble
553/// to force this back.
555 // If the global doesn't force its name or if it already has the right name,
556 // there is nothing for us to do.
557 if (GV->hasLocalLinkage() || GV->getName() == Name)
558 return;
559
560 Module *M = GV->getParent();
561
562 // If there is a conflict, rename the conflict.
563 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
564 GV->takeName(ConflictGV);
565 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
566 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
567 } else {
568 GV->setName(Name); // Force the name back
569 }
570}
571
572Value *GlobalValueMaterializer::materialize(Value *SGV) {
573 return TheIRLinker.materialize(SGV, false);
574}
575
576Value *LocalValueMaterializer::materialize(Value *SGV) {
577 return TheIRLinker.materialize(SGV, true);
578}
579
580Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
581 auto *SGV = dyn_cast<GlobalValue>(V);
582 if (!SGV)
583 return nullptr;
584
585 // If SGV is from dest, it was already materialized when dest was loaded.
586 if (SGV->getParent() == &DstM)
587 return nullptr;
588
589 // When linking a global from other modules than source & dest, skip
590 // materializing it because it would be mapped later when its containing
591 // module is linked. Linking it now would potentially pull in many types that
592 // may not be mapped properly.
593 if (SGV->getParent() != SrcM.get())
594 return nullptr;
595
596 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
597 if (!NewProto) {
598 setError(NewProto.takeError());
599 return nullptr;
600 }
601 if (!*NewProto)
602 return nullptr;
603
604 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
605 if (!New)
606 return *NewProto;
607
608 // If we already created the body, just return.
609 if (auto *F = dyn_cast<Function>(New)) {
610 if (!F->isDeclaration())
611 return New;
612 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
613 if (V->hasInitializer() || V->hasAppendingLinkage())
614 return New;
615 } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
616 if (GA->getAliasee())
617 return New;
618 } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
619 if (GI->getResolver())
620 return New;
621 } else {
622 llvm_unreachable("Invalid GlobalValue type");
623 }
624
625 // If the global is being linked for an indirect symbol, it may have already
626 // been scheduled to satisfy a regular symbol. Similarly, a global being linked
627 // for a regular symbol may have already been scheduled for an indirect
628 // symbol. Check for these cases by looking in the other value map and
629 // confirming the same value has been scheduled. If there is an entry in the
630 // ValueMap but the value is different, it means that the value already had a
631 // definition in the destination module (linkonce for instance), but we need a
632 // new definition for the indirect symbol ("New" will be different).
633 if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
634 (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
635 return New;
636
637 if (ForIndirectSymbol || shouldLink(New, *SGV))
638 setError(linkGlobalValueBody(*New, *SGV));
639
640 updateAttributes(*New);
641 return New;
642}
643
644/// Loop through the global variables in the src module and merge them into the
645/// dest module.
646GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
647 // No linking to be performed or linking from the source: simply create an
648 // identical version of the symbol over in the dest module... the
649 // initializer will be filled in later by LinkGlobalInits.
650 GlobalVariable *NewDGV =
651 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
653 /*init*/ nullptr, SGVar->getName(),
654 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
655 SGVar->getAddressSpace());
656 NewDGV->setAlignment(SGVar->getAlign());
657 NewDGV->copyAttributesFrom(SGVar);
658 return NewDGV;
659}
660
661AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
662 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
663 for (int AttrIdx = Attribute::FirstTypeAttr;
664 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
665 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
666 if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
667 if (Type *Ty =
668 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
669 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
670 TypeMap.get(Ty));
671 break;
672 }
673 }
674 }
675 }
676 return Attrs;
677}
678
679/// Link the function in the source module into the destination module if
680/// needed, setting up mapping information.
681Function *IRLinker::copyFunctionProto(const Function *SF) {
682 // If there is no linkage to be performed or we are linking from the source,
683 // bring SF over.
684 auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
686 SF->getAddressSpace(), SF->getName(), &DstM);
687 F->copyAttributesFrom(SF);
688 F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
689 F->IsNewDbgInfoFormat = SF->IsNewDbgInfoFormat;
690 return F;
691}
692
693/// Set up prototypes for any indirect symbols that come over from the source
694/// module.
695GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
696 // If there is no linkage to be performed or we're linking from the source,
697 // bring over SGA.
698 auto *Ty = TypeMap.get(SGV->getValueType());
699
700 if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
701 auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
703 SGV->getName(), &DstM);
704 DGA->copyAttributesFrom(GA);
705 return DGA;
706 }
707
708 if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
709 auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
711 SGV->getName(), nullptr, &DstM);
712 DGI->copyAttributesFrom(GI);
713 return DGI;
714 }
715
716 llvm_unreachable("Invalid source global value type");
717}
718
719GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
720 bool ForDefinition) {
721 GlobalValue *NewGV;
722 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
723 NewGV = copyGlobalVariableProto(SGVar);
724 } else if (auto *SF = dyn_cast<Function>(SGV)) {
725 NewGV = copyFunctionProto(SF);
726 } else {
727 if (ForDefinition)
728 NewGV = copyIndirectSymbolProto(SGV);
729 else if (SGV->getValueType()->isFunctionTy())
730 NewGV =
731 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
733 SGV->getName(), &DstM);
734 else
735 NewGV =
736 new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
737 /*isConstant*/ false, GlobalValue::ExternalLinkage,
738 /*init*/ nullptr, SGV->getName(),
739 /*insertbefore*/ nullptr,
740 SGV->getThreadLocalMode(), SGV->getAddressSpace());
741 }
742
743 if (ForDefinition)
744 NewGV->setLinkage(SGV->getLinkage());
745 else if (SGV->hasExternalWeakLinkage())
747
748 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
749 // Metadata for global variables and function declarations is copied eagerly.
750 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) {
751 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
752 if (SGV->isDeclaration() && NewGO->hasMetadata())
753 UnmappedMetadata.insert(NewGO);
754 }
755 }
756
757 // Remove these copied constants in case this stays a declaration, since
758 // they point to the source module. If the def is linked the values will
759 // be mapped in during linkFunctionBody.
760 if (auto *NewF = dyn_cast<Function>(NewGV)) {
761 NewF->setPersonalityFn(nullptr);
762 NewF->setPrefixData(nullptr);
763 NewF->setPrologueData(nullptr);
764 }
765
766 return NewGV;
767}
768
770 size_t DotPos = Name.rfind('.');
771 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
772 !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
773 ? Name
774 : Name.substr(0, DotPos);
775}
776
777/// Loop over all of the linked values to compute type mappings. For example,
778/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
779/// types 'Foo' but one got renamed when the module was loaded into the same
780/// LLVMContext.
781void IRLinker::computeTypeMapping() {
782 for (GlobalValue &SGV : SrcM->globals()) {
783 GlobalValue *DGV = getLinkedToGlobal(&SGV);
784 if (!DGV)
785 continue;
786
787 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
788 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
789 continue;
790 }
791
792 // Unify the element type of appending arrays.
793 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
794 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
795 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
796 }
797
798 for (GlobalValue &SGV : *SrcM)
799 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
800 if (DGV->getType() == SGV.getType()) {
801 // If the types of DGV and SGV are the same, it means that DGV is from
802 // the source module and got added to DstM from a shared metadata. We
803 // shouldn't map this type to itself in case the type's components get
804 // remapped to a new type from DstM (for instance, during the loop over
805 // SrcM->getIdentifiedStructTypes() below).
806 continue;
807 }
808
809 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
810 }
811
812 for (GlobalValue &SGV : SrcM->aliases())
813 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
814 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
815
816 // Incorporate types by name, scanning all the types in the source module.
817 // At this point, the destination module may have a type "%foo = { i32 }" for
818 // example. When the source module got loaded into the same LLVMContext, if
819 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
820 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
821 for (StructType *ST : Types) {
822 if (!ST->hasName())
823 continue;
824
825 if (TypeMap.DstStructTypesSet.hasType(ST)) {
826 // This is actually a type from the destination module.
827 // getIdentifiedStructTypes() can have found it by walking debug info
828 // metadata nodes, some of which get linked by name when ODR Type Uniquing
829 // is enabled on the Context, from the source to the destination module.
830 continue;
831 }
832
833 auto STTypePrefix = getTypeNamePrefix(ST->getName());
834 if (STTypePrefix.size() == ST->getName().size())
835 continue;
836
837 // Check to see if the destination module has a struct with the prefix name.
838 StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
839 if (!DST)
840 continue;
841
842 // Don't use it if this actually came from the source module. They're in
843 // the same LLVMContext after all. Also don't use it unless the type is
844 // actually used in the destination module. This can happen in situations
845 // like this:
846 //
847 // Module A Module B
848 // -------- --------
849 // %Z = type { %A } %B = type { %C.1 }
850 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
851 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
852 // %C = type { i8* } %B.3 = type { %C.1 }
853 //
854 // When we link Module B with Module A, the '%B' in Module B is
855 // used. However, that would then use '%C.1'. But when we process '%C.1',
856 // we prefer to take the '%C' version. So we are then left with both
857 // '%C.1' and '%C' being used for the same types. This leads to some
858 // variables using one type and some using the other.
859 if (TypeMap.DstStructTypesSet.hasType(DST))
860 TypeMap.addTypeMapping(DST, ST);
861 }
862
863 // Now that we have discovered all of the type equivalences, get a body for
864 // any 'opaque' types in the dest module that are now resolved.
865 setError(TypeMap.linkDefinedTypeBodies());
866}
867
868static void getArrayElements(const Constant *C,
870 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
871
872 for (unsigned i = 0; i != NumElements; ++i)
873 Dest.push_back(C->getAggregateElement(i));
874}
875
876/// If there were any appending global variables, link them together now.
878IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
879 const GlobalVariable *SrcGV) {
880 // Check that both variables have compatible properties.
881 if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
882 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
883 return stringErr(
884 "Linking globals named '" + SrcGV->getName() +
885 "': can only link appending global with another appending "
886 "global!");
887
888 if (DstGV->isConstant() != SrcGV->isConstant())
889 return stringErr("Appending variables linked with different const'ness!");
890
891 if (DstGV->getAlign() != SrcGV->getAlign())
892 return stringErr(
893 "Appending variables with different alignment need to be linked!");
894
895 if (DstGV->getVisibility() != SrcGV->getVisibility())
896 return stringErr(
897 "Appending variables with different visibility need to be linked!");
898
899 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
900 return stringErr(
901 "Appending variables with different unnamed_addr need to be linked!");
902
903 if (DstGV->getSection() != SrcGV->getSection())
904 return stringErr(
905 "Appending variables with different section name need to be linked!");
906
907 if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
908 return stringErr("Appending variables with different address spaces need "
909 "to be linked!");
910 }
911
912 // Do not need to do anything if source is a declaration.
913 if (SrcGV->isDeclaration())
914 return DstGV;
915
916 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
917 ->getElementType();
918
919 // FIXME: This upgrade is done during linking to support the C API. Once the
920 // old form is deprecated, we should move this upgrade to
921 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
922 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
923 StringRef Name = SrcGV->getName();
924 bool IsNewStructor = false;
925 bool IsOldStructor = false;
926 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
927 if (cast<StructType>(EltTy)->getNumElements() == 3)
928 IsNewStructor = true;
929 else
930 IsOldStructor = true;
931 }
932
933 PointerType *VoidPtrTy = PointerType::get(SrcGV->getContext(), 0);
934 if (IsOldStructor) {
935 auto &ST = *cast<StructType>(EltTy);
936 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
937 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
938 }
939
940 uint64_t DstNumElements = 0;
941 if (DstGV && !DstGV->isDeclaration()) {
942 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
943 DstNumElements = DstTy->getNumElements();
944
945 // Check to see that they two arrays agree on type.
946 if (EltTy != DstTy->getElementType())
947 return stringErr("Appending variables with different element types!");
948 }
949
950 SmallVector<Constant *, 16> SrcElements;
951 getArrayElements(SrcGV->getInitializer(), SrcElements);
952
953 if (IsNewStructor) {
954 erase_if(SrcElements, [this](Constant *E) {
955 auto *Key =
956 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
957 if (!Key)
958 return false;
959 GlobalValue *DGV = getLinkedToGlobal(Key);
960 return !shouldLink(DGV, *Key);
961 });
962 }
963 uint64_t NewSize = DstNumElements + SrcElements.size();
964 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
965
966 // Create the new global variable.
968 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
969 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
970 SrcGV->getAddressSpace());
971
972 NG->copyAttributesFrom(SrcGV);
973 forceRenaming(NG, SrcGV->getName());
974
975 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
976
978 *NG,
979 (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
980 IsOldStructor, SrcElements);
981
982 // Replace any uses of the two global variables with uses of the new
983 // global.
984 if (DstGV) {
985 RAUWWorklist.push_back(std::make_pair(DstGV, NG));
986 }
987
988 return Ret;
989}
990
991bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
992 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
993 return true;
994
995 if (DGV && !DGV->isDeclarationForLinker())
996 return false;
997
998 if (SGV.isDeclaration() || DoneLinkingBodies)
999 return false;
1000
1001 // Callback to the client to give a chance to lazily add the Global to the
1002 // list of value to link.
1003 bool LazilyAdded = false;
1004 if (AddLazyFor)
1005 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1006 maybeAdd(&GV);
1007 LazilyAdded = true;
1008 });
1009 return LazilyAdded;
1010}
1011
1012Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1013 bool ForIndirectSymbol) {
1014 GlobalValue *DGV = getLinkedToGlobal(SGV);
1015
1016 bool ShouldLink = shouldLink(DGV, *SGV);
1017
1018 // just missing from map
1019 if (ShouldLink) {
1020 auto I = ValueMap.find(SGV);
1021 if (I != ValueMap.end())
1022 return cast<Constant>(I->second);
1023
1024 I = IndirectSymbolValueMap.find(SGV);
1025 if (I != IndirectSymbolValueMap.end())
1026 return cast<Constant>(I->second);
1027 }
1028
1029 if (!ShouldLink && ForIndirectSymbol)
1030 DGV = nullptr;
1031
1032 // Handle the ultra special appending linkage case first.
1033 if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
1034 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1035 cast<GlobalVariable>(SGV));
1036
1037 bool NeedsRenaming = false;
1038 GlobalValue *NewGV;
1039 if (DGV && !ShouldLink) {
1040 NewGV = DGV;
1041 } else {
1042 // If we are done linking global value bodies (i.e. we are performing
1043 // metadata linking), don't link in the global value due to this
1044 // reference, simply map it to null.
1045 if (DoneLinkingBodies)
1046 return nullptr;
1047
1048 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1049 if (ShouldLink || !ForIndirectSymbol)
1050 NeedsRenaming = true;
1051 }
1052
1053 // Overloaded intrinsics have overloaded types names as part of their
1054 // names. If we renamed overloaded types we should rename the intrinsic
1055 // as well.
1056 if (Function *F = dyn_cast<Function>(NewGV))
1057 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
1058 // Note: remangleIntrinsicFunction does not copy metadata and as such
1059 // F should not occur in the set of objects with unmapped metadata.
1060 // If this assertion fails then remangleIntrinsicFunction needs updating.
1061 assert(!UnmappedMetadata.count(F) && "intrinsic has unmapped metadata");
1062 NewGV->eraseFromParent();
1063 NewGV = *Remangled;
1064 NeedsRenaming = false;
1065 }
1066
1067 if (NeedsRenaming)
1068 forceRenaming(NewGV, SGV->getName());
1069
1070 if (ShouldLink || ForIndirectSymbol) {
1071 if (const Comdat *SC = SGV->getComdat()) {
1072 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1073 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1074 DC->setSelectionKind(SC->getSelectionKind());
1075 GO->setComdat(DC);
1076 }
1077 }
1078 }
1079
1080 if (!ShouldLink && ForIndirectSymbol)
1082
1083 Constant *C = NewGV;
1084 // Only create a bitcast if necessary. In particular, with
1085 // DebugTypeODRUniquing we may reach metadata in the destination module
1086 // containing a GV from the source module, in which case SGV will be
1087 // the same as DGV and NewGV, and TypeMap.get() will assert since it
1088 // assumes it is being invoked on a type in the source module.
1089 if (DGV && NewGV != SGV) {
1091 NewGV, TypeMap.get(SGV->getType()));
1092 }
1093
1094 if (DGV && NewGV != DGV) {
1095 // Schedule "replace all uses with" to happen after materializing is
1096 // done. It is not safe to do it now, since ValueMapper may be holding
1097 // pointers to constants that will get deleted if RAUW runs.
1098 RAUWWorklist.push_back(std::make_pair(
1099 DGV,
1101 }
1102
1103 return C;
1104}
1105
1106/// Update the initializers in the Dest module now that all globals that may be
1107/// referenced are in Dest.
1108void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1109 // Figure out what the initializer looks like in the dest module.
1110 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1111}
1112
1113/// Copy the source function over into the dest function and fix up references
1114/// to values. At this point we know that Dest is an external function, and
1115/// that Src is not.
1116Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1117 assert(Dst.isDeclaration() && !Src.isDeclaration());
1118
1119 // Materialize if needed.
1120 if (Error Err = Src.materialize())
1121 return Err;
1122
1123 // Link in the operands without remapping.
1124 if (Src.hasPrefixData())
1125 Dst.setPrefixData(Src.getPrefixData());
1126 if (Src.hasPrologueData())
1127 Dst.setPrologueData(Src.getPrologueData());
1128 if (Src.hasPersonalityFn())
1129 Dst.setPersonalityFn(Src.getPersonalityFn());
1130 assert(Src.IsNewDbgInfoFormat == Dst.IsNewDbgInfoFormat);
1131
1132 // Copy over the metadata attachments without remapping.
1133 Dst.copyMetadata(&Src, 0);
1134
1135 // Steal arguments and splice the body of Src into Dst.
1136 Dst.stealArgumentListFrom(Src);
1137 Dst.splice(Dst.end(), &Src);
1138
1139 // Everything has been moved over. Remap it.
1140 Mapper.scheduleRemapFunction(Dst);
1141 return Error::success();
1142}
1143
1144void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1145 Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1146}
1147
1148void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1149 Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1150}
1151
1152Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1153 if (auto *F = dyn_cast<Function>(&Src))
1154 return linkFunctionBody(cast<Function>(Dst), *F);
1155 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1156 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1157 return Error::success();
1158 }
1159 if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1160 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1161 return Error::success();
1162 }
1163 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1164 return Error::success();
1165}
1166
1167void IRLinker::flushRAUWWorklist() {
1168 for (const auto &Elem : RAUWWorklist) {
1169 GlobalValue *Old;
1170 Value *New;
1171 std::tie(Old, New) = Elem;
1172
1173 Old->replaceAllUsesWith(New);
1174 Old->eraseFromParent();
1175 }
1176 RAUWWorklist.clear();
1177}
1178
1179void IRLinker::prepareCompileUnitsForImport() {
1180 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1181 if (!SrcCompileUnits)
1182 return;
1183 // When importing for ThinLTO, prevent importing of types listed on
1184 // the DICompileUnit that we don't need a copy of in the importing
1185 // module. They will be emitted by the originating module.
1186 for (MDNode *N : SrcCompileUnits->operands()) {
1187 auto *CU = cast<DICompileUnit>(N);
1188 assert(CU && "Expected valid compile unit");
1189 // Enums, macros, and retained types don't need to be listed on the
1190 // imported DICompileUnit. This means they will only be imported
1191 // if reached from the mapped IR.
1192 CU->replaceEnumTypes(nullptr);
1193 CU->replaceMacros(nullptr);
1194 CU->replaceRetainedTypes(nullptr);
1195
1196 // The original definition (or at least its debug info - if the variable is
1197 // internalized and optimized away) will remain in the source module, so
1198 // there's no need to import them.
1199 // If LLVM ever does more advanced optimizations on global variables
1200 // (removing/localizing write operations, for instance) that can track
1201 // through debug info, this decision may need to be revisited - but do so
1202 // with care when it comes to debug info size. Emitting small CUs containing
1203 // only a few imported entities into every destination module may be very
1204 // size inefficient.
1205 CU->replaceGlobalVariables(nullptr);
1206
1207 CU->replaceImportedEntities(nullptr);
1208 }
1209}
1210
1211/// Insert all of the named MDNodes in Src into the Dest module.
1212void IRLinker::linkNamedMDNodes() {
1213 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1214 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1215 // Don't link module flags here. Do them separately.
1216 if (&NMD == SrcModFlags)
1217 continue;
1218 // Don't import pseudo probe descriptors here for thinLTO. They will be
1219 // emitted by the originating module.
1220 if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
1221 if (!DstM.getNamedMetadata(NMD.getName()))
1222 emitWarning("Pseudo-probe ignored: source module '" +
1223 SrcM->getModuleIdentifier() +
1224 "' is compiled with -fpseudo-probe-for-profiling while "
1225 "destination module '" +
1226 DstM.getModuleIdentifier() + "' is not\n");
1227 continue;
1228 }
1229 // The stats are computed per module and will all be merged in the binary.
1230 // Importing the metadata will cause duplication of the stats.
1231 if (IsPerformingImport && NMD.getName() == "llvm.stats")
1232 continue;
1233
1234 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1235 // Add Src elements into Dest node.
1236 for (const MDNode *Op : NMD.operands())
1237 DestNMD->addOperand(Mapper.mapMDNode(*Op));
1238 }
1239}
1240
1241/// Merge the linker flags in Src into the Dest module.
1242Error IRLinker::linkModuleFlagsMetadata() {
1243 // If the source module has no module flags, we are done.
1244 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1245 if (!SrcModFlags)
1246 return Error::success();
1247
1248 // Check for module flag for updates before do anything.
1249 UpgradeModuleFlags(*SrcM);
1250
1251 // If the destination module doesn't have module flags yet, then just copy
1252 // over the source module's flags.
1253 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1254 if (DstModFlags->getNumOperands() == 0) {
1255 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1256 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1257
1258 return Error::success();
1259 }
1260
1261 // First build a map of the existing module flags and requirements.
1263 SmallSetVector<MDNode *, 16> Requirements;
1265 DenseSet<MDString *> SeenMin;
1266 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1267 MDNode *Op = DstModFlags->getOperand(I);
1268 uint64_t Behavior =
1269 mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1270 MDString *ID = cast<MDString>(Op->getOperand(1));
1271
1272 if (Behavior == Module::Require) {
1273 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1274 } else {
1275 if (Behavior == Module::Min)
1276 Mins.push_back(I);
1277 Flags[ID] = std::make_pair(Op, I);
1278 }
1279 }
1280
1281 // Merge in the flags from the source module, and also collect its set of
1282 // requirements.
1283 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1284 MDNode *SrcOp = SrcModFlags->getOperand(I);
1285 ConstantInt *SrcBehavior =
1286 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1287 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1288 MDNode *DstOp;
1289 unsigned DstIndex;
1290 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1291 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1292 SeenMin.insert(ID);
1293
1294 // If this is a requirement, add it and continue.
1295 if (SrcBehaviorValue == Module::Require) {
1296 // If the destination module does not already have this requirement, add
1297 // it.
1298 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1299 DstModFlags->addOperand(SrcOp);
1300 }
1301 continue;
1302 }
1303
1304 // If there is no existing flag with this ID, just add it.
1305 if (!DstOp) {
1306 if (SrcBehaviorValue == Module::Min) {
1307 Mins.push_back(DstModFlags->getNumOperands());
1308 SeenMin.erase(ID);
1309 }
1310 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1311 DstModFlags->addOperand(SrcOp);
1312 continue;
1313 }
1314
1315 // Otherwise, perform a merge.
1316 ConstantInt *DstBehavior =
1317 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1318 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1319
1320 auto overrideDstValue = [&]() {
1321 DstModFlags->setOperand(DstIndex, SrcOp);
1322 Flags[ID].first = SrcOp;
1323 };
1324
1325 // If either flag has override behavior, handle it first.
1326 if (DstBehaviorValue == Module::Override) {
1327 // Diagnose inconsistent flags which both have override behavior.
1328 if (SrcBehaviorValue == Module::Override &&
1329 SrcOp->getOperand(2) != DstOp->getOperand(2))
1330 return stringErr("linking module flags '" + ID->getString() +
1331 "': IDs have conflicting override values in '" +
1332 SrcM->getModuleIdentifier() + "' and '" +
1333 DstM.getModuleIdentifier() + "'");
1334 continue;
1335 } else if (SrcBehaviorValue == Module::Override) {
1336 // Update the destination flag to that of the source.
1337 overrideDstValue();
1338 continue;
1339 }
1340
1341 // Diagnose inconsistent merge behavior types.
1342 if (SrcBehaviorValue != DstBehaviorValue) {
1343 bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1344 DstBehaviorValue == Module::Warning) ||
1345 (DstBehaviorValue == Module::Min &&
1346 SrcBehaviorValue == Module::Warning);
1347 bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1348 DstBehaviorValue == Module::Warning) ||
1349 (DstBehaviorValue == Module::Max &&
1350 SrcBehaviorValue == Module::Warning);
1351 if (!(MaxAndWarn || MinAndWarn))
1352 return stringErr("linking module flags '" + ID->getString() +
1353 "': IDs have conflicting behaviors in '" +
1354 SrcM->getModuleIdentifier() + "' and '" +
1355 DstM.getModuleIdentifier() + "'");
1356 }
1357
1358 auto ensureDistinctOp = [&](MDNode *DstValue) {
1359 assert(isa<MDTuple>(DstValue) &&
1360 "Expected MDTuple when appending module flags");
1361 if (DstValue->isDistinct())
1362 return dyn_cast<MDTuple>(DstValue);
1363 ArrayRef<MDOperand> DstOperands = DstValue->operands();
1365 DstM.getContext(), SmallVector<Metadata *, 4>(DstOperands));
1366 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1367 MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1368 DstModFlags->setOperand(DstIndex, Flag);
1369 Flags[ID].first = Flag;
1370 return New;
1371 };
1372
1373 // Emit a warning if the values differ and either source or destination
1374 // request Warning behavior.
1375 if ((DstBehaviorValue == Module::Warning ||
1376 SrcBehaviorValue == Module::Warning) &&
1377 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1378 std::string Str;
1380 << "linking module flags '" << ID->getString()
1381 << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1382 << "' from " << SrcM->getModuleIdentifier() << " with '"
1383 << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1384 << ')';
1385 emitWarning(Str);
1386 }
1387
1388 // Choose the minimum if either source or destination request Min behavior.
1389 if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1390 ConstantInt *DstValue =
1391 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1392 ConstantInt *SrcValue =
1393 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1394
1395 // The resulting flag should have a Min behavior, and contain the minimum
1396 // value from between the source and destination values.
1397 Metadata *FlagOps[] = {
1398 (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1399 (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1400 ->getOperand(2)};
1401 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1402 DstModFlags->setOperand(DstIndex, Flag);
1403 Flags[ID].first = Flag;
1404 continue;
1405 }
1406
1407 // Choose the maximum if either source or destination request Max behavior.
1408 if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1409 ConstantInt *DstValue =
1410 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1411 ConstantInt *SrcValue =
1412 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1413
1414 // The resulting flag should have a Max behavior, and contain the maximum
1415 // value from between the source and destination values.
1416 Metadata *FlagOps[] = {
1417 (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1418 (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1419 ->getOperand(2)};
1420 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1421 DstModFlags->setOperand(DstIndex, Flag);
1422 Flags[ID].first = Flag;
1423 continue;
1424 }
1425
1426 // Perform the merge for standard behavior types.
1427 switch (SrcBehaviorValue) {
1428 case Module::Require:
1429 case Module::Override:
1430 llvm_unreachable("not possible");
1431 case Module::Error: {
1432 // Emit an error if the values differ.
1433 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1434 std::string Str;
1436 << "linking module flags '" << ID->getString()
1437 << "': IDs have conflicting values: '" << *SrcOp->getOperand(2)
1438 << "' from " << SrcM->getModuleIdentifier() << ", and '"
1439 << *DstOp->getOperand(2) << "' from " + DstM.getModuleIdentifier();
1440 return stringErr(Str);
1441 }
1442 continue;
1443 }
1444 case Module::Warning: {
1445 break;
1446 }
1447 case Module::Max: {
1448 break;
1449 }
1450 case Module::Append: {
1451 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1452 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1453 for (const auto &O : SrcValue->operands())
1454 DstValue->push_back(O);
1455 break;
1456 }
1457 case Module::AppendUnique: {
1459 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1460 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1461 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1462 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1463 for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1464 DstValue->push_back(Elts[I]);
1465 break;
1466 }
1467 }
1468
1469 }
1470
1471 // For the Min behavior, set the value to 0 if either module does not have the
1472 // flag.
1473 for (auto Idx : Mins) {
1474 MDNode *Op = DstModFlags->getOperand(Idx);
1475 MDString *ID = cast<MDString>(Op->getOperand(1));
1476 if (!SeenMin.count(ID)) {
1477 ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1478 Metadata *FlagOps[] = {
1479 Op->getOperand(0), ID,
1480 ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1481 DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1482 }
1483 }
1484
1485 // Check all of the requirements.
1486 for (MDNode *Requirement : Requirements) {
1487 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1488 Metadata *ReqValue = Requirement->getOperand(1);
1489
1490 MDNode *Op = Flags[Flag].first;
1491 if (!Op || Op->getOperand(2) != ReqValue)
1492 return stringErr("linking module flags '" + Flag->getString() +
1493 "': does not have the required value");
1494 }
1495 return Error::success();
1496}
1497
1498/// Return InlineAsm adjusted with target-specific directives if required.
1499/// For ARM and Thumb, we have to add directives to select the appropriate ISA
1500/// to support mixing module-level inline assembly from ARM and Thumb modules.
1501static std::string adjustInlineAsm(const std::string &InlineAsm,
1502 const Triple &Triple) {
1504 return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1506 return ".text\n.balign 4\n.arm\n" + InlineAsm;
1507 return InlineAsm;
1508}
1509
1510void IRLinker::updateAttributes(GlobalValue &GV) {
1511 /// Remove nocallback attribute while linking, because nocallback attribute
1512 /// indicates that the function is only allowed to jump back into caller's
1513 /// module only by a return or an exception. When modules are linked, this
1514 /// property cannot be guaranteed anymore. For example, the nocallback
1515 /// function may contain a call to another module. But if we merge its caller
1516 /// and callee module here, and not the module containing the nocallback
1517 /// function definition itself, the nocallback property will be violated
1518 /// (since the nocallback function will call back into the newly merged module
1519 /// containing both its caller and callee). This could happen if the module
1520 /// containing the nocallback function definition is native code, so it does
1521 /// not participate in the LTO link. Note if the nocallback function does
1522 /// participate in the LTO link, and thus ends up in the merged module
1523 /// containing its caller and callee, removing the attribute doesn't hurt as
1524 /// it has no effect on definitions in the same module.
1525 if (auto *F = dyn_cast<Function>(&GV)) {
1526 if (!F->isIntrinsic())
1527 F->removeFnAttr(llvm::Attribute::NoCallback);
1528
1529 // Remove nocallback attribute when it is on a call-site.
1530 for (BasicBlock &BB : *F)
1531 for (Instruction &I : BB)
1532 if (CallBase *CI = dyn_cast<CallBase>(&I))
1533 CI->removeFnAttr(Attribute::NoCallback);
1534 }
1535}
1536
1537Error IRLinker::run() {
1538 // Ensure metadata materialized before value mapping.
1539 if (SrcM->getMaterializer())
1540 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1541 return Err;
1542
1543 // Convert source module to match dest for the duration of the link.
1544 ScopedDbgInfoFormatSetter FormatSetter(*SrcM, DstM.IsNewDbgInfoFormat);
1545
1546 // Inherit the target data from the source module if the destination
1547 // module doesn't have one already.
1548 if (DstM.getDataLayout().isDefault())
1549 DstM.setDataLayout(SrcM->getDataLayout());
1550
1551 // Copy the target triple from the source to dest if the dest's is empty.
1552 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1553 DstM.setTargetTriple(SrcM->getTargetTriple());
1554
1555 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1556
1557 // During CUDA compilation we have to link with the bitcode supplied with
1558 // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1559 // the layout that is different from the one used by LLVM/clang (it does not
1560 // include i128). Issuing a warning is not very helpful as there's not much
1561 // the user can do about it.
1562 bool EnableDLWarning = true;
1563 bool EnableTripleWarning = true;
1564 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1565 std::string ModuleId = SrcM->getModuleIdentifier();
1566 StringRef FileName = llvm::sys::path::filename(ModuleId);
1567 bool SrcIsLibDevice =
1568 FileName.starts_with("libdevice") && FileName.ends_with(".10.bc");
1569 bool SrcHasLibDeviceDL =
1570 (SrcM->getDataLayoutStr().empty() ||
1571 SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1572 // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1573 // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1574 // all NVPTX variants.
1575 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1576 SrcTriple.getOSName() == "gpulibs") ||
1577 (SrcTriple.getVendorName() == "unknown" &&
1578 SrcTriple.getOSName() == "unknown");
1579 EnableTripleWarning = !(SrcIsLibDevice && SrcHasLibDeviceTriple);
1580 EnableDLWarning = !(SrcIsLibDevice && SrcHasLibDeviceDL);
1581 }
1582
1583 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1584 emitWarning("Linking two modules of different data layouts: '" +
1585 SrcM->getModuleIdentifier() + "' is '" +
1586 SrcM->getDataLayoutStr() + "' whereas '" +
1587 DstM.getModuleIdentifier() + "' is '" +
1588 DstM.getDataLayoutStr() + "'\n");
1589 }
1590
1591 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1592 !SrcTriple.isCompatibleWith(DstTriple))
1593 emitWarning("Linking two modules of different target triples: '" +
1594 SrcM->getModuleIdentifier() + "' is '" +
1595 SrcM->getTargetTriple() + "' whereas '" +
1596 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1597 "'\n");
1598
1599 DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1600
1601 // Loop over all of the linked values to compute type mappings.
1602 computeTypeMapping();
1603
1604 std::reverse(Worklist.begin(), Worklist.end());
1605 while (!Worklist.empty()) {
1606 GlobalValue *GV = Worklist.back();
1607 Worklist.pop_back();
1608
1609 // Already mapped.
1610 if (ValueMap.find(GV) != ValueMap.end() ||
1611 IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1612 continue;
1613
1614 assert(!GV->isDeclaration());
1615 Mapper.mapValue(*GV);
1616 if (FoundError)
1617 return std::move(*FoundError);
1618 flushRAUWWorklist();
1619 }
1620
1621 // Note that we are done linking global value bodies. This prevents
1622 // metadata linking from creating new references.
1623 DoneLinkingBodies = true;
1625
1626 // Remap all of the named MDNodes in Src into the DstM module. We do this
1627 // after linking GlobalValues so that MDNodes that reference GlobalValues
1628 // are properly remapped.
1629 linkNamedMDNodes();
1630
1631 // Clean up any global objects with potentially unmapped metadata.
1632 // Specifically declarations which did not become definitions.
1633 for (GlobalObject *NGO : UnmappedMetadata) {
1634 if (NGO->isDeclaration())
1635 Mapper.remapGlobalObjectMetadata(*NGO);
1636 }
1637
1638 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1639 // Append the module inline asm string.
1640 DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1641 SrcTriple));
1642 } else if (IsPerformingImport) {
1643 // Import any symver directives for symbols in DstM.
1645 [&](StringRef Name, StringRef Alias) {
1646 if (DstM.getNamedValue(Name)) {
1647 SmallString<256> S(".symver ");
1648 S += Name;
1649 S += ", ";
1650 S += Alias;
1651 DstM.appendModuleInlineAsm(S);
1652 }
1653 });
1654 }
1655
1656 // Reorder the globals just added to the destination module to match their
1657 // original order in the source module.
1658 for (GlobalVariable &GV : SrcM->globals()) {
1659 if (GV.hasAppendingLinkage())
1660 continue;
1661 Value *NewValue = Mapper.mapValue(GV);
1662 if (NewValue) {
1663 auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1664 if (NewGV) {
1665 NewGV->removeFromParent();
1666 DstM.insertGlobalVariable(NewGV);
1667 }
1668 }
1669 }
1670
1671 // Merge the module flags into the DstM module.
1672 return linkModuleFlagsMetadata();
1673}
1674
1676 : ETypes(E), IsPacked(P) {}
1677
1679 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1680
1682 return IsPacked == That.IsPacked && ETypes == That.ETypes;
1683}
1684
1686 return !this->operator==(That);
1687}
1688
1689StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1691}
1692
1693StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1695}
1696
1697unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1698 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1699 Key.IsPacked);
1700}
1701
1702unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1703 return getHashValue(KeyTy(ST));
1704}
1705
1706bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1707 const StructType *RHS) {
1708 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1709 return false;
1710 return LHS == KeyTy(RHS);
1711}
1712
1713bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1714 const StructType *RHS) {
1715 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1716 return LHS == RHS;
1717 return KeyTy(LHS) == KeyTy(RHS);
1718}
1719
1721 assert(!Ty->isOpaque());
1722 NonOpaqueStructTypes.insert(Ty);
1723}
1724
1726 assert(!Ty->isOpaque());
1727 NonOpaqueStructTypes.insert(Ty);
1728 bool Removed = OpaqueStructTypes.erase(Ty);
1729 (void)Removed;
1730 assert(Removed);
1731}
1732
1734 assert(Ty->isOpaque());
1735 OpaqueStructTypes.insert(Ty);
1736}
1737
1738StructType *
1740 bool IsPacked) {
1741 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1742 auto I = NonOpaqueStructTypes.find_as(Key);
1743 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1744}
1745
1747 if (Ty->isOpaque())
1748 return OpaqueStructTypes.count(Ty);
1749 auto I = NonOpaqueStructTypes.find(Ty);
1750 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1751}
1752
1753IRMover::IRMover(Module &M) : Composite(M) {
1754 TypeFinder StructTypes;
1755 StructTypes.run(M, /* OnlyNamed */ false);
1756 for (StructType *Ty : StructTypes) {
1757 if (Ty->isOpaque())
1758 IdentifiedStructTypes.addOpaque(Ty);
1759 else
1760 IdentifiedStructTypes.addNonOpaque(Ty);
1761 }
1762 // Self-map metadatas in the destination module. This is needed when
1763 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1764 // destination module may be reached from the source module.
1765 for (const auto *MD : StructTypes.getVisitedMetadata()) {
1766 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1767 }
1768}
1769
1770Error IRMover::move(std::unique_ptr<Module> Src,
1771 ArrayRef<GlobalValue *> ValuesToLink,
1772 LazyCallback AddLazyFor, bool IsPerformingImport) {
1773 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1774 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1775 IsPerformingImport);
1776 Error E = TheIRLinker.run();
1778 return E;
1779}
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file contains the declarations for the subclasses of Constant, which represent the different fla...
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
static void forceRenaming(GlobalValue *GV, StringRef Name)
The LLVM SymbolTable class autorenames globals that conflict in the symbol table.
Definition: IRMover.cpp:554
static void getArrayElements(const Constant *C, SmallVectorImpl< Constant * > &Dest)
Definition: IRMover.cpp:868
static std::string adjustInlineAsm(const std::string &InlineAsm, const Triple &Triple)
Return InlineAsm adjusted with target-specific directives if required.
Definition: IRMover.cpp:1501
static StringRef getTypeNamePrefix(StringRef Name)
Definition: IRMover.cpp:769
static Error stringErr(const Twine &T)
Most of the errors produced by this module are inconvertible StringErrors.
Definition: IRMover.cpp:39
Module.h This file contains the declarations for the Module class.
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
static unsigned getAddressSpace(const Value *V, unsigned MaxLookup)
#define P(N)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static unsigned getNumElements(Type *Ty)
This file defines the make_scope_exit function, which executes user-defined cleanup logic at scope ex...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallPtrSet class.
This file defines the SmallString class.
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
static ArrayType * get(Type *ElementType, uint64_t NumElements)
This static method is the primary way to construct an ArrayType.
AttrKind
This enumeration lists the attributes that can be associated with parameters, function results,...
Definition: Attributes.h:86
LLVM Basic Block Representation.
Definition: BasicBlock.h:61
Base class for all callable instructions (InvokeInst and CallInst) Holds everything related to callin...
Definition: InstrTypes.h:1120
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:47
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:528
static Constant * getPointerBitCastOrAddrSpaceCast(Constant *C, Type *Ty)
Create a BitCast or AddrSpaceCast for a pointer type depending on the address space.
Definition: Constants.cpp:2268
static Constant * getBitCast(Constant *C, Type *Ty, bool OnlyIfReduced=false)
Definition: Constants.cpp:2321
This is the shared class of boolean and integer constants.
Definition: Constants.h:83
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Definition: Constants.h:157
This is an important base class in LLVM.
Definition: Constant.h:42
const Constant * stripPointerCasts() const
Definition: Constant.h:218
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
Definition: Constants.cpp:435
This class represents an Operation in the Expression.
bool isDefault() const
Test if the DataLayout was constructed from an empty string.
Definition: DataLayout.h:210
bool erase(const KeyT &Val)
Definition: DenseMap.h:321
Implements a dense probed hash-table based set.
Definition: DenseSet.h:278
This is the base abstract class for diagnostic reporting in the backend.
Interface for custom diagnostic printing.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:337
Tagged union holding either a T or a Error.
Definition: Error.h:481
Error takeError()
Take ownership of the stored error.
Definition: Error.h:608
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:173
FunctionType * getFunctionType() const
Returns the FunctionType for me.
Definition: Function.h:216
bool IsNewDbgInfoFormat
Is this function using intrinsics to record the position of debugging information,...
Definition: Function.h:116
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:557
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:614
StringRef getSection() const
Get the custom section of this global if it has one.
Definition: GlobalObject.h:117
MaybeAlign getAlign() const
Returns the alignment of the given variable or function.
Definition: GlobalObject.h:79
void setAlignment(Align Align)
Sets the alignment attribute of the GlobalObject.
Definition: Globals.cpp:143
VisibilityTypes getVisibility() const
Definition: GlobalValue.h:248
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
Definition: Globals.cpp:296
LinkageTypes getLinkage() const
Definition: GlobalValue.h:546
bool hasLocalLinkage() const
Definition: GlobalValue.h:528
const Comdat * getComdat() const
Definition: Globals.cpp:199
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:529
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:271
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
bool isDeclarationForLinker() const
Definition: GlobalValue.h:618
unsigned getAddressSpace() const
Definition: GlobalValue.h:205
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:656
void eraseFromParent()
This method unlinks 'this' from the containing module and deletes it.
Definition: Globals.cpp:91
PointerType * getType() const
Global values are always pointers.
Definition: GlobalValue.h:294
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:215
bool hasAppendingLinkage() const
Definition: GlobalValue.h:525
void removeFromParent()
This method unlinks 'this' from the containing module, but does not delete it.
Definition: Globals.cpp:79
@ InternalLinkage
Rename collisions when linking (static functions).
Definition: GlobalValue.h:59
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
@ ExternalWeakLinkage
ExternalWeak linkage description.
Definition: GlobalValue.h:61
Type * getValueType() const
Definition: GlobalValue.h:296
const Constant * getInitializer() const
getInitializer - Return the initializer for this global variable.
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:521
bool isConstant() const
If the value is a global constant, its value is immutable throughout the runtime execution of the pro...
void switchToNonOpaque(StructType *Ty)
Definition: IRMover.cpp:1725
StructType * findNonOpaque(ArrayRef< Type * > ETypes, bool IsPacked)
Definition: IRMover.cpp:1739
IRMover(Module &M)
Definition: IRMover.cpp:1753
Error move(std::unique_ptr< Module > Src, ArrayRef< GlobalValue * > ValuesToLink, LazyCallback AddLazyFor, bool IsPerformingImport)
Move in the provide values in ValuesToLink from Src.
Definition: IRMover.cpp:1770
This is an important class for using LLVM in a threaded context.
Definition: LLVMContext.h:67
LinkDiagnosticInfo(DiagnosticSeverity Severity, const Twine &Msg)
Definition: IRMover.cpp:345
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
Definition: IRMover.cpp:348
Metadata node.
Definition: Metadata.h:1069
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1428
op_iterator op_end() const
Definition: Metadata.h:1424
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1543
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1436
op_iterator op_begin() const
Definition: Metadata.h:1420
A single uniqued string.
Definition: Metadata.h:720
Tuple of metadata.
Definition: Metadata.h:1473
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1511
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition: Metadata.h:1529
Root of the metadata hierarchy.
Definition: Metadata.h:62
static void CollectAsmSymvers(const Module &M, function_ref< void(StringRef, StringRef)> AsmSymver)
Parse inline ASM and collect the symvers directives that are defined in the current module.
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
NamedMDNode * getNamedMetadata(StringRef Name) const
Return the first NamedMDNode in the module with the specified name.
Definition: Module.cpp:297
@ AppendUnique
Appends the two values, which are required to be metadata nodes.
Definition: Module.h:144
@ Override
Uses the specified value, regardless of the behavior or value of the other module.
Definition: Module.h:136
@ Warning
Emits a warning if two values disagree.
Definition: Module.h:122
@ Error
Emits an error if two values disagree, otherwise the resulting value is that of the operands.
Definition: Module.h:118
@ Min
Takes the min of the two values, which are required to be integers.
Definition: Module.h:150
@ Append
Appends the two values, which are required to be metadata nodes.
Definition: Module.h:139
@ Max
Takes the max of the two values, which are required to be integers.
Definition: Module.h:147
@ Require
Adds a requirement that another module flag be present and have a specified value after linking is pe...
Definition: Module.h:131
LLVMContext & getContext() const
Get the global data context.
Definition: Module.h:302
bool IsNewDbgInfoFormat
Is this Module using intrinsics to record the position of debugging information, or non-intrinsic rec...
Definition: Module.h:217
void dropTriviallyDeadConstantArrays()
Destroy ConstantArrays in LLVMContext if they are not used.
NamedMDNode * getOrInsertModuleFlagsMetadata()
Returns the NamedMDNode in the module that represents module-level flags.
Definition: Module.cpp:368
const std::string & getTargetTriple() const
Get the target triple which is a string describing the target host.
Definition: Module.h:298
const std::string & getModuleIdentifier() const
Get the module identifier which is, essentially, the name of the module.
Definition: Module.h:268
void setDataLayout(StringRef Desc)
Set the data layout.
Definition: Module.cpp:425
void insertGlobalVariable(GlobalVariable *GV)
Insert global variable GV at the end of the global variable list and take ownership.
Definition: Module.h:586
GlobalValue * getNamedValue(StringRef Name) const
Return the global value in the module with the specified name, of arbitrary type.
Definition: Module.cpp:170
NamedMDNode * getOrInsertNamedMetadata(StringRef Name)
Return the named MDNode in the module with the specified name.
Definition: Module.cpp:304
Comdat * getOrInsertComdat(StringRef Name)
Return the Comdat in the module with the specified name.
Definition: Module.cpp:611
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Definition: Module.h:294
const std::string & getDataLayoutStr() const
Get the data layout string for the module's target platform.
Definition: Module.h:289
void appendModuleInlineAsm(StringRef Asm)
Append to the module-scope inline assembly blocks.
Definition: Module.h:353
void setTargetTriple(StringRef T)
Set the target triple.
Definition: Module.h:341
A tuple of MDNodes.
Definition: Metadata.h:1731
void setOperand(unsigned I, MDNode *New)
Definition: Metadata.cpp:1433
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1425
unsigned getNumOperands() const
Definition: Metadata.cpp:1421
iterator_range< op_iterator > operands()
Definition: Metadata.h:1827
void addOperand(MDNode *M)
Definition: Metadata.cpp:1431
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space.
Used to temporarily set the debug info format of a function, module, or basic block for the duration ...
size_type size() const
Determine the number of elements in the SetVector.
Definition: SetVector.h:98
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
bool erase(PtrType Ptr)
Remove pointer from the set.
Definition: SmallPtrSet.h:401
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:384
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
Definition: SmallPtrSet.h:519
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
bool empty() const
Definition: SmallVector.h:81
size_t size() const
Definition: SmallVector.h:78
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: SmallVector.h:573
void resize(size_type N)
Definition: SmallVector.h:638
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:51
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:265
bool ends_with(StringRef Suffix) const
Check if this string ends with the given Suffix.
Definition: StringRef.h:277
static constexpr size_t npos
Definition: StringRef.h:53
Class to represent struct types.
Definition: DerivedTypes.h:218
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
Definition: Type.cpp:406
static StructType * getTypeByName(LLVMContext &C, StringRef Name)
Return the type with the specified name, or null if there is none by that name.
Definition: Type.cpp:731
static StructType * create(LLVMContext &Context, StringRef Name)
This creates an identified struct.
Definition: Type.cpp:612
bool isPacked() const
Definition: DerivedTypes.h:284
void setName(StringRef Name)
Change the name of this type to the specified name, or to a name with a suffix if there is a collisio...
Definition: Type.cpp:561
Error setBodyOrError(ArrayRef< Type * > Elements, bool isPacked=false)
Specify a body for an opaque identified type or return an error if it would make the type recursive.
Definition: Type.cpp:531
bool isLiteral() const
Return true if this type is uniqued by structural equivalence, false if it is a struct definition.
Definition: DerivedTypes.h:288
bool isOpaque() const
Return true if this is a type with an identity that has no body specified yet.
Definition: DerivedTypes.h:292
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
ArchType getArch() const
Get the parsed architecture type of this triple.
Definition: Triple.h:383
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
TypeFinder - Walk over a module, identifying all of the types that are used by the module.
Definition: TypeFinder.h:31
DenseSet< const MDNode * > & getVisitedMetadata()
Definition: TypeFinder.h:63
void run(const Module &M, bool onlyNamed)
Definition: TypeFinder.cpp:34
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
@ FunctionTyID
Functions.
Definition: Type.h:71
@ ArrayTyID
Arrays.
Definition: Type.h:74
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition: Type.h:76
@ StructTyID
Structures.
Definition: Type.h:73
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition: Type.h:75
@ PointerTyID
Pointers.
Definition: Type.h:72
unsigned getNumContainedTypes() const
Return the number of types in the derived type.
Definition: Type.h:390
LLVMContext & getContext() const
Return the LLVMContext in which this type was uniqued.
Definition: Type.h:128
bool isFunctionTy() const
True if this is an instance of FunctionType.
Definition: Type.h:255
TypeID getTypeID() const
Return the type id for the type.
Definition: Type.h:136
Type * getContainedType(unsigned i) const
This method is used to implement the type iterator (defined at the end of the file).
Definition: Type.h:384
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition: ValueMapper.h:41
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:164
std::optional< MDMapT > & getMDMap()
Definition: ValueMap.h:119
iterator find(const KeyT &Val)
Definition: ValueMap.h:155
iterator end()
Definition: ValueMap.h:135
Context for (re-)mapping values (and metadata).
Definition: ValueMapper.h:149
MDNode * mapMDNode(const MDNode &N)
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
void remapGlobalObjectMetadata(GlobalObject &GO)
Value * mapValue(const Value &V)
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
Definition: ValueMapper.h:54
LLVM Value Representation.
Definition: Value.h:74
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Definition: Value.cpp:534
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs and address space casts.
Definition: Value.cpp:694
LLVMContext & getContext() const
All values hold a context through their type.
Definition: Value.cpp:1075
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
void takeName(Value *V)
Transfer the name from V to this value.
Definition: Value.cpp:383
std::pair< iterator, bool > insert(const ValueT &V)
Definition: DenseSet.h:213
bool erase(const ValueT &V)
Definition: DenseSet.h:97
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
Definition: DenseSet.h:95
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:661
unique_function is a type-erasing functor similar to std::function.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
constexpr char Attrs[]
Key for Kernel::Metadata::mAttrs.
Key
PAL metadata keys.
@ Entry
Definition: COFF.h:844
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition: CallingConv.h:24
ID ArrayRef< Type * > Tys
Definition: Intrinsics.h:102
std::optional< Function * > remangleIntrinsicFunction(Function *F)
Flag
These should be considered private to the implementation of the MCInstrDesc class.
Definition: MCInstrDesc.h:148
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
StringRef filename(StringRef path, Style style=Style::native)
Get filename.
Definition: Path.cpp:577
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:98
bool UpgradeModuleFlags(Module &M)
This checks for module flags which should be upgraded.
@ SAT
Definition: SPIRVUtils.h:403
bool operator==(const AddressRangeValuePair &LHS, const AddressRangeValuePair &RHS)
@ DK_Linker
decltype(auto) get(const PointerIntPair< PointerTy, IntBits, IntType, PtrTraits, Info > &Pair)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition: ValueMapper.h:94
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
Definition: ValueMapper.h:104
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
Definition: ValueMapper.h:100
OutputIt move(R &&Range, OutputIt Out)
Provide wrappers to std::move which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1873
DiagnosticSeverity
Defines the different supported severity of a diagnostic.
@ DS_Warning
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
Definition: STLExtras.h:2099
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Definition: Hashing.h:590
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
Definition: Hashing.h:468
constexpr const char * PseudoProbeDescMetadataName
Definition: PseudoProbe.h:25
Implement std::hash so that hash_code can be used in STL containers.
Definition: BitVector.h:858
#define N
An information struct used to provide DenseMap with the various necessary components for a given valu...
Definition: DenseMapInfo.h:52
KeyTy(ArrayRef< Type * > E, bool P)
Definition: IRMover.cpp:1675
bool operator==(const KeyTy &that) const
Definition: IRMover.cpp:1681
bool operator!=(const KeyTy &that) const
Definition: IRMover.cpp:1685