30 void ValueMapTypeRemapper::anchor() {}
31 void ValueMaterializer::anchor() {}
37 struct DelayedBasicBlock {
39 std::unique_ptr<BasicBlock> TempBB;
42 : OldBB(Old.getBasicBlock()),
43 TempBB(
BasicBlock::Create(Old.getContext())) {}
46 struct WorklistEntry {
57 struct AppendingGVTy {
61 struct GlobalAliaseeTy {
68 unsigned AppendingGVIsOldCtorDtor : 1;
69 unsigned AppendingGVNumNewMembers;
72 AppendingGVTy AppendingGV;
73 GlobalAliaseeTy GlobalAliasee;
78 struct MappingContext {
85 : VM(&VM), Materializer(Materializer) {}
90 friend class MDNodeMapper;
98 unsigned CurrentMCID = 0;
107 : Flags(Flags), TypeMapper(TypeMapper),
108 MCs(1, MappingContext(VM, Materializer)) {}
111 ~Mapper() {
assert(!hasWorkToDo() &&
"Expected to be flushed"); }
113 bool hasWorkToDo()
const {
return !Worklist.empty(); }
118 MCs.push_back(MappingContext(VM, Materializer));
119 return MCs.size() - 1;
131 return cast_or_null<Constant>(mapValue(C));
148 void scheduleRemapFunction(
Function &
F,
unsigned MCID);
177 bool HasChanged =
false;
179 TempMDNode Placeholder;
183 struct UniquedGraph {
191 void propagateChanges();
205 MDNodeMapper(Mapper &M) : M(M) {}
285 bool createPOT(UniquedGraph &
G,
const MDNode &FirstN);
307 void mapNodesInPOT(UniquedGraph &
G);
315 template <
class OperandMapper>
316 void remapOperands(
MDNode &
N, OperandMapper mapOperand);
325 if (I != getVM().
end()) {
331 if (
auto *Materializer = getMaterializer()) {
332 if (
Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
340 if (isa<GlobalValue>(V)) {
343 return getVM()[V] =
const_cast<Value *
>(V);
346 if (
const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
350 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
352 if (NewTy != IA->getFunctionType())
353 V =
InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
354 IA->hasSideEffects(), IA->isAlignStack());
357 return getVM()[V] =
const_cast<Value *
>(V);
360 if (
const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
361 const Metadata *MD = MDV->getMetadata();
363 if (
auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
365 if (
Value *LV = mapValue(LAM->getValue())) {
366 if (V == LAM->getValue())
367 return const_cast<Value *>(V);
382 return getVM()[V] =
const_cast<Value *
>(V);
385 auto *MappedMD = mapMetadata(MD);
387 return getVM()[V] =
const_cast<Value *
>(V);
398 return mapBlockAddress(*BA);
400 auto mapValueOrNull = [
this](
Value *V) {
401 auto Mapped = mapValue(V);
403 "Unexpected null mapping for constant operand without "
404 "NullMapMissingGlobalValues flag");
411 Value *Mapped =
nullptr;
412 for (; OpNo != NumOperands; ++OpNo) {
414 Mapped = mapValueOrNull(Op);
424 NewTy = TypeMapper->remapType(NewTy);
428 if (OpNo == NumOperands && NewTy == C->
getType())
429 return getVM()[V] =
C;
435 for (
unsigned j = 0; j != OpNo; ++j)
439 if (OpNo != NumOperands) {
443 for (++OpNo; OpNo != NumOperands; ++OpNo) {
450 Type *NewSrcTy =
nullptr;
452 if (
auto *GEPO = dyn_cast<GEPOperator>(C))
453 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
456 return getVM()[V] =
CE->getWithOperands(Ops, NewTy,
false, NewSrcTy);
457 if (isa<ConstantArray>(C))
459 if (isa<ConstantStruct>(C))
461 if (isa<ConstantVector>(C))
464 if (isa<UndefValue>(C))
466 if (isa<ConstantAggregateZero>(C))
468 assert(isa<ConstantPointerNull>(C));
480 DelayedBBs.push_back(DelayedBasicBlock(BA));
481 BB = DelayedBBs.
back().TempBB.get();
490 getVM().MD()[Key].reset(Val);
495 return mapToMetadata(MD, const_cast<Metadata *>(MD));
504 if (
auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
505 assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
506 M.getVM().getMappedMD(Op)) &&
507 "Expected Value to be memoized");
509 assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
510 "Expected result to be memoized");
517 return mapDistinctNode(N);
521 MDNode *MDNodeMapper::mapDistinctNode(
const MDNode &N) {
523 assert(!M.getVM().getMappedMD(&N) &&
"Expected an unmapped node");
524 DistinctWorklist.push_back(cast<MDNode>(
528 return DistinctWorklist.back();
534 return const_cast<ConstantAsMetadata *>(&CMD);
545 if (isa<MDString>(Op))
546 return const_cast<Metadata *>(Op);
548 if (
auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
554 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(
MDNode &Op) {
555 auto Where = Info.find(&Op);
556 assert(Where != Info.end() &&
"Expected a valid reference");
558 auto &OpD = Where->second;
563 if (!OpD.Placeholder)
564 OpD.Placeholder = Op.
clone();
566 return *OpD.Placeholder;
569 template <
class OperandMapper>
570 void MDNodeMapper::remapOperands(
MDNode &N, OperandMapper mapOperand) {
583 struct POTWorklistEntry {
589 bool HasChanged =
false;
591 POTWorklistEntry(
MDNode &N) : N(&N), Op(N.op_begin()) {}
595 bool MDNodeMapper::createPOT(UniquedGraph &
G,
const MDNode &FirstN) {
596 assert(G.Info.empty() &&
"Expected a fresh traversal");
600 bool AnyChanges =
false;
602 Worklist.
push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
603 (void)G.Info[&FirstN];
604 while (!Worklist.
empty()) {
606 auto &WE = Worklist.
back();
607 if (
MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
609 Worklist.
push_back(POTWorklistEntry(*N));
614 assert(WE.N->isUniqued() &&
"Expected only uniqued nodes");
615 assert(WE.Op == WE.N->op_end() &&
"Expected to visit all operands");
616 auto &
D = G.Info[WE.N];
617 AnyChanges |= D.HasChanged = WE.HasChanged;
619 G.POT.push_back(WE.N);
633 HasChanged |= Op != *MappedOp;
640 "Only uniqued operands cannot be mapped immediately");
641 if (G.Info.insert(std::make_pair(&OpN,
Data())).second)
647 void MDNodeMapper::UniquedGraph::propagateChanges() {
657 auto Where = Info.find(Op);
658 return Where != Info.
end() && Where->second.HasChanged;
662 AnyChanges = D.HasChanged =
true;
664 }
while (AnyChanges);
667 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
670 for (
auto *N : G.POT) {
679 bool HadPlaceholder(D.Placeholder);
682 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
683 remapOperands(*ClonedN, [
this, &D, &G](
Metadata *Old) {
687 assert(G.Info[Old].ID > D.ID &&
"Expected a forward reference");
688 return &G.getFwdReference(*cast<MDNode>(Old));
692 M.mapToMetadata(N, NewN);
701 for (
auto *N : CyclicNodes)
707 assert(DistinctWorklist.empty() &&
"MDNodeMapper::map is not recursive");
708 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
709 "MDNodeMapper::map assumes module-level changes");
715 N.
isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
716 while (!DistinctWorklist.empty())
717 remapOperands(*DistinctWorklist.pop_back_val(), [
this](
Metadata *Old) {
720 return mapTopLevelUniquedNode(*cast<MDNode>(Old));
725 Metadata *MDNodeMapper::mapTopLevelUniquedNode(
const MDNode &FirstN) {
730 if (!createPOT(G, FirstN)) {
732 for (
const MDNode *N : G.POT)
734 return &
const_cast<MDNode &
>(FirstN);
738 G.propagateChanges();
744 return *getMappedOp(&FirstN);
749 struct MapMetadataDisabler {
765 if (isa<MDString>(MD))
770 if ((
Flags & RF_NoModuleLevelChanges))
771 return const_cast<Metadata *>(MD);
773 if (
auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
775 MapMetadataDisabler MMD(getVM());
784 assert(isa<MDNode>(MD) &&
"Expected a metadata node");
790 assert(MD &&
"Expected valid metadata");
791 assert(!isa<LocalAsMetadata>(MD) &&
"Unexpected local metadata");
796 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
799 void Mapper::flush() {
801 while (!Worklist.
empty()) {
803 CurrentMCID = E.MCID;
805 case WorklistEntry::MapGlobalInit:
806 E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
807 remapGlobalObjectMetadata(*E.Data.GVInit.GV);
809 case WorklistEntry::MapAppendingVar: {
810 unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
811 mapAppendingVariable(*E.Data.AppendingGV.GV,
812 E.Data.AppendingGV.InitPrefix,
813 E.AppendingGVIsOldCtorDtor,
815 AppendingInits.resize(PrefixSize);
818 case WorklistEntry::MapGlobalAliasee:
819 E.Data.GlobalAliasee.GA->setAliasee(
820 mapConstant(E.Data.GlobalAliasee.Aliasee));
823 remapFunction(*E.Data.RemapF);
831 while (!DelayedBBs.empty()) {
832 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
833 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
834 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
841 Value *V = mapValue(Op);
847 "Referenced value not in value map!");
851 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
852 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
853 Value *V = mapValue(PN->getIncomingBlock(i));
856 PN->setIncomingBlock(i, cast<BasicBlock>(V));
859 "Referenced block not in value map!");
866 for (
const auto &
MI : MDs) {
868 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
882 Tys.
push_back(TypeMapper->remapType(Ty));
887 if (
auto *AI = dyn_cast<AllocaInst>(I))
888 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
889 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I)) {
890 GEP->setSourceElementType(
891 TypeMapper->remapType(
GEP->getSourceElementType()));
892 GEP->setResultElementType(
893 TypeMapper->remapType(
GEP->getResultElementType()));
898 void Mapper::remapGlobalObjectMetadata(
GlobalObject &GO) {
902 for (
const auto &I : MDs)
903 GO.
addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
906 void Mapper::remapFunction(
Function &F) {
913 remapGlobalObjectMetadata(F);
918 A.mutateType(TypeMapper->remapType(
A.getType()));
931 unsigned NumElements =
932 cast<ArrayType>(InitPrefix->
getType())->getNumElements();
933 for (
unsigned I = 0; I != NumElements; ++
I)
944 Type *Tys[3] = {
ST.getElementType(0),
ST.getElementType(1), VoidPtrTy};
948 for (
auto *V : NewMembers) {
951 auto *S = cast<ConstantStruct>(V);
952 auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
953 auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
957 NewV = cast_or_null<Constant>(mapValue(V));
968 assert(AlreadyScheduled.insert(&GV).second &&
"Should not reschedule");
969 assert(MCID < MCs.size() &&
"Invalid mapping context");
972 WE.Kind = WorklistEntry::MapGlobalInit;
974 WE.Data.GVInit.GV = &GV;
975 WE.Data.GVInit.Init = &Init;
984 assert(AlreadyScheduled.insert(&GV).second &&
"Should not reschedule");
985 assert(MCID < MCs.size() &&
"Invalid mapping context");
988 WE.Kind = WorklistEntry::MapAppendingVar;
990 WE.Data.AppendingGV.GV = &GV;
991 WE.Data.AppendingGV.InitPrefix = InitPrefix;
992 WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
993 WE.AppendingGVNumNewMembers = NewMembers.
size();
995 AppendingInits.append(NewMembers.
begin(), NewMembers.
end());
1000 assert(AlreadyScheduled.insert(&GA).second &&
"Should not reschedule");
1001 assert(MCID < MCs.size() &&
"Invalid mapping context");
1004 WE.Kind = WorklistEntry::MapGlobalAliasee;
1006 WE.Data.GlobalAliasee.GA = &GA;
1007 WE.Data.GlobalAliasee.Aliasee = &Aliasee;
1011 void Mapper::scheduleRemapFunction(
Function &F,
unsigned MCID) {
1012 assert(AlreadyScheduled.insert(&F).second &&
"Should not reschedule");
1013 assert(MCID < MCs.size() &&
"Invalid mapping context");
1018 WE.Data.RemapF = &
F;
1023 assert(!hasWorkToDo() &&
"Expected to have flushed the worklist");
1024 this->Flags = this->Flags |
Flags;
1028 return reinterpret_cast<Mapper *
>(pImpl);
1033 class FlushingMapper {
1037 explicit FlushingMapper(
void *pImpl) : M(*
getAsMapper(pImpl)) {
1038 assert(!M.hasWorkToDo() &&
"Expected to be flushed");
1040 ~FlushingMapper() { M.flush(); }
1041 Mapper *operator->()
const {
return &M; }
1049 : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1056 return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1060 FlushingMapper(pImpl)->addFlags(Flags);
1064 return FlushingMapper(pImpl)->mapValue(&V);
1068 return cast_or_null<Constant>(
mapValue(C));
1072 return FlushingMapper(pImpl)->mapMetadata(&MD);
1080 FlushingMapper(pImpl)->remapInstruction(&I);
1084 FlushingMapper(pImpl)->remapFunction(F);
1090 getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1099 GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1104 getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
1108 getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Appends all attachments for the global to MDs, sorting by attachment ID.
void push_back(const T &Elt)
const_iterator end(StringRef path)
Get end iterator over path.
Tracking metadata reference owned by Metadata.
This class represents an incoming formal argument to a Function.
const Instruction & back() const
static void remapInstruction(Instruction *I, ValueToValueMapTy &VMap)
Convert the instruction operands from referencing the current values into those specified by VMap...
unsigned getNumParams() const
Return the number of fixed parameters this function type requires.
void replaceOperandWith(unsigned I, Metadata *New)
Replace a specific operand.
const T & front() const
front - Get the first element.
void RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Remap the operands, metadata, arguments, and instructions of a function.
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
unsigned getNumOperands() const
Return number of MDNode operands.
Any global values not in value map are mapped to null instead of mapping to self. ...
static ConstantAggregateZero * get(Type *Ty)
ArrayRef< Type * > params() const
void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
void getAllMetadata(SmallVectorImpl< std::pair< unsigned, MDNode * >> &MDs) const
Get all metadata attached to this Instruction.
Type * getElementType() const
void reserve(size_type N)
static Mapper * getAsMapper(void *pImpl)
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static std::enable_if< std::is_base_of< MDNode, T >::value, T * >::type replaceWithDistinct(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a distinct one.
The address of a basic block.
ArrayRef< T > makeArrayRef(const T &OneElt)
Construct an ArrayRef from a single element.
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
void remapInstruction(Instruction &I)
A Use represents the edge between a Value definition and its users.
Constant * mapConstant(const Constant &C)
static Constant * get(ArrayRef< Constant * > V)
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly...
Windows NT (Windows on ARM)
void resolveCycles()
Resolve cycles.
LLVM_NODISCARD bool empty() const
A constant value that is initialized with an expression using other constant values.
Class to represent function types.
Metadata * mapMetadata(const Metadata &MD)
Instruct the remapper to move distinct metadata instead of duplicating it when there are module-level...
static FunctionType * get(Type *Result, ArrayRef< Type * > Params, bool isVarArg)
This static method is the primary way of constructing a FunctionType.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
size_t size() const
size - Get the array size.
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Class to represent pointers.
This is a class that can be implemented by clients to materialize Values on demand.
static std::enable_if< std::is_base_of< MDNode, T >::value, T * >::type replaceWithUniqued(std::unique_ptr< T, TempMDNodeDeleter > N)
Replace a temporary node with a uniqued one.
static ConstantPointerNull * get(PointerType *T)
Static factory methods - Return objects of the specified value.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
static ConstantAsMetadata * wrapConstantAsMetadata(const ConstantAsMetadata &CMD, Value *MappedV)
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static MDTuple * get(LLVMContext &Context, ArrayRef< Metadata * > MDs)
This is an important base class in LLVM.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static Constant * get(ArrayType *T, ArrayRef< Constant * > V)
void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
Value * getOperand(unsigned i) const
void disableMapMetadata()
static Constant * get(StructType *T, ArrayRef< Constant * > V)
Constant * getAggregateElement(unsigned Elt) const
For aggregates (struct/array/vector) return the constant that corresponds to the specified element if...
TempMDNode clone() const
Create a (temporary) clone of this.
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
RemapFlags
These are flags that the value mapping APIs allow.
LLVMContext & getContext() const
All values hold a context through their type.
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
const MDOperand & getOperand(unsigned I) const
static StructType * get(LLVMContext &Context, ArrayRef< Type * > Elements, bool isPacked=false)
This static method is the primary way to create a literal StructType.
void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Type * getType() const
All values are typed, get the type of this value.
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
LLVM_NODISCARD T pop_back_val()
BasicBlock * getBasicBlock() const
void remapFunction(Function &F)
void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
If this flag is set, the remapper ignores missing function-local entries (Argument, Instruction, BasicBlock) that are not in the value map.
static std::vector< std::string > Flags
PointerType * getType() const
Global values are always pointers.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
op_range operands() const
static InlineAsm * get(FunctionType *Ty, StringRef AsmString, StringRef Constraints, bool hasSideEffects, bool isAlignStack=false, AsmDialect asmDialect=AD_ATT)
InlineAsm::get - Return the specified uniqued inline asm string.
void mutateType(Type *Ty)
Mutate the type of this Value to be of the specified type.
Value * mapValue(const Value &V)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
Function * getFunction() const
LLVM Value Representation.
unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
bool isResolved() const
Check if node is fully resolved.
static IntegerType * getInt8Ty(LLVMContext &C)
iterator_range< arg_iterator > args()
MDNode * mapMDNode(const MDNode &N)