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 = FunctionType::get(ElementTypes[0],
301 ArrayRef(ElementTypes).slice(1),
302 cast<FunctionType>(Ty)->isVarArg());
303 case Type::StructTyID: {
304 auto *STy = cast<StructType>(Ty);
305 bool IsPacked = STy->isPacked();
306 if (IsUniqued)
307 return *Entry = StructType::get(Ty->getContext(), ElementTypes, IsPacked);
308
309 // If the type is opaque, we can just use it directly.
310 if (STy->isOpaque()) {
311 DstStructTypesSet.addOpaque(STy);
312 return *Entry = Ty;
313 }
314
315 if (StructType *OldT =
316 DstStructTypesSet.findNonOpaque(ElementTypes, IsPacked)) {
317 STy->setName("");
318 return *Entry = OldT;
319 }
320
321 if (!AnyChange) {
322 DstStructTypesSet.addNonOpaque(STy);
323 return *Entry = Ty;
324 }
325
326 StructType *DTy =
327 StructType::create(Ty->getContext(), ElementTypes, "", STy->isPacked());
328
329 // Steal STy's name.
330 if (STy->hasName()) {
331 SmallString<16> TmpName = STy->getName();
332 STy->setName("");
333 DTy->setName(TmpName);
334 }
335
336 DstStructTypesSet.addNonOpaque(DTy);
337 return *Entry = DTy;
338 }
339 }
340}
341
343 const Twine &Msg)
344 : DiagnosticInfo(DK_Linker, Severity), Msg(Msg) {}
345void LinkDiagnosticInfo::print(DiagnosticPrinter &DP) const { DP << Msg; }
346
347//===----------------------------------------------------------------------===//
348// IRLinker implementation.
349//===----------------------------------------------------------------------===//
350
351namespace {
352class IRLinker;
353
354/// Creates prototypes for functions that are lazily linked on the fly. This
355/// speeds up linking for modules with many/ lazily linked functions of which
356/// few get used.
357class GlobalValueMaterializer final : public ValueMaterializer {
358 IRLinker &TheIRLinker;
359
360public:
361 GlobalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
362 Value *materialize(Value *V) override;
363};
364
365class LocalValueMaterializer final : public ValueMaterializer {
366 IRLinker &TheIRLinker;
367
368public:
369 LocalValueMaterializer(IRLinker &TheIRLinker) : TheIRLinker(TheIRLinker) {}
370 Value *materialize(Value *V) override;
371};
372
373/// Type of the Metadata map in \a ValueToValueMapTy.
375
376/// This is responsible for keeping track of the state used for moving data
377/// from SrcM to DstM.
378class IRLinker {
379 Module &DstM;
380 std::unique_ptr<Module> SrcM;
381
382 /// See IRMover::move().
383 IRMover::LazyCallback AddLazyFor;
384
385 TypeMapTy TypeMap;
386 GlobalValueMaterializer GValMaterializer;
387 LocalValueMaterializer LValMaterializer;
388
389 /// A metadata map that's shared between IRLinker instances.
390 MDMapT &SharedMDs;
391
392 /// Mapping of values from what they used to be in Src, to what they are now
393 /// in DstM. ValueToValueMapTy is a ValueMap, which involves some overhead
394 /// due to the use of Value handles which the Linker doesn't actually need,
395 /// but this allows us to reuse the ValueMapper code.
397 ValueToValueMapTy IndirectSymbolValueMap;
398
399 DenseSet<GlobalValue *> ValuesToLink;
400 std::vector<GlobalValue *> Worklist;
401 std::vector<std::pair<GlobalValue *, Value*>> RAUWWorklist;
402
403 /// Set of globals with eagerly copied metadata that may require remapping.
404 /// This remapping is performed after metadata linking.
405 DenseSet<GlobalObject *> UnmappedMetadata;
406
407 void maybeAdd(GlobalValue *GV) {
408 if (ValuesToLink.insert(GV).second)
409 Worklist.push_back(GV);
410 }
411
412 /// Whether we are importing globals for ThinLTO, as opposed to linking the
413 /// source module. If this flag is set, it means that we can rely on some
414 /// other object file to define any non-GlobalValue entities defined by the
415 /// source module. This currently causes us to not link retained types in
416 /// debug info metadata and module inline asm.
417 bool IsPerformingImport;
418
419 /// Set to true when all global value body linking is complete (including
420 /// lazy linking). Used to prevent metadata linking from creating new
421 /// references.
422 bool DoneLinkingBodies = false;
423
424 /// The Error encountered during materialization. We use an Optional here to
425 /// avoid needing to manage an unconsumed success value.
426 std::optional<Error> FoundError;
427 void setError(Error E) {
428 if (E)
429 FoundError = std::move(E);
430 }
431
432 /// Entry point for mapping values and alternate context for mapping aliases.
433 ValueMapper Mapper;
434 unsigned IndirectSymbolMCID;
435
436 /// Handles cloning of a global values from the source module into
437 /// the destination module, including setting the attributes and visibility.
438 GlobalValue *copyGlobalValueProto(const GlobalValue *SGV, bool ForDefinition);
439
440 void emitWarning(const Twine &Message) {
441 SrcM->getContext().diagnose(LinkDiagnosticInfo(DS_Warning, Message));
442 }
443
444 /// Given a global in the source module, return the global in the
445 /// destination module that is being linked to, if any.
446 GlobalValue *getLinkedToGlobal(const GlobalValue *SrcGV) {
447 // If the source has no name it can't link. If it has local linkage,
448 // there is no name match-up going on.
449 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
450 return nullptr;
451
452 // Otherwise see if we have a match in the destination module's symtab.
453 GlobalValue *DGV = DstM.getNamedValue(SrcGV->getName());
454 if (!DGV)
455 return nullptr;
456
457 // If we found a global with the same name in the dest module, but it has
458 // internal linkage, we are really not doing any linkage here.
459 if (DGV->hasLocalLinkage())
460 return nullptr;
461
462 // If we found an intrinsic declaration with mismatching prototypes, we
463 // probably had a nameclash. Don't use that version.
464 if (auto *FDGV = dyn_cast<Function>(DGV))
465 if (FDGV->isIntrinsic())
466 if (const auto *FSrcGV = dyn_cast<Function>(SrcGV))
467 if (FDGV->getFunctionType() != TypeMap.get(FSrcGV->getFunctionType()))
468 return nullptr;
469
470 // Otherwise, we do in fact link to the destination global.
471 return DGV;
472 }
473
474 void computeTypeMapping();
475
476 Expected<Constant *> linkAppendingVarProto(GlobalVariable *DstGV,
477 const GlobalVariable *SrcGV);
478
479 /// Given the GlobaValue \p SGV in the source module, and the matching
480 /// GlobalValue \p DGV (if any), return true if the linker will pull \p SGV
481 /// into the destination module.
482 ///
483 /// Note this code may call the client-provided \p AddLazyFor.
484 bool shouldLink(GlobalValue *DGV, GlobalValue &SGV);
485 Expected<Constant *> linkGlobalValueProto(GlobalValue *GV,
486 bool ForIndirectSymbol);
487
488 Error linkModuleFlagsMetadata();
489
490 void linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src);
491 Error linkFunctionBody(Function &Dst, Function &Src);
492 void linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src);
493 void linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src);
494 Error linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src);
495
496 /// Replace all types in the source AttributeList with the
497 /// corresponding destination type.
498 AttributeList mapAttributeTypes(LLVMContext &C, AttributeList Attrs);
499
500 /// Functions that take care of cloning a specific global value type
501 /// into the destination module.
502 GlobalVariable *copyGlobalVariableProto(const GlobalVariable *SGVar);
503 Function *copyFunctionProto(const Function *SF);
504 GlobalValue *copyIndirectSymbolProto(const GlobalValue *SGV);
505
506 /// Perform "replace all uses with" operations. These work items need to be
507 /// performed as part of materialization, but we postpone them to happen after
508 /// materialization is done. The materializer called by ValueMapper is not
509 /// expected to delete constants, as ValueMapper is holding pointers to some
510 /// of them, but constant destruction may be indirectly triggered by RAUW.
511 /// Hence, the need to move this out of the materialization call chain.
512 void flushRAUWWorklist();
513
514 /// When importing for ThinLTO, prevent importing of types listed on
515 /// the DICompileUnit that we don't need a copy of in the importing
516 /// module.
517 void prepareCompileUnitsForImport();
518 void linkNamedMDNodes();
519
520 /// Update attributes while linking.
521 void updateAttributes(GlobalValue &GV);
522
523public:
524 IRLinker(Module &DstM, MDMapT &SharedMDs,
525 IRMover::IdentifiedStructTypeSet &Set, std::unique_ptr<Module> SrcM,
526 ArrayRef<GlobalValue *> ValuesToLink,
527 IRMover::LazyCallback AddLazyFor, bool IsPerformingImport)
528 : DstM(DstM), SrcM(std::move(SrcM)), AddLazyFor(std::move(AddLazyFor)),
529 TypeMap(Set), GValMaterializer(*this), LValMaterializer(*this),
530 SharedMDs(SharedMDs), IsPerformingImport(IsPerformingImport),
532 &TypeMap, &GValMaterializer),
533 IndirectSymbolMCID(Mapper.registerAlternateMappingContext(
534 IndirectSymbolValueMap, &LValMaterializer)) {
535 ValueMap.getMDMap() = std::move(SharedMDs);
536 for (GlobalValue *GV : ValuesToLink)
537 maybeAdd(GV);
538 if (IsPerformingImport)
539 prepareCompileUnitsForImport();
540 }
541 ~IRLinker() { SharedMDs = std::move(*ValueMap.getMDMap()); }
542
543 Error run();
544 Value *materialize(Value *V, bool ForIndirectSymbol);
545};
546}
547
548/// The LLVM SymbolTable class autorenames globals that conflict in the symbol
549/// table. This is good for all clients except for us. Go through the trouble
550/// to force this back.
552 // If the global doesn't force its name or if it already has the right name,
553 // there is nothing for us to do.
554 if (GV->hasLocalLinkage() || GV->getName() == Name)
555 return;
556
557 Module *M = GV->getParent();
558
559 // If there is a conflict, rename the conflict.
560 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
561 GV->takeName(ConflictGV);
562 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
563 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
564 } else {
565 GV->setName(Name); // Force the name back
566 }
567}
568
569Value *GlobalValueMaterializer::materialize(Value *SGV) {
570 return TheIRLinker.materialize(SGV, false);
571}
572
573Value *LocalValueMaterializer::materialize(Value *SGV) {
574 return TheIRLinker.materialize(SGV, true);
575}
576
577Value *IRLinker::materialize(Value *V, bool ForIndirectSymbol) {
578 auto *SGV = dyn_cast<GlobalValue>(V);
579 if (!SGV)
580 return nullptr;
581
582 // If SGV is from dest, it was already materialized when dest was loaded.
583 if (SGV->getParent() == &DstM)
584 return nullptr;
585
586 // When linking a global from other modules than source & dest, skip
587 // materializing it because it would be mapped later when its containing
588 // module is linked. Linking it now would potentially pull in many types that
589 // may not be mapped properly.
590 if (SGV->getParent() != SrcM.get())
591 return nullptr;
592
593 Expected<Constant *> NewProto = linkGlobalValueProto(SGV, ForIndirectSymbol);
594 if (!NewProto) {
595 setError(NewProto.takeError());
596 return nullptr;
597 }
598 if (!*NewProto)
599 return nullptr;
600
601 GlobalValue *New = dyn_cast<GlobalValue>(*NewProto);
602 if (!New)
603 return *NewProto;
604
605 // If we already created the body, just return.
606 if (auto *F = dyn_cast<Function>(New)) {
607 if (!F->isDeclaration())
608 return New;
609 } else if (auto *V = dyn_cast<GlobalVariable>(New)) {
610 if (V->hasInitializer() || V->hasAppendingLinkage())
611 return New;
612 } else if (auto *GA = dyn_cast<GlobalAlias>(New)) {
613 if (GA->getAliasee())
614 return New;
615 } else if (auto *GI = dyn_cast<GlobalIFunc>(New)) {
616 if (GI->getResolver())
617 return New;
618 } else {
619 llvm_unreachable("Invalid GlobalValue type");
620 }
621
622 // If the global is being linked for an indirect symbol, it may have already
623 // been scheduled to satisfy a regular symbol. Similarly, a global being linked
624 // for a regular symbol may have already been scheduled for an indirect
625 // symbol. Check for these cases by looking in the other value map and
626 // confirming the same value has been scheduled. If there is an entry in the
627 // ValueMap but the value is different, it means that the value already had a
628 // definition in the destination module (linkonce for instance), but we need a
629 // new definition for the indirect symbol ("New" will be different).
630 if ((ForIndirectSymbol && ValueMap.lookup(SGV) == New) ||
631 (!ForIndirectSymbol && IndirectSymbolValueMap.lookup(SGV) == New))
632 return New;
633
634 if (ForIndirectSymbol || shouldLink(New, *SGV))
635 setError(linkGlobalValueBody(*New, *SGV));
636
637 updateAttributes(*New);
638 return New;
639}
640
641/// Loop through the global variables in the src module and merge them into the
642/// dest module.
643GlobalVariable *IRLinker::copyGlobalVariableProto(const GlobalVariable *SGVar) {
644 // No linking to be performed or linking from the source: simply create an
645 // identical version of the symbol over in the dest module... the
646 // initializer will be filled in later by LinkGlobalInits.
647 GlobalVariable *NewDGV =
648 new GlobalVariable(DstM, TypeMap.get(SGVar->getValueType()),
650 /*init*/ nullptr, SGVar->getName(),
651 /*insertbefore*/ nullptr, SGVar->getThreadLocalMode(),
652 SGVar->getAddressSpace());
653 NewDGV->setAlignment(SGVar->getAlign());
654 NewDGV->copyAttributesFrom(SGVar);
655 return NewDGV;
656}
657
658AttributeList IRLinker::mapAttributeTypes(LLVMContext &C, AttributeList Attrs) {
659 for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
660 for (int AttrIdx = Attribute::FirstTypeAttr;
661 AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
662 Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
663 if (Attrs.hasAttributeAtIndex(i, TypedAttr)) {
664 if (Type *Ty =
665 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
666 Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
667 TypeMap.get(Ty));
668 break;
669 }
670 }
671 }
672 }
673 return Attrs;
674}
675
676/// Link the function in the source module into the destination module if
677/// needed, setting up mapping information.
678Function *IRLinker::copyFunctionProto(const Function *SF) {
679 // If there is no linkage to be performed or we are linking from the source,
680 // bring SF over.
681 auto *F = Function::Create(TypeMap.get(SF->getFunctionType()),
683 SF->getAddressSpace(), SF->getName(), &DstM);
684 F->copyAttributesFrom(SF);
685 F->setAttributes(mapAttributeTypes(F->getContext(), F->getAttributes()));
686 F->IsNewDbgInfoFormat = SF->IsNewDbgInfoFormat;
687 return F;
688}
689
690/// Set up prototypes for any indirect symbols that come over from the source
691/// module.
692GlobalValue *IRLinker::copyIndirectSymbolProto(const GlobalValue *SGV) {
693 // If there is no linkage to be performed or we're linking from the source,
694 // bring over SGA.
695 auto *Ty = TypeMap.get(SGV->getValueType());
696
697 if (auto *GA = dyn_cast<GlobalAlias>(SGV)) {
698 auto *DGA = GlobalAlias::create(Ty, SGV->getAddressSpace(),
700 SGV->getName(), &DstM);
701 DGA->copyAttributesFrom(GA);
702 return DGA;
703 }
704
705 if (auto *GI = dyn_cast<GlobalIFunc>(SGV)) {
706 auto *DGI = GlobalIFunc::create(Ty, SGV->getAddressSpace(),
708 SGV->getName(), nullptr, &DstM);
709 DGI->copyAttributesFrom(GI);
710 return DGI;
711 }
712
713 llvm_unreachable("Invalid source global value type");
714}
715
716GlobalValue *IRLinker::copyGlobalValueProto(const GlobalValue *SGV,
717 bool ForDefinition) {
718 GlobalValue *NewGV;
719 if (auto *SGVar = dyn_cast<GlobalVariable>(SGV)) {
720 NewGV = copyGlobalVariableProto(SGVar);
721 } else if (auto *SF = dyn_cast<Function>(SGV)) {
722 NewGV = copyFunctionProto(SF);
723 } else {
724 if (ForDefinition)
725 NewGV = copyIndirectSymbolProto(SGV);
726 else if (SGV->getValueType()->isFunctionTy())
727 NewGV =
728 Function::Create(cast<FunctionType>(TypeMap.get(SGV->getValueType())),
730 SGV->getName(), &DstM);
731 else
732 NewGV =
733 new GlobalVariable(DstM, TypeMap.get(SGV->getValueType()),
734 /*isConstant*/ false, GlobalValue::ExternalLinkage,
735 /*init*/ nullptr, SGV->getName(),
736 /*insertbefore*/ nullptr,
737 SGV->getThreadLocalMode(), SGV->getAddressSpace());
738 }
739
740 if (ForDefinition)
741 NewGV->setLinkage(SGV->getLinkage());
742 else if (SGV->hasExternalWeakLinkage())
744
745 if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
746 // Metadata for global variables and function declarations is copied eagerly.
747 if (isa<GlobalVariable>(SGV) || SGV->isDeclaration()) {
748 NewGO->copyMetadata(cast<GlobalObject>(SGV), 0);
749 if (SGV->isDeclaration() && NewGO->hasMetadata())
750 UnmappedMetadata.insert(NewGO);
751 }
752 }
753
754 // Remove these copied constants in case this stays a declaration, since
755 // they point to the source module. If the def is linked the values will
756 // be mapped in during linkFunctionBody.
757 if (auto *NewF = dyn_cast<Function>(NewGV)) {
758 NewF->setPersonalityFn(nullptr);
759 NewF->setPrefixData(nullptr);
760 NewF->setPrologueData(nullptr);
761 }
762
763 return NewGV;
764}
765
767 size_t DotPos = Name.rfind('.');
768 return (DotPos == 0 || DotPos == StringRef::npos || Name.back() == '.' ||
769 !isdigit(static_cast<unsigned char>(Name[DotPos + 1])))
770 ? Name
771 : Name.substr(0, DotPos);
772}
773
774/// Loop over all of the linked values to compute type mappings. For example,
775/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
776/// types 'Foo' but one got renamed when the module was loaded into the same
777/// LLVMContext.
778void IRLinker::computeTypeMapping() {
779 for (GlobalValue &SGV : SrcM->globals()) {
780 GlobalValue *DGV = getLinkedToGlobal(&SGV);
781 if (!DGV)
782 continue;
783
784 if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
785 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
786 continue;
787 }
788
789 // Unify the element type of appending arrays.
790 ArrayType *DAT = cast<ArrayType>(DGV->getValueType());
791 ArrayType *SAT = cast<ArrayType>(SGV.getValueType());
792 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
793 }
794
795 for (GlobalValue &SGV : *SrcM)
796 if (GlobalValue *DGV = getLinkedToGlobal(&SGV)) {
797 if (DGV->getType() == SGV.getType()) {
798 // If the types of DGV and SGV are the same, it means that DGV is from
799 // the source module and got added to DstM from a shared metadata. We
800 // shouldn't map this type to itself in case the type's components get
801 // remapped to a new type from DstM (for instance, during the loop over
802 // SrcM->getIdentifiedStructTypes() below).
803 continue;
804 }
805
806 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
807 }
808
809 for (GlobalValue &SGV : SrcM->aliases())
810 if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
811 TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
812
813 // Incorporate types by name, scanning all the types in the source module.
814 // At this point, the destination module may have a type "%foo = { i32 }" for
815 // example. When the source module got loaded into the same LLVMContext, if
816 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
817 std::vector<StructType *> Types = SrcM->getIdentifiedStructTypes();
818 for (StructType *ST : Types) {
819 if (!ST->hasName())
820 continue;
821
822 if (TypeMap.DstStructTypesSet.hasType(ST)) {
823 // This is actually a type from the destination module.
824 // getIdentifiedStructTypes() can have found it by walking debug info
825 // metadata nodes, some of which get linked by name when ODR Type Uniquing
826 // is enabled on the Context, from the source to the destination module.
827 continue;
828 }
829
830 auto STTypePrefix = getTypeNamePrefix(ST->getName());
831 if (STTypePrefix.size() == ST->getName().size())
832 continue;
833
834 // Check to see if the destination module has a struct with the prefix name.
835 StructType *DST = StructType::getTypeByName(ST->getContext(), STTypePrefix);
836 if (!DST)
837 continue;
838
839 // Don't use it if this actually came from the source module. They're in
840 // the same LLVMContext after all. Also don't use it unless the type is
841 // actually used in the destination module. This can happen in situations
842 // like this:
843 //
844 // Module A Module B
845 // -------- --------
846 // %Z = type { %A } %B = type { %C.1 }
847 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
848 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
849 // %C = type { i8* } %B.3 = type { %C.1 }
850 //
851 // When we link Module B with Module A, the '%B' in Module B is
852 // used. However, that would then use '%C.1'. But when we process '%C.1',
853 // we prefer to take the '%C' version. So we are then left with both
854 // '%C.1' and '%C' being used for the same types. This leads to some
855 // variables using one type and some using the other.
856 if (TypeMap.DstStructTypesSet.hasType(DST))
857 TypeMap.addTypeMapping(DST, ST);
858 }
859
860 // Now that we have discovered all of the type equivalences, get a body for
861 // any 'opaque' types in the dest module that are now resolved.
862 setError(TypeMap.linkDefinedTypeBodies());
863}
864
865static void getArrayElements(const Constant *C,
867 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
868
869 for (unsigned i = 0; i != NumElements; ++i)
870 Dest.push_back(C->getAggregateElement(i));
871}
872
873/// If there were any appending global variables, link them together now.
875IRLinker::linkAppendingVarProto(GlobalVariable *DstGV,
876 const GlobalVariable *SrcGV) {
877 // Check that both variables have compatible properties.
878 if (DstGV && !DstGV->isDeclaration() && !SrcGV->isDeclaration()) {
879 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
880 return stringErr(
881 "Linking globals named '" + SrcGV->getName() +
882 "': can only link appending global with another appending "
883 "global!");
884
885 if (DstGV->isConstant() != SrcGV->isConstant())
886 return stringErr("Appending variables linked with different const'ness!");
887
888 if (DstGV->getAlign() != SrcGV->getAlign())
889 return stringErr(
890 "Appending variables with different alignment need to be linked!");
891
892 if (DstGV->getVisibility() != SrcGV->getVisibility())
893 return stringErr(
894 "Appending variables with different visibility need to be linked!");
895
896 if (DstGV->hasGlobalUnnamedAddr() != SrcGV->hasGlobalUnnamedAddr())
897 return stringErr(
898 "Appending variables with different unnamed_addr need to be linked!");
899
900 if (DstGV->getSection() != SrcGV->getSection())
901 return stringErr(
902 "Appending variables with different section name need to be linked!");
903
904 if (DstGV->getAddressSpace() != SrcGV->getAddressSpace())
905 return stringErr("Appending variables with different address spaces need "
906 "to be linked!");
907 }
908
909 // Do not need to do anything if source is a declaration.
910 if (SrcGV->isDeclaration())
911 return DstGV;
912
913 Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getValueType()))
914 ->getElementType();
915
916 // FIXME: This upgrade is done during linking to support the C API. Once the
917 // old form is deprecated, we should move this upgrade to
918 // llvm::UpgradeGlobalVariable() and simplify the logic here and in
919 // Mapper::mapAppendingVariable() in ValueMapper.cpp.
920 StringRef Name = SrcGV->getName();
921 bool IsNewStructor = false;
922 bool IsOldStructor = false;
923 if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
924 if (cast<StructType>(EltTy)->getNumElements() == 3)
925 IsNewStructor = true;
926 else
927 IsOldStructor = true;
928 }
929
930 PointerType *VoidPtrTy = PointerType::get(SrcGV->getContext(), 0);
931 if (IsOldStructor) {
932 auto &ST = *cast<StructType>(EltTy);
933 Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
934 EltTy = StructType::get(SrcGV->getContext(), Tys, false);
935 }
936
937 uint64_t DstNumElements = 0;
938 if (DstGV && !DstGV->isDeclaration()) {
939 ArrayType *DstTy = cast<ArrayType>(DstGV->getValueType());
940 DstNumElements = DstTy->getNumElements();
941
942 // Check to see that they two arrays agree on type.
943 if (EltTy != DstTy->getElementType())
944 return stringErr("Appending variables with different element types!");
945 }
946
947 SmallVector<Constant *, 16> SrcElements;
948 getArrayElements(SrcGV->getInitializer(), SrcElements);
949
950 if (IsNewStructor) {
951 erase_if(SrcElements, [this](Constant *E) {
952 auto *Key =
953 dyn_cast<GlobalValue>(E->getAggregateElement(2)->stripPointerCasts());
954 if (!Key)
955 return false;
956 GlobalValue *DGV = getLinkedToGlobal(Key);
957 return !shouldLink(DGV, *Key);
958 });
959 }
960 uint64_t NewSize = DstNumElements + SrcElements.size();
961 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
962
963 // Create the new global variable.
965 DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
966 /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
967 SrcGV->getAddressSpace());
968
969 NG->copyAttributesFrom(SrcGV);
970 forceRenaming(NG, SrcGV->getName());
971
972 Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
973
975 *NG,
976 (DstGV && !DstGV->isDeclaration()) ? DstGV->getInitializer() : nullptr,
977 IsOldStructor, SrcElements);
978
979 // Replace any uses of the two global variables with uses of the new
980 // global.
981 if (DstGV) {
982 RAUWWorklist.push_back(std::make_pair(DstGV, NG));
983 }
984
985 return Ret;
986}
987
988bool IRLinker::shouldLink(GlobalValue *DGV, GlobalValue &SGV) {
989 if (ValuesToLink.count(&SGV) || SGV.hasLocalLinkage())
990 return true;
991
992 if (DGV && !DGV->isDeclarationForLinker())
993 return false;
994
995 if (SGV.isDeclaration() || DoneLinkingBodies)
996 return false;
997
998 // Callback to the client to give a chance to lazily add the Global to the
999 // list of value to link.
1000 bool LazilyAdded = false;
1001 if (AddLazyFor)
1002 AddLazyFor(SGV, [this, &LazilyAdded](GlobalValue &GV) {
1003 maybeAdd(&GV);
1004 LazilyAdded = true;
1005 });
1006 return LazilyAdded;
1007}
1008
1009Expected<Constant *> IRLinker::linkGlobalValueProto(GlobalValue *SGV,
1010 bool ForIndirectSymbol) {
1011 GlobalValue *DGV = getLinkedToGlobal(SGV);
1012
1013 bool ShouldLink = shouldLink(DGV, *SGV);
1014
1015 // just missing from map
1016 if (ShouldLink) {
1017 auto I = ValueMap.find(SGV);
1018 if (I != ValueMap.end())
1019 return cast<Constant>(I->second);
1020
1021 I = IndirectSymbolValueMap.find(SGV);
1022 if (I != IndirectSymbolValueMap.end())
1023 return cast<Constant>(I->second);
1024 }
1025
1026 if (!ShouldLink && ForIndirectSymbol)
1027 DGV = nullptr;
1028
1029 // Handle the ultra special appending linkage case first.
1030 if (SGV->hasAppendingLinkage() || (DGV && DGV->hasAppendingLinkage()))
1031 return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
1032 cast<GlobalVariable>(SGV));
1033
1034 bool NeedsRenaming = false;
1035 GlobalValue *NewGV;
1036 if (DGV && !ShouldLink) {
1037 NewGV = DGV;
1038 } else {
1039 // If we are done linking global value bodies (i.e. we are performing
1040 // metadata linking), don't link in the global value due to this
1041 // reference, simply map it to null.
1042 if (DoneLinkingBodies)
1043 return nullptr;
1044
1045 NewGV = copyGlobalValueProto(SGV, ShouldLink || ForIndirectSymbol);
1046 if (ShouldLink || !ForIndirectSymbol)
1047 NeedsRenaming = true;
1048 }
1049
1050 // Overloaded intrinsics have overloaded types names as part of their
1051 // names. If we renamed overloaded types we should rename the intrinsic
1052 // as well.
1053 if (Function *F = dyn_cast<Function>(NewGV))
1054 if (auto Remangled = Intrinsic::remangleIntrinsicFunction(F)) {
1055 // Note: remangleIntrinsicFunction does not copy metadata and as such
1056 // F should not occur in the set of objects with unmapped metadata.
1057 // If this assertion fails then remangleIntrinsicFunction needs updating.
1058 assert(!UnmappedMetadata.count(F) && "intrinsic has unmapped metadata");
1059 NewGV->eraseFromParent();
1060 NewGV = *Remangled;
1061 NeedsRenaming = false;
1062 }
1063
1064 if (NeedsRenaming)
1065 forceRenaming(NewGV, SGV->getName());
1066
1067 if (ShouldLink || ForIndirectSymbol) {
1068 if (const Comdat *SC = SGV->getComdat()) {
1069 if (auto *GO = dyn_cast<GlobalObject>(NewGV)) {
1070 Comdat *DC = DstM.getOrInsertComdat(SC->getName());
1071 DC->setSelectionKind(SC->getSelectionKind());
1072 GO->setComdat(DC);
1073 }
1074 }
1075 }
1076
1077 if (!ShouldLink && ForIndirectSymbol)
1079
1080 Constant *C = NewGV;
1081 // Only create a bitcast if necessary. In particular, with
1082 // DebugTypeODRUniquing we may reach metadata in the destination module
1083 // containing a GV from the source module, in which case SGV will be
1084 // the same as DGV and NewGV, and TypeMap.get() will assert since it
1085 // assumes it is being invoked on a type in the source module.
1086 if (DGV && NewGV != SGV) {
1088 NewGV, TypeMap.get(SGV->getType()));
1089 }
1090
1091 if (DGV && NewGV != DGV) {
1092 // Schedule "replace all uses with" to happen after materializing is
1093 // done. It is not safe to do it now, since ValueMapper may be holding
1094 // pointers to constants that will get deleted if RAUW runs.
1095 RAUWWorklist.push_back(std::make_pair(
1096 DGV,
1098 }
1099
1100 return C;
1101}
1102
1103/// Update the initializers in the Dest module now that all globals that may be
1104/// referenced are in Dest.
1105void IRLinker::linkGlobalVariable(GlobalVariable &Dst, GlobalVariable &Src) {
1106 // Figure out what the initializer looks like in the dest module.
1107 Mapper.scheduleMapGlobalInitializer(Dst, *Src.getInitializer());
1108}
1109
1110/// Copy the source function over into the dest function and fix up references
1111/// to values. At this point we know that Dest is an external function, and
1112/// that Src is not.
1113Error IRLinker::linkFunctionBody(Function &Dst, Function &Src) {
1114 assert(Dst.isDeclaration() && !Src.isDeclaration());
1115
1116 // Materialize if needed.
1117 if (Error Err = Src.materialize())
1118 return Err;
1119
1120 // Link in the operands without remapping.
1121 if (Src.hasPrefixData())
1122 Dst.setPrefixData(Src.getPrefixData());
1123 if (Src.hasPrologueData())
1124 Dst.setPrologueData(Src.getPrologueData());
1125 if (Src.hasPersonalityFn())
1126 Dst.setPersonalityFn(Src.getPersonalityFn());
1127 assert(Src.IsNewDbgInfoFormat == Dst.IsNewDbgInfoFormat);
1128
1129 // Copy over the metadata attachments without remapping.
1130 Dst.copyMetadata(&Src, 0);
1131
1132 // Steal arguments and splice the body of Src into Dst.
1133 Dst.stealArgumentListFrom(Src);
1134 Dst.splice(Dst.end(), &Src);
1135
1136 // Everything has been moved over. Remap it.
1137 Mapper.scheduleRemapFunction(Dst);
1138 return Error::success();
1139}
1140
1141void IRLinker::linkAliasAliasee(GlobalAlias &Dst, GlobalAlias &Src) {
1142 Mapper.scheduleMapGlobalAlias(Dst, *Src.getAliasee(), IndirectSymbolMCID);
1143}
1144
1145void IRLinker::linkIFuncResolver(GlobalIFunc &Dst, GlobalIFunc &Src) {
1146 Mapper.scheduleMapGlobalIFunc(Dst, *Src.getResolver(), IndirectSymbolMCID);
1147}
1148
1149Error IRLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
1150 if (auto *F = dyn_cast<Function>(&Src))
1151 return linkFunctionBody(cast<Function>(Dst), *F);
1152 if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
1153 linkGlobalVariable(cast<GlobalVariable>(Dst), *GVar);
1154 return Error::success();
1155 }
1156 if (auto *GA = dyn_cast<GlobalAlias>(&Src)) {
1157 linkAliasAliasee(cast<GlobalAlias>(Dst), *GA);
1158 return Error::success();
1159 }
1160 linkIFuncResolver(cast<GlobalIFunc>(Dst), cast<GlobalIFunc>(Src));
1161 return Error::success();
1162}
1163
1164void IRLinker::flushRAUWWorklist() {
1165 for (const auto &Elem : RAUWWorklist) {
1166 GlobalValue *Old;
1167 Value *New;
1168 std::tie(Old, New) = Elem;
1169
1170 Old->replaceAllUsesWith(New);
1171 Old->eraseFromParent();
1172 }
1173 RAUWWorklist.clear();
1174}
1175
1176void IRLinker::prepareCompileUnitsForImport() {
1177 NamedMDNode *SrcCompileUnits = SrcM->getNamedMetadata("llvm.dbg.cu");
1178 if (!SrcCompileUnits)
1179 return;
1180 // When importing for ThinLTO, prevent importing of types listed on
1181 // the DICompileUnit that we don't need a copy of in the importing
1182 // module. They will be emitted by the originating module.
1183 for (MDNode *N : SrcCompileUnits->operands()) {
1184 auto *CU = cast<DICompileUnit>(N);
1185 assert(CU && "Expected valid compile unit");
1186 // Enums, macros, and retained types don't need to be listed on the
1187 // imported DICompileUnit. This means they will only be imported
1188 // if reached from the mapped IR.
1189 CU->replaceEnumTypes(nullptr);
1190 CU->replaceMacros(nullptr);
1191 CU->replaceRetainedTypes(nullptr);
1192
1193 // The original definition (or at least its debug info - if the variable is
1194 // internalized and optimized away) will remain in the source module, so
1195 // there's no need to import them.
1196 // If LLVM ever does more advanced optimizations on global variables
1197 // (removing/localizing write operations, for instance) that can track
1198 // through debug info, this decision may need to be revisited - but do so
1199 // with care when it comes to debug info size. Emitting small CUs containing
1200 // only a few imported entities into every destination module may be very
1201 // size inefficient.
1202 CU->replaceGlobalVariables(nullptr);
1203
1204 CU->replaceImportedEntities(nullptr);
1205 }
1206}
1207
1208/// Insert all of the named MDNodes in Src into the Dest module.
1209void IRLinker::linkNamedMDNodes() {
1210 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1211 for (const NamedMDNode &NMD : SrcM->named_metadata()) {
1212 // Don't link module flags here. Do them separately.
1213 if (&NMD == SrcModFlags)
1214 continue;
1215 // Don't import pseudo probe descriptors here for thinLTO. They will be
1216 // emitted by the originating module.
1217 if (IsPerformingImport && NMD.getName() == PseudoProbeDescMetadataName) {
1218 if (!DstM.getNamedMetadata(NMD.getName()))
1219 emitWarning("Pseudo-probe ignored: source module '" +
1220 SrcM->getModuleIdentifier() +
1221 "' is compiled with -fpseudo-probe-for-profiling while "
1222 "destination module '" +
1223 DstM.getModuleIdentifier() + "' is not\n");
1224 continue;
1225 }
1226 // The stats are computed per module and will all be merged in the binary.
1227 // Importing the metadata will cause duplication of the stats.
1228 if (IsPerformingImport && NMD.getName() == "llvm.stats")
1229 continue;
1230
1231 NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName());
1232 // Add Src elements into Dest node.
1233 for (const MDNode *Op : NMD.operands())
1234 DestNMD->addOperand(Mapper.mapMDNode(*Op));
1235 }
1236}
1237
1238/// Merge the linker flags in Src into the Dest module.
1239Error IRLinker::linkModuleFlagsMetadata() {
1240 // If the source module has no module flags, we are done.
1241 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1242 if (!SrcModFlags)
1243 return Error::success();
1244
1245 // Check for module flag for updates before do anything.
1246 UpgradeModuleFlags(*SrcM);
1247
1248 // If the destination module doesn't have module flags yet, then just copy
1249 // over the source module's flags.
1250 NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata();
1251 if (DstModFlags->getNumOperands() == 0) {
1252 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1253 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1254
1255 return Error::success();
1256 }
1257
1258 // First build a map of the existing module flags and requirements.
1260 SmallSetVector<MDNode *, 16> Requirements;
1262 DenseSet<MDString *> SeenMin;
1263 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1264 MDNode *Op = DstModFlags->getOperand(I);
1265 uint64_t Behavior =
1266 mdconst::extract<ConstantInt>(Op->getOperand(0))->getZExtValue();
1267 MDString *ID = cast<MDString>(Op->getOperand(1));
1268
1269 if (Behavior == Module::Require) {
1270 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1271 } else {
1272 if (Behavior == Module::Min)
1273 Mins.push_back(I);
1274 Flags[ID] = std::make_pair(Op, I);
1275 }
1276 }
1277
1278 // Merge in the flags from the source module, and also collect its set of
1279 // requirements.
1280 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1281 MDNode *SrcOp = SrcModFlags->getOperand(I);
1282 ConstantInt *SrcBehavior =
1283 mdconst::extract<ConstantInt>(SrcOp->getOperand(0));
1284 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1285 MDNode *DstOp;
1286 unsigned DstIndex;
1287 std::tie(DstOp, DstIndex) = Flags.lookup(ID);
1288 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1289 SeenMin.insert(ID);
1290
1291 // If this is a requirement, add it and continue.
1292 if (SrcBehaviorValue == Module::Require) {
1293 // If the destination module does not already have this requirement, add
1294 // it.
1295 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1296 DstModFlags->addOperand(SrcOp);
1297 }
1298 continue;
1299 }
1300
1301 // If there is no existing flag with this ID, just add it.
1302 if (!DstOp) {
1303 if (SrcBehaviorValue == Module::Min) {
1304 Mins.push_back(DstModFlags->getNumOperands());
1305 SeenMin.erase(ID);
1306 }
1307 Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands());
1308 DstModFlags->addOperand(SrcOp);
1309 continue;
1310 }
1311
1312 // Otherwise, perform a merge.
1313 ConstantInt *DstBehavior =
1314 mdconst::extract<ConstantInt>(DstOp->getOperand(0));
1315 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1316
1317 auto overrideDstValue = [&]() {
1318 DstModFlags->setOperand(DstIndex, SrcOp);
1319 Flags[ID].first = SrcOp;
1320 };
1321
1322 // If either flag has override behavior, handle it first.
1323 if (DstBehaviorValue == Module::Override) {
1324 // Diagnose inconsistent flags which both have override behavior.
1325 if (SrcBehaviorValue == Module::Override &&
1326 SrcOp->getOperand(2) != DstOp->getOperand(2))
1327 return stringErr("linking module flags '" + ID->getString() +
1328 "': IDs have conflicting override values in '" +
1329 SrcM->getModuleIdentifier() + "' and '" +
1330 DstM.getModuleIdentifier() + "'");
1331 continue;
1332 } else if (SrcBehaviorValue == Module::Override) {
1333 // Update the destination flag to that of the source.
1334 overrideDstValue();
1335 continue;
1336 }
1337
1338 // Diagnose inconsistent merge behavior types.
1339 if (SrcBehaviorValue != DstBehaviorValue) {
1340 bool MinAndWarn = (SrcBehaviorValue == Module::Min &&
1341 DstBehaviorValue == Module::Warning) ||
1342 (DstBehaviorValue == Module::Min &&
1343 SrcBehaviorValue == Module::Warning);
1344 bool MaxAndWarn = (SrcBehaviorValue == Module::Max &&
1345 DstBehaviorValue == Module::Warning) ||
1346 (DstBehaviorValue == Module::Max &&
1347 SrcBehaviorValue == Module::Warning);
1348 if (!(MaxAndWarn || MinAndWarn))
1349 return stringErr("linking module flags '" + ID->getString() +
1350 "': IDs have conflicting behaviors in '" +
1351 SrcM->getModuleIdentifier() + "' and '" +
1352 DstM.getModuleIdentifier() + "'");
1353 }
1354
1355 auto ensureDistinctOp = [&](MDNode *DstValue) {
1356 assert(isa<MDTuple>(DstValue) &&
1357 "Expected MDTuple when appending module flags");
1358 if (DstValue->isDistinct())
1359 return dyn_cast<MDTuple>(DstValue);
1360 ArrayRef<MDOperand> DstOperands = DstValue->operands();
1362 DstM.getContext(), SmallVector<Metadata *, 4>(DstOperands));
1363 Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New};
1364 MDNode *Flag = MDTuple::getDistinct(DstM.getContext(), FlagOps);
1365 DstModFlags->setOperand(DstIndex, Flag);
1366 Flags[ID].first = Flag;
1367 return New;
1368 };
1369
1370 // Emit a warning if the values differ and either source or destination
1371 // request Warning behavior.
1372 if ((DstBehaviorValue == Module::Warning ||
1373 SrcBehaviorValue == Module::Warning) &&
1374 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1375 std::string Str;
1377 << "linking module flags '" << ID->getString()
1378 << "': IDs have conflicting values ('" << *SrcOp->getOperand(2)
1379 << "' from " << SrcM->getModuleIdentifier() << " with '"
1380 << *DstOp->getOperand(2) << "' from " << DstM.getModuleIdentifier()
1381 << ')';
1382 emitWarning(Str);
1383 }
1384
1385 // Choose the minimum if either source or destination request Min behavior.
1386 if (DstBehaviorValue == Module::Min || SrcBehaviorValue == Module::Min) {
1387 ConstantInt *DstValue =
1388 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1389 ConstantInt *SrcValue =
1390 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1391
1392 // The resulting flag should have a Min behavior, and contain the minimum
1393 // value from between the source and destination values.
1394 Metadata *FlagOps[] = {
1395 (DstBehaviorValue != Module::Min ? SrcOp : DstOp)->getOperand(0), ID,
1396 (SrcValue->getZExtValue() < DstValue->getZExtValue() ? SrcOp : DstOp)
1397 ->getOperand(2)};
1398 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1399 DstModFlags->setOperand(DstIndex, Flag);
1400 Flags[ID].first = Flag;
1401 continue;
1402 }
1403
1404 // Choose the maximum if either source or destination request Max behavior.
1405 if (DstBehaviorValue == Module::Max || SrcBehaviorValue == Module::Max) {
1406 ConstantInt *DstValue =
1407 mdconst::extract<ConstantInt>(DstOp->getOperand(2));
1408 ConstantInt *SrcValue =
1409 mdconst::extract<ConstantInt>(SrcOp->getOperand(2));
1410
1411 // The resulting flag should have a Max behavior, and contain the maximum
1412 // value from between the source and destination values.
1413 Metadata *FlagOps[] = {
1414 (DstBehaviorValue != Module::Max ? SrcOp : DstOp)->getOperand(0), ID,
1415 (SrcValue->getZExtValue() > DstValue->getZExtValue() ? SrcOp : DstOp)
1416 ->getOperand(2)};
1417 MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps);
1418 DstModFlags->setOperand(DstIndex, Flag);
1419 Flags[ID].first = Flag;
1420 continue;
1421 }
1422
1423 // Perform the merge for standard behavior types.
1424 switch (SrcBehaviorValue) {
1425 case Module::Require:
1426 case Module::Override:
1427 llvm_unreachable("not possible");
1428 case Module::Error: {
1429 // Emit an error if the values differ.
1430 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1431 std::string Str;
1433 << "linking module flags '" << ID->getString()
1434 << "': IDs have conflicting values: '" << *SrcOp->getOperand(2)
1435 << "' from " << SrcM->getModuleIdentifier() << ", and '"
1436 << *DstOp->getOperand(2) << "' from " + DstM.getModuleIdentifier();
1437 return stringErr(Str);
1438 }
1439 continue;
1440 }
1441 case Module::Warning: {
1442 break;
1443 }
1444 case Module::Max: {
1445 break;
1446 }
1447 case Module::Append: {
1448 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1449 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1450 for (const auto &O : SrcValue->operands())
1451 DstValue->push_back(O);
1452 break;
1453 }
1454 case Module::AppendUnique: {
1456 MDTuple *DstValue = ensureDistinctOp(cast<MDNode>(DstOp->getOperand(2)));
1457 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1458 Elts.insert(DstValue->op_begin(), DstValue->op_end());
1459 Elts.insert(SrcValue->op_begin(), SrcValue->op_end());
1460 for (auto I = DstValue->getNumOperands(); I < Elts.size(); I++)
1461 DstValue->push_back(Elts[I]);
1462 break;
1463 }
1464 }
1465
1466 }
1467
1468 // For the Min behavior, set the value to 0 if either module does not have the
1469 // flag.
1470 for (auto Idx : Mins) {
1471 MDNode *Op = DstModFlags->getOperand(Idx);
1472 MDString *ID = cast<MDString>(Op->getOperand(1));
1473 if (!SeenMin.count(ID)) {
1474 ConstantInt *V = mdconst::extract<ConstantInt>(Op->getOperand(2));
1475 Metadata *FlagOps[] = {
1476 Op->getOperand(0), ID,
1477 ConstantAsMetadata::get(ConstantInt::get(V->getType(), 0))};
1478 DstModFlags->setOperand(Idx, MDNode::get(DstM.getContext(), FlagOps));
1479 }
1480 }
1481
1482 // Check all of the requirements.
1483 for (MDNode *Requirement : Requirements) {
1484 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1485 Metadata *ReqValue = Requirement->getOperand(1);
1486
1487 MDNode *Op = Flags[Flag].first;
1488 if (!Op || Op->getOperand(2) != ReqValue)
1489 return stringErr("linking module flags '" + Flag->getString() +
1490 "': does not have the required value");
1491 }
1492 return Error::success();
1493}
1494
1495/// Return InlineAsm adjusted with target-specific directives if required.
1496/// For ARM and Thumb, we have to add directives to select the appropriate ISA
1497/// to support mixing module-level inline assembly from ARM and Thumb modules.
1498static std::string adjustInlineAsm(const std::string &InlineAsm,
1499 const Triple &Triple) {
1501 return ".text\n.balign 2\n.thumb\n" + InlineAsm;
1503 return ".text\n.balign 4\n.arm\n" + InlineAsm;
1504 return InlineAsm;
1505}
1506
1507void IRLinker::updateAttributes(GlobalValue &GV) {
1508 /// Remove nocallback attribute while linking, because nocallback attribute
1509 /// indicates that the function is only allowed to jump back into caller's
1510 /// module only by a return or an exception. When modules are linked, this
1511 /// property cannot be guaranteed anymore. For example, the nocallback
1512 /// function may contain a call to another module. But if we merge its caller
1513 /// and callee module here, and not the module containing the nocallback
1514 /// function definition itself, the nocallback property will be violated
1515 /// (since the nocallback function will call back into the newly merged module
1516 /// containing both its caller and callee). This could happen if the module
1517 /// containing the nocallback function definition is native code, so it does
1518 /// not participate in the LTO link. Note if the nocallback function does
1519 /// participate in the LTO link, and thus ends up in the merged module
1520 /// containing its caller and callee, removing the attribute doesn't hurt as
1521 /// it has no effect on definitions in the same module.
1522 if (auto *F = dyn_cast<Function>(&GV)) {
1523 if (!F->isIntrinsic())
1524 F->removeFnAttr(llvm::Attribute::NoCallback);
1525
1526 // Remove nocallback attribute when it is on a call-site.
1527 for (BasicBlock &BB : *F)
1528 for (Instruction &I : BB)
1529 if (CallBase *CI = dyn_cast<CallBase>(&I))
1530 CI->removeFnAttr(Attribute::NoCallback);
1531 }
1532}
1533
1534Error IRLinker::run() {
1535 // Ensure metadata materialized before value mapping.
1536 if (SrcM->getMaterializer())
1537 if (Error Err = SrcM->getMaterializer()->materializeMetadata())
1538 return Err;
1539
1540 // Convert source module to match dest for the duration of the link.
1541 ScopedDbgInfoFormatSetter FormatSetter(*SrcM, DstM.IsNewDbgInfoFormat);
1542
1543 // Inherit the target data from the source module if the destination
1544 // module doesn't have one already.
1545 if (DstM.getDataLayout().isDefault())
1546 DstM.setDataLayout(SrcM->getDataLayout());
1547
1548 // Copy the target triple from the source to dest if the dest's is empty.
1549 if (DstM.getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1550 DstM.setTargetTriple(SrcM->getTargetTriple());
1551
1552 Triple SrcTriple(SrcM->getTargetTriple()), DstTriple(DstM.getTargetTriple());
1553
1554 // During CUDA compilation we have to link with the bitcode supplied with
1555 // CUDA. libdevice bitcode either has no data layout set (pre-CUDA-11), or has
1556 // the layout that is different from the one used by LLVM/clang (it does not
1557 // include i128). Issuing a warning is not very helpful as there's not much
1558 // the user can do about it.
1559 bool EnableDLWarning = true;
1560 bool EnableTripleWarning = true;
1561 if (SrcTriple.isNVPTX() && DstTriple.isNVPTX()) {
1562 bool SrcHasLibDeviceDL =
1563 (SrcM->getDataLayoutStr().empty() ||
1564 SrcM->getDataLayoutStr() == "e-i64:64-v16:16-v32:32-n16:32:64");
1565 // libdevice bitcode uses nvptx64-nvidia-gpulibs or just
1566 // 'nvptx-unknown-unknown' triple (before CUDA-10.x) and is compatible with
1567 // all NVPTX variants.
1568 bool SrcHasLibDeviceTriple = (SrcTriple.getVendor() == Triple::NVIDIA &&
1569 SrcTriple.getOSName() == "gpulibs") ||
1570 (SrcTriple.getVendorName() == "unknown" &&
1571 SrcTriple.getOSName() == "unknown");
1572 EnableTripleWarning = !SrcHasLibDeviceTriple;
1573 EnableDLWarning = !(SrcHasLibDeviceTriple && SrcHasLibDeviceDL);
1574 }
1575
1576 if (EnableDLWarning && (SrcM->getDataLayout() != DstM.getDataLayout())) {
1577 emitWarning("Linking two modules of different data layouts: '" +
1578 SrcM->getModuleIdentifier() + "' is '" +
1579 SrcM->getDataLayoutStr() + "' whereas '" +
1580 DstM.getModuleIdentifier() + "' is '" +
1581 DstM.getDataLayoutStr() + "'\n");
1582 }
1583
1584 if (EnableTripleWarning && !SrcM->getTargetTriple().empty() &&
1585 !SrcTriple.isCompatibleWith(DstTriple))
1586 emitWarning("Linking two modules of different target triples: '" +
1587 SrcM->getModuleIdentifier() + "' is '" +
1588 SrcM->getTargetTriple() + "' whereas '" +
1589 DstM.getModuleIdentifier() + "' is '" + DstM.getTargetTriple() +
1590 "'\n");
1591
1592 DstM.setTargetTriple(SrcTriple.merge(DstTriple));
1593
1594 // Loop over all of the linked values to compute type mappings.
1595 computeTypeMapping();
1596
1597 std::reverse(Worklist.begin(), Worklist.end());
1598 while (!Worklist.empty()) {
1599 GlobalValue *GV = Worklist.back();
1600 Worklist.pop_back();
1601
1602 // Already mapped.
1603 if (ValueMap.find(GV) != ValueMap.end() ||
1604 IndirectSymbolValueMap.find(GV) != IndirectSymbolValueMap.end())
1605 continue;
1606
1607 assert(!GV->isDeclaration());
1608 Mapper.mapValue(*GV);
1609 if (FoundError)
1610 return std::move(*FoundError);
1611 flushRAUWWorklist();
1612 }
1613
1614 // Note that we are done linking global value bodies. This prevents
1615 // metadata linking from creating new references.
1616 DoneLinkingBodies = true;
1618
1619 // Remap all of the named MDNodes in Src into the DstM module. We do this
1620 // after linking GlobalValues so that MDNodes that reference GlobalValues
1621 // are properly remapped.
1622 linkNamedMDNodes();
1623
1624 // Clean up any global objects with potentially unmapped metadata.
1625 // Specifically declarations which did not become definitions.
1626 for (GlobalObject *NGO : UnmappedMetadata) {
1627 if (NGO->isDeclaration())
1628 Mapper.remapGlobalObjectMetadata(*NGO);
1629 }
1630
1631 if (!IsPerformingImport && !SrcM->getModuleInlineAsm().empty()) {
1632 // Append the module inline asm string.
1633 DstM.appendModuleInlineAsm(adjustInlineAsm(SrcM->getModuleInlineAsm(),
1634 SrcTriple));
1635 } else if (IsPerformingImport) {
1636 // Import any symver directives for symbols in DstM.
1638 [&](StringRef Name, StringRef Alias) {
1639 if (DstM.getNamedValue(Name)) {
1640 SmallString<256> S(".symver ");
1641 S += Name;
1642 S += ", ";
1643 S += Alias;
1644 DstM.appendModuleInlineAsm(S);
1645 }
1646 });
1647 }
1648
1649 // Reorder the globals just added to the destination module to match their
1650 // original order in the source module.
1651 for (GlobalVariable &GV : SrcM->globals()) {
1652 if (GV.hasAppendingLinkage())
1653 continue;
1654 Value *NewValue = Mapper.mapValue(GV);
1655 if (NewValue) {
1656 auto *NewGV = dyn_cast<GlobalVariable>(NewValue->stripPointerCasts());
1657 if (NewGV) {
1658 NewGV->removeFromParent();
1659 DstM.insertGlobalVariable(NewGV);
1660 }
1661 }
1662 }
1663
1664 // Merge the module flags into the DstM module.
1665 return linkModuleFlagsMetadata();
1666}
1667
1669 : ETypes(E), IsPacked(P) {}
1670
1672 : ETypes(ST->elements()), IsPacked(ST->isPacked()) {}
1673
1675 return IsPacked == That.IsPacked && ETypes == That.ETypes;
1676}
1677
1679 return !this->operator==(That);
1680}
1681
1682StructType *IRMover::StructTypeKeyInfo::getEmptyKey() {
1684}
1685
1686StructType *IRMover::StructTypeKeyInfo::getTombstoneKey() {
1688}
1689
1690unsigned IRMover::StructTypeKeyInfo::getHashValue(const KeyTy &Key) {
1691 return hash_combine(hash_combine_range(Key.ETypes.begin(), Key.ETypes.end()),
1692 Key.IsPacked);
1693}
1694
1695unsigned IRMover::StructTypeKeyInfo::getHashValue(const StructType *ST) {
1696 return getHashValue(KeyTy(ST));
1697}
1698
1699bool IRMover::StructTypeKeyInfo::isEqual(const KeyTy &LHS,
1700 const StructType *RHS) {
1701 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1702 return false;
1703 return LHS == KeyTy(RHS);
1704}
1705
1706bool IRMover::StructTypeKeyInfo::isEqual(const StructType *LHS,
1707 const StructType *RHS) {
1708 if (RHS == getEmptyKey() || RHS == getTombstoneKey())
1709 return LHS == RHS;
1710 return KeyTy(LHS) == KeyTy(RHS);
1711}
1712
1714 assert(!Ty->isOpaque());
1715 NonOpaqueStructTypes.insert(Ty);
1716}
1717
1719 assert(!Ty->isOpaque());
1720 NonOpaqueStructTypes.insert(Ty);
1721 bool Removed = OpaqueStructTypes.erase(Ty);
1722 (void)Removed;
1723 assert(Removed);
1724}
1725
1727 assert(Ty->isOpaque());
1728 OpaqueStructTypes.insert(Ty);
1729}
1730
1731StructType *
1733 bool IsPacked) {
1734 IRMover::StructTypeKeyInfo::KeyTy Key(ETypes, IsPacked);
1735 auto I = NonOpaqueStructTypes.find_as(Key);
1736 return I == NonOpaqueStructTypes.end() ? nullptr : *I;
1737}
1738
1740 if (Ty->isOpaque())
1741 return OpaqueStructTypes.count(Ty);
1742 auto I = NonOpaqueStructTypes.find(Ty);
1743 return I == NonOpaqueStructTypes.end() ? false : *I == Ty;
1744}
1745
1746IRMover::IRMover(Module &M) : Composite(M) {
1747 TypeFinder StructTypes;
1748 StructTypes.run(M, /* OnlyNamed */ false);
1749 for (StructType *Ty : StructTypes) {
1750 if (Ty->isOpaque())
1751 IdentifiedStructTypes.addOpaque(Ty);
1752 else
1753 IdentifiedStructTypes.addNonOpaque(Ty);
1754 }
1755 // Self-map metadatas in the destination module. This is needed when
1756 // DebugTypeODRUniquing is enabled on the LLVMContext, since metadata in the
1757 // destination module may be reached from the source module.
1758 for (const auto *MD : StructTypes.getVisitedMetadata()) {
1759 SharedMDs[MD].reset(const_cast<MDNode *>(MD));
1760 }
1761}
1762
1763Error IRMover::move(std::unique_ptr<Module> Src,
1764 ArrayRef<GlobalValue *> ValuesToLink,
1765 LazyCallback AddLazyFor, bool IsPerformingImport) {
1766 IRLinker TheIRLinker(Composite, SharedMDs, IdentifiedStructTypes,
1767 std::move(Src), ValuesToLink, std::move(AddLazyFor),
1768 IsPerformingImport);
1769 Error E = TheIRLinker.run();
1771 return E;
1772}
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:551
static void getArrayElements(const Constant *C, SmallVectorImpl< Constant * > &Dest)
Definition: IRMover.cpp:865
static std::string adjustInlineAsm(const std::string &InlineAsm, const Triple &Triple)
Return InlineAsm adjusted with target-specific directives if required.
Definition: IRMover.cpp:1498
static StringRef getTypeNamePrefix(StringRef Name)
Definition: IRMover.cpp:766
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
#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:1112
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:47
static ConstantAsMetadata * get(Constant *C)
Definition: Metadata.h:532
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:249
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:547
bool hasLocalLinkage() const
Definition: GlobalValue.h:529
const Comdat * getComdat() const
Definition: Globals.cpp:199
bool hasExternalWeakLinkage() const
Definition: GlobalValue.h:530
ThreadLocalMode getThreadLocalMode() const
Definition: GlobalValue.h:272
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:538
bool isDeclarationForLinker() const
Definition: GlobalValue.h:619
unsigned getAddressSpace() const
Definition: GlobalValue.h:206
Module * getParent()
Get the module that this global value is contained inside of...
Definition: GlobalValue.h:657
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:295
bool hasGlobalUnnamedAddr() const
Definition: GlobalValue.h:216
bool hasAppendingLinkage() const
Definition: GlobalValue.h:526
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:297
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:1718
StructType * findNonOpaque(ArrayRef< Type * > ETypes, bool IsPacked)
Definition: IRMover.cpp:1732
IRMover(Module &M)
Definition: IRMover.cpp:1746
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:1763
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:342
void print(DiagnosticPrinter &DP) const override
Print using the given DP a user-friendly message.
Definition: IRMover.cpp:345
Metadata node.
Definition: Metadata.h:1073
ArrayRef< MDOperand > operands() const
Definition: Metadata.h:1432
op_iterator op_end() const
Definition: Metadata.h:1428
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Definition: Metadata.h:1549
unsigned getNumOperands() const
Return number of MDNode operands.
Definition: Metadata.h:1440
op_iterator op_begin() const
Definition: Metadata.h:1424
A single uniqued string.
Definition: Metadata.h:724
Tuple of metadata.
Definition: Metadata.h:1479
static MDTuple * getDistinct(LLVMContext &Context, ArrayRef< Metadata * > MDs)
Return a distinct node.
Definition: Metadata.h:1517
void push_back(Metadata *MD)
Append an element to the tuple. This will resize the node.
Definition: Metadata.h:1535
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:1737
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:1833
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
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:395
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
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.
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:409
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:1668
bool operator==(const KeyTy &that) const
Definition: IRMover.cpp:1674
bool operator!=(const KeyTy &that) const
Definition: IRMover.cpp:1678