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