xref: /llvm-project/llvm/lib/Transforms/Utils/ValueMapper.cpp (revision 2aaaed3527de891062e9503d09d42075049e05fa)
1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
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 //
9 // This file defines the MapValue function, which is shared by various parts of
10 // the lib/Transforms/Utils library.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/Transforms/Utils/ValueMapper.h"
15 #include "llvm/ADT/ArrayRef.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/DenseSet.h"
18 #include "llvm/ADT/STLExtras.h"
19 #include "llvm/ADT/SmallVector.h"
20 #include "llvm/IR/Argument.h"
21 #include "llvm/IR/BasicBlock.h"
22 #include "llvm/IR/Constant.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DebugInfoMetadata.h"
25 #include "llvm/IR/DerivedTypes.h"
26 #include "llvm/IR/Function.h"
27 #include "llvm/IR/GlobalAlias.h"
28 #include "llvm/IR/GlobalIFunc.h"
29 #include "llvm/IR/GlobalObject.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/InlineAsm.h"
32 #include "llvm/IR/Instruction.h"
33 #include "llvm/IR/Instructions.h"
34 #include "llvm/IR/Metadata.h"
35 #include "llvm/IR/Operator.h"
36 #include "llvm/IR/Type.h"
37 #include "llvm/IR/Value.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/Debug.h"
40 #include <cassert>
41 #include <limits>
42 #include <memory>
43 #include <utility>
44 
45 using namespace llvm;
46 
47 #define DEBUG_TYPE "value-mapper"
48 
49 // Out of line method to get vtable etc for class.
50 void ValueMapTypeRemapper::anchor() {}
51 void ValueMaterializer::anchor() {}
52 
53 namespace {
54 
55 /// A basic block used in a BlockAddress whose function body is not yet
56 /// materialized.
57 struct DelayedBasicBlock {
58   BasicBlock *OldBB;
59   std::unique_ptr<BasicBlock> TempBB;
60 
61   DelayedBasicBlock(const BlockAddress &Old)
62       : OldBB(Old.getBasicBlock()),
63         TempBB(BasicBlock::Create(Old.getContext())) {}
64 };
65 
66 struct WorklistEntry {
67   enum EntryKind {
68     MapGlobalInit,
69     MapAppendingVar,
70     MapAliasOrIFunc,
71     RemapFunction
72   };
73   struct GVInitTy {
74     GlobalVariable *GV;
75     Constant *Init;
76   };
77   struct AppendingGVTy {
78     GlobalVariable *GV;
79     Constant *InitPrefix;
80   };
81   struct AliasOrIFuncTy {
82     GlobalValue *GV;
83     Constant *Target;
84   };
85 
86   unsigned Kind : 2;
87   unsigned MCID : 29;
88   unsigned AppendingGVIsOldCtorDtor : 1;
89   unsigned AppendingGVNumNewMembers;
90   union {
91     GVInitTy GVInit;
92     AppendingGVTy AppendingGV;
93     AliasOrIFuncTy AliasOrIFunc;
94     Function *RemapF;
95   } Data;
96 };
97 
98 struct MappingContext {
99   ValueToValueMapTy *VM;
100   ValueMaterializer *Materializer = nullptr;
101 
102   /// Construct a MappingContext with a value map and materializer.
103   explicit MappingContext(ValueToValueMapTy &VM,
104                           ValueMaterializer *Materializer = nullptr)
105       : VM(&VM), Materializer(Materializer) {}
106 };
107 
108 class Mapper {
109   friend class MDNodeMapper;
110 
111 #ifndef NDEBUG
112   DenseSet<GlobalValue *> AlreadyScheduled;
113 #endif
114 
115   RemapFlags Flags;
116   ValueMapTypeRemapper *TypeMapper;
117   unsigned CurrentMCID = 0;
118   SmallVector<MappingContext, 2> MCs;
119   SmallVector<WorklistEntry, 4> Worklist;
120   SmallVector<DelayedBasicBlock, 1> DelayedBBs;
121   SmallVector<Constant *, 16> AppendingInits;
122 
123 public:
124   Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
125          ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
126       : Flags(Flags), TypeMapper(TypeMapper),
127         MCs(1, MappingContext(VM, Materializer)) {}
128 
129   /// ValueMapper should explicitly call \a flush() before destruction.
130   ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
131 
132   bool hasWorkToDo() const { return !Worklist.empty(); }
133 
134   unsigned
135   registerAlternateMappingContext(ValueToValueMapTy &VM,
136                                   ValueMaterializer *Materializer = nullptr) {
137     MCs.push_back(MappingContext(VM, Materializer));
138     return MCs.size() - 1;
139   }
140 
141   void addFlags(RemapFlags Flags);
142 
143   void remapGlobalObjectMetadata(GlobalObject &GO);
144 
145   Value *mapValue(const Value *V);
146   void remapInstruction(Instruction *I);
147   void remapFunction(Function &F);
148 
149   Constant *mapConstant(const Constant *C) {
150     return cast_or_null<Constant>(mapValue(C));
151   }
152 
153   /// Map metadata.
154   ///
155   /// Find the mapping for MD.  Guarantees that the return will be resolved
156   /// (not an MDNode, or MDNode::isResolved() returns true).
157   Metadata *mapMetadata(const Metadata *MD);
158 
159   void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
160                                     unsigned MCID);
161   void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
162                                     bool IsOldCtorDtor,
163                                     ArrayRef<Constant *> NewMembers,
164                                     unsigned MCID);
165   void scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
166                                unsigned MCID);
167   void scheduleRemapFunction(Function &F, unsigned MCID);
168 
169   void flush();
170 
171 private:
172   void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
173                             bool IsOldCtorDtor,
174                             ArrayRef<Constant *> NewMembers);
175 
176   ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
177   ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
178 
179   Value *mapBlockAddress(const BlockAddress &BA);
180 
181   /// Map metadata that doesn't require visiting operands.
182   std::optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
183 
184   Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
185   Metadata *mapToSelf(const Metadata *MD);
186 };
187 
188 class MDNodeMapper {
189   Mapper &M;
190 
191   /// Data about a node in \a UniquedGraph.
192   struct Data {
193     bool HasChanged = false;
194     unsigned ID = std::numeric_limits<unsigned>::max();
195     TempMDNode Placeholder;
196   };
197 
198   /// A graph of uniqued nodes.
199   struct UniquedGraph {
200     SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
201     SmallVector<MDNode *, 16> POT;                  // Post-order traversal.
202 
203     /// Propagate changed operands through the post-order traversal.
204     ///
205     /// Iteratively update \a Data::HasChanged for each node based on \a
206     /// Data::HasChanged of its operands, until fixed point.
207     void propagateChanges();
208 
209     /// Get a forward reference to a node to use as an operand.
210     Metadata &getFwdReference(MDNode &Op);
211   };
212 
213   /// Worklist of distinct nodes whose operands need to be remapped.
214   SmallVector<MDNode *, 16> DistinctWorklist;
215 
216   // Storage for a UniquedGraph.
217   SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
218   SmallVector<MDNode *, 16> POTStorage;
219 
220 public:
221   MDNodeMapper(Mapper &M) : M(M) {}
222 
223   /// Map a metadata node (and its transitive operands).
224   ///
225   /// Map all the (unmapped) nodes in the subgraph under \c N.  The iterative
226   /// algorithm handles distinct nodes and uniqued node subgraphs using
227   /// different strategies.
228   ///
229   /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
230   /// using \a mapDistinctNode().  Their mapping can always be computed
231   /// immediately without visiting operands, even if their operands change.
232   ///
233   /// The mapping for uniqued nodes depends on whether their operands change.
234   /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
235   /// a node to calculate uniqued node mappings in bulk.  Distinct leafs are
236   /// added to \a DistinctWorklist with \a mapDistinctNode().
237   ///
238   /// After mapping \c N itself, this function remaps the operands of the
239   /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
240   /// N has been mapped.
241   Metadata *map(const MDNode &N);
242 
243 private:
244   /// Map a top-level uniqued node and the uniqued subgraph underneath it.
245   ///
246   /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
247   /// underneath \c FirstN and calculates the nodes' mapping.  Each node uses
248   /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
249   /// operands uses the identity mapping.
250   ///
251   /// The algorithm works as follows:
252   ///
253   ///  1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
254   ///     save the post-order traversal in the given \a UniquedGraph, tracking
255   ///     nodes' operands change.
256   ///
257   ///  2. \a UniquedGraph::propagateChanges(): propagate changed operands
258   ///     through the \a UniquedGraph until fixed point, following the rule
259   ///     that if a node changes, any node that references must also change.
260   ///
261   ///  3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
262   ///     (referencing new operands) where necessary.
263   Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
264 
265   /// Try to map the operand of an \a MDNode.
266   ///
267   /// If \c Op is already mapped, return the mapping.  If it's not an \a
268   /// MDNode, compute and return the mapping.  If it's a distinct \a MDNode,
269   /// return the result of \a mapDistinctNode().
270   ///
271   /// \return std::nullopt if \c Op is an unmapped uniqued \a MDNode.
272   /// \post getMappedOp(Op) only returns std::nullopt if this returns
273   /// std::nullopt.
274   std::optional<Metadata *> tryToMapOperand(const Metadata *Op);
275 
276   /// Map a distinct node.
277   ///
278   /// Return the mapping for the distinct node \c N, saving the result in \a
279   /// DistinctWorklist for later remapping.
280   ///
281   /// \pre \c N is not yet mapped.
282   /// \pre \c N.isDistinct().
283   MDNode *mapDistinctNode(const MDNode &N);
284 
285   /// Get a previously mapped node.
286   std::optional<Metadata *> getMappedOp(const Metadata *Op) const;
287 
288   /// Create a post-order traversal of an unmapped uniqued node subgraph.
289   ///
290   /// This traverses the metadata graph deeply enough to map \c FirstN.  It
291   /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
292   /// metadata that has already been mapped will not be part of the POT.
293   ///
294   /// Each node that has a changed operand from outside the graph (e.g., a
295   /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
296   /// is marked with \a Data::HasChanged.
297   ///
298   /// \return \c true if any nodes in \c G have \a Data::HasChanged.
299   /// \post \c G.POT is a post-order traversal ending with \c FirstN.
300   /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
301   /// to change because of operands outside the graph.
302   bool createPOT(UniquedGraph &G, const MDNode &FirstN);
303 
304   /// Visit the operands of a uniqued node in the POT.
305   ///
306   /// Visit the operands in the range from \c I to \c E, returning the first
307   /// uniqued node we find that isn't yet in \c G.  \c I is always advanced to
308   /// where to continue the loop through the operands.
309   ///
310   /// This sets \c HasChanged if any of the visited operands change.
311   MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
312                         MDNode::op_iterator E, bool &HasChanged);
313 
314   /// Map all the nodes in the given uniqued graph.
315   ///
316   /// This visits all the nodes in \c G in post-order, using the identity
317   /// mapping or creating a new node depending on \a Data::HasChanged.
318   ///
319   /// \pre \a getMappedOp() returns std::nullopt for nodes in \c G, but not for
320   /// any of their operands outside of \c G. \pre \a Data::HasChanged is true
321   /// for a node in \c G iff any of its operands have changed. \post \a
322   /// getMappedOp() returns the mapped node for every node in \c G.
323   void mapNodesInPOT(UniquedGraph &G);
324 
325   /// Remap a node's operands using the given functor.
326   ///
327   /// Iterate through the operands of \c N and update them in place using \c
328   /// mapOperand.
329   ///
330   /// \pre N.isDistinct() or N.isTemporary().
331   template <class OperandMapper>
332   void remapOperands(MDNode &N, OperandMapper mapOperand);
333 };
334 
335 } // end anonymous namespace
336 
337 Value *Mapper::mapValue(const Value *V) {
338   ValueToValueMapTy::iterator I = getVM().find(V);
339 
340   // If the value already exists in the map, use it.
341   if (I != getVM().end()) {
342     assert(I->second && "Unexpected null mapping");
343     return I->second;
344   }
345 
346   // If we have a materializer and it can materialize a value, use that.
347   if (auto *Materializer = getMaterializer()) {
348     if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
349       getVM()[V] = NewV;
350       return NewV;
351     }
352   }
353 
354   // Global values do not need to be seeded into the VM if they
355   // are using the identity mapping.
356   if (isa<GlobalValue>(V)) {
357     if (Flags & RF_NullMapMissingGlobalValues)
358       return nullptr;
359     return getVM()[V] = const_cast<Value *>(V);
360   }
361 
362   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
363     // Inline asm may need *type* remapping.
364     FunctionType *NewTy = IA->getFunctionType();
365     if (TypeMapper) {
366       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
367 
368       if (NewTy != IA->getFunctionType())
369         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
370                            IA->hasSideEffects(), IA->isAlignStack(),
371                            IA->getDialect(), IA->canThrow());
372     }
373 
374     return getVM()[V] = const_cast<Value *>(V);
375   }
376 
377   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
378     const Metadata *MD = MDV->getMetadata();
379 
380     if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
381       // Look through to grab the local value.
382       if (Value *LV = mapValue(LAM->getValue())) {
383         if (V == LAM->getValue())
384           return const_cast<Value *>(V);
385         return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
386       }
387 
388       // FIXME: always return nullptr once Verifier::verifyDominatesUse()
389       // ensures metadata operands only reference defined SSA values.
390       return (Flags & RF_IgnoreMissingLocals)
391                  ? nullptr
392                  : MetadataAsValue::get(
393                        V->getContext(),
394                        MDTuple::get(V->getContext(), std::nullopt));
395     }
396     if (auto *AL = dyn_cast<DIArgList>(MD)) {
397       SmallVector<ValueAsMetadata *, 4> MappedArgs;
398       for (auto *VAM : AL->getArgs()) {
399         // Map both Local and Constant VAMs here; they will both ultimately
400         // be mapped via mapValue. The exceptions are constants when we have no
401         // module level changes and locals when they have no existing mapped
402         // value and RF_IgnoreMissingLocals is set; these have identity
403         // mappings.
404         if ((Flags & RF_NoModuleLevelChanges) && isa<ConstantAsMetadata>(VAM)) {
405           MappedArgs.push_back(VAM);
406         } else if (Value *LV = mapValue(VAM->getValue())) {
407           MappedArgs.push_back(
408               LV == VAM->getValue() ? VAM : ValueAsMetadata::get(LV));
409         } else if ((Flags & RF_IgnoreMissingLocals) && isa<LocalAsMetadata>(VAM)) {
410             MappedArgs.push_back(VAM);
411         } else {
412           // If we cannot map the value, set the argument as undef.
413           MappedArgs.push_back(ValueAsMetadata::get(
414               UndefValue::get(VAM->getValue()->getType())));
415         }
416       }
417       return MetadataAsValue::get(V->getContext(),
418                                   DIArgList::get(V->getContext(), MappedArgs));
419     }
420 
421     // If this is a module-level metadata and we know that nothing at the module
422     // level is changing, then use an identity mapping.
423     if (Flags & RF_NoModuleLevelChanges)
424       return getVM()[V] = const_cast<Value *>(V);
425 
426     // Map the metadata and turn it into a value.
427     auto *MappedMD = mapMetadata(MD);
428     if (MD == MappedMD)
429       return getVM()[V] = const_cast<Value *>(V);
430     return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
431   }
432 
433   // Okay, this either must be a constant (which may or may not be mappable) or
434   // is something that is not in the mapping table.
435   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
436   if (!C)
437     return nullptr;
438 
439   if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
440     return mapBlockAddress(*BA);
441 
442   if (const auto *E = dyn_cast<DSOLocalEquivalent>(C)) {
443     auto *Val = mapValue(E->getGlobalValue());
444     GlobalValue *GV = dyn_cast<GlobalValue>(Val);
445     if (GV)
446       return getVM()[E] = DSOLocalEquivalent::get(GV);
447 
448     auto *Func = cast<Function>(Val->stripPointerCastsAndAliases());
449     Type *NewTy = E->getType();
450     if (TypeMapper)
451       NewTy = TypeMapper->remapType(NewTy);
452     return getVM()[E] = llvm::ConstantExpr::getBitCast(
453                DSOLocalEquivalent::get(Func), NewTy);
454   }
455 
456   if (const auto *NC = dyn_cast<NoCFIValue>(C)) {
457     auto *Val = mapValue(NC->getGlobalValue());
458     GlobalValue *GV = cast<GlobalValue>(Val);
459     return getVM()[NC] = NoCFIValue::get(GV);
460   }
461 
462   auto mapValueOrNull = [this](Value *V) {
463     auto Mapped = mapValue(V);
464     assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
465            "Unexpected null mapping for constant operand without "
466            "NullMapMissingGlobalValues flag");
467     return Mapped;
468   };
469 
470   // Otherwise, we have some other constant to remap.  Start by checking to see
471   // if all operands have an identity remapping.
472   unsigned OpNo = 0, NumOperands = C->getNumOperands();
473   Value *Mapped = nullptr;
474   for (; OpNo != NumOperands; ++OpNo) {
475     Value *Op = C->getOperand(OpNo);
476     Mapped = mapValueOrNull(Op);
477     if (!Mapped)
478       return nullptr;
479     if (Mapped != Op)
480       break;
481   }
482 
483   // See if the type mapper wants to remap the type as well.
484   Type *NewTy = C->getType();
485   if (TypeMapper)
486     NewTy = TypeMapper->remapType(NewTy);
487 
488   // If the result type and all operands match up, then just insert an identity
489   // mapping.
490   if (OpNo == NumOperands && NewTy == C->getType())
491     return getVM()[V] = C;
492 
493   // Okay, we need to create a new constant.  We've already processed some or
494   // all of the operands, set them all up now.
495   SmallVector<Constant*, 8> Ops;
496   Ops.reserve(NumOperands);
497   for (unsigned j = 0; j != OpNo; ++j)
498     Ops.push_back(cast<Constant>(C->getOperand(j)));
499 
500   // If one of the operands mismatch, push it and the other mapped operands.
501   if (OpNo != NumOperands) {
502     Ops.push_back(cast<Constant>(Mapped));
503 
504     // Map the rest of the operands that aren't processed yet.
505     for (++OpNo; OpNo != NumOperands; ++OpNo) {
506       Mapped = mapValueOrNull(C->getOperand(OpNo));
507       if (!Mapped)
508         return nullptr;
509       Ops.push_back(cast<Constant>(Mapped));
510     }
511   }
512   Type *NewSrcTy = nullptr;
513   if (TypeMapper)
514     if (auto *GEPO = dyn_cast<GEPOperator>(C))
515       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
516 
517   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
518     return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
519   if (isa<ConstantArray>(C))
520     return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
521   if (isa<ConstantStruct>(C))
522     return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
523   if (isa<ConstantVector>(C))
524     return getVM()[V] = ConstantVector::get(Ops);
525   // If this is a no-operand constant, it must be because the type was remapped.
526   if (isa<PoisonValue>(C))
527     return getVM()[V] = PoisonValue::get(NewTy);
528   if (isa<UndefValue>(C))
529     return getVM()[V] = UndefValue::get(NewTy);
530   if (isa<ConstantAggregateZero>(C))
531     return getVM()[V] = ConstantAggregateZero::get(NewTy);
532   assert(isa<ConstantPointerNull>(C));
533   return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
534 }
535 
536 Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
537   Function *F = cast<Function>(mapValue(BA.getFunction()));
538 
539   // F may not have materialized its initializer.  In that case, create a
540   // dummy basic block for now, and replace it once we've materialized all
541   // the initializers.
542   BasicBlock *BB;
543   if (F->empty()) {
544     DelayedBBs.push_back(DelayedBasicBlock(BA));
545     BB = DelayedBBs.back().TempBB.get();
546   } else {
547     BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
548   }
549 
550   return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
551 }
552 
553 Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
554   getVM().MD()[Key].reset(Val);
555   return Val;
556 }
557 
558 Metadata *Mapper::mapToSelf(const Metadata *MD) {
559   return mapToMetadata(MD, const_cast<Metadata *>(MD));
560 }
561 
562 std::optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
563   if (!Op)
564     return nullptr;
565 
566   if (std::optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
567 #ifndef NDEBUG
568     if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
569       assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
570               M.getVM().getMappedMD(Op)) &&
571              "Expected Value to be memoized");
572     else
573       assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
574              "Expected result to be memoized");
575 #endif
576     return *MappedOp;
577   }
578 
579   const MDNode &N = *cast<MDNode>(Op);
580   if (N.isDistinct())
581     return mapDistinctNode(N);
582   return std::nullopt;
583 }
584 
585 MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
586   assert(N.isDistinct() && "Expected a distinct node");
587   assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
588   Metadata *NewM = nullptr;
589 
590   if (M.Flags & RF_ReuseAndMutateDistinctMDs) {
591     NewM = M.mapToSelf(&N);
592   } else {
593     NewM = MDNode::replaceWithDistinct(N.clone());
594     LLVM_DEBUG(dbgs() << "\nMap " << N << "\n"
595                       << "To  " << *NewM << "\n\n");
596     M.mapToMetadata(&N, NewM);
597   }
598   DistinctWorklist.push_back(cast<MDNode>(NewM));
599 
600   return DistinctWorklist.back();
601 }
602 
603 static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
604                                                   Value *MappedV) {
605   if (CMD.getValue() == MappedV)
606     return const_cast<ConstantAsMetadata *>(&CMD);
607   return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
608 }
609 
610 std::optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
611   if (!Op)
612     return nullptr;
613 
614   if (std::optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
615     return *MappedOp;
616 
617   if (isa<MDString>(Op))
618     return const_cast<Metadata *>(Op);
619 
620   if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
621     return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
622 
623   return std::nullopt;
624 }
625 
626 Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
627   auto Where = Info.find(&Op);
628   assert(Where != Info.end() && "Expected a valid reference");
629 
630   auto &OpD = Where->second;
631   if (!OpD.HasChanged)
632     return Op;
633 
634   // Lazily construct a temporary node.
635   if (!OpD.Placeholder)
636     OpD.Placeholder = Op.clone();
637 
638   return *OpD.Placeholder;
639 }
640 
641 template <class OperandMapper>
642 void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
643   assert(!N.isUniqued() && "Expected distinct or temporary nodes");
644   for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
645     Metadata *Old = N.getOperand(I);
646     Metadata *New = mapOperand(Old);
647     if (Old != New)
648       LLVM_DEBUG(dbgs() << "Replacing Op " << Old << " with " << New << " in "
649                         << N << "\n");
650 
651     if (Old != New)
652       N.replaceOperandWith(I, New);
653   }
654 }
655 
656 namespace {
657 
658 /// An entry in the worklist for the post-order traversal.
659 struct POTWorklistEntry {
660   MDNode *N;              ///< Current node.
661   MDNode::op_iterator Op; ///< Current operand of \c N.
662 
663   /// Keep a flag of whether operands have changed in the worklist to avoid
664   /// hitting the map in \a UniquedGraph.
665   bool HasChanged = false;
666 
667   POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
668 };
669 
670 } // end anonymous namespace
671 
672 bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
673   assert(G.Info.empty() && "Expected a fresh traversal");
674   assert(FirstN.isUniqued() && "Expected uniqued node in POT");
675 
676   // Construct a post-order traversal of the uniqued subgraph under FirstN.
677   bool AnyChanges = false;
678   SmallVector<POTWorklistEntry, 16> Worklist;
679   Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
680   (void)G.Info[&FirstN];
681   while (!Worklist.empty()) {
682     // Start or continue the traversal through the this node's operands.
683     auto &WE = Worklist.back();
684     if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
685       // Push a new node to traverse first.
686       Worklist.push_back(POTWorklistEntry(*N));
687       continue;
688     }
689 
690     // Push the node onto the POT.
691     assert(WE.N->isUniqued() && "Expected only uniqued nodes");
692     assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
693     auto &D = G.Info[WE.N];
694     AnyChanges |= D.HasChanged = WE.HasChanged;
695     D.ID = G.POT.size();
696     G.POT.push_back(WE.N);
697 
698     // Pop the node off the worklist.
699     Worklist.pop_back();
700   }
701   return AnyChanges;
702 }
703 
704 MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
705                                     MDNode::op_iterator E, bool &HasChanged) {
706   while (I != E) {
707     Metadata *Op = *I++; // Increment even on early return.
708     if (std::optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
709       // Check if the operand changes.
710       HasChanged |= Op != *MappedOp;
711       continue;
712     }
713 
714     // A uniqued metadata node.
715     MDNode &OpN = *cast<MDNode>(Op);
716     assert(OpN.isUniqued() &&
717            "Only uniqued operands cannot be mapped immediately");
718     if (G.Info.insert(std::make_pair(&OpN, Data())).second)
719       return &OpN; // This is a new one.  Return it.
720   }
721   return nullptr;
722 }
723 
724 void MDNodeMapper::UniquedGraph::propagateChanges() {
725   bool AnyChanges;
726   do {
727     AnyChanges = false;
728     for (MDNode *N : POT) {
729       auto &D = Info[N];
730       if (D.HasChanged)
731         continue;
732 
733       if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
734             auto Where = Info.find(Op);
735             return Where != Info.end() && Where->second.HasChanged;
736           }))
737         continue;
738 
739       AnyChanges = D.HasChanged = true;
740     }
741   } while (AnyChanges);
742 }
743 
744 void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
745   // Construct uniqued nodes, building forward references as necessary.
746   SmallVector<MDNode *, 16> CyclicNodes;
747   for (auto *N : G.POT) {
748     auto &D = G.Info[N];
749     if (!D.HasChanged) {
750       // The node hasn't changed.
751       M.mapToSelf(N);
752       continue;
753     }
754 
755     // Remember whether this node had a placeholder.
756     bool HadPlaceholder(D.Placeholder);
757 
758     // Clone the uniqued node and remap the operands.
759     TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
760     remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
761       if (std::optional<Metadata *> MappedOp = getMappedOp(Old))
762         return *MappedOp;
763       (void)D;
764       assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
765       return &G.getFwdReference(*cast<MDNode>(Old));
766     });
767 
768     auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
769     if (N && NewN && N != NewN) {
770       LLVM_DEBUG(dbgs() << "\nMap " << *N << "\n"
771                         << "To  " << *NewN << "\n\n");
772     }
773 
774     M.mapToMetadata(N, NewN);
775 
776     // Nodes that were referenced out of order in the POT are involved in a
777     // uniquing cycle.
778     if (HadPlaceholder)
779       CyclicNodes.push_back(NewN);
780   }
781 
782   // Resolve cycles.
783   for (auto *N : CyclicNodes)
784     if (!N->isResolved())
785       N->resolveCycles();
786 }
787 
788 Metadata *MDNodeMapper::map(const MDNode &N) {
789   assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
790   assert(!(M.Flags & RF_NoModuleLevelChanges) &&
791          "MDNodeMapper::map assumes module-level changes");
792 
793   // Require resolved nodes whenever metadata might be remapped.
794   assert(N.isResolved() && "Unexpected unresolved node");
795 
796   Metadata *MappedN =
797       N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
798   while (!DistinctWorklist.empty())
799     remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
800       if (std::optional<Metadata *> MappedOp = tryToMapOperand(Old))
801         return *MappedOp;
802       return mapTopLevelUniquedNode(*cast<MDNode>(Old));
803     });
804   return MappedN;
805 }
806 
807 Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
808   assert(FirstN.isUniqued() && "Expected uniqued node");
809 
810   // Create a post-order traversal of uniqued nodes under FirstN.
811   UniquedGraph G;
812   if (!createPOT(G, FirstN)) {
813     // Return early if no nodes have changed.
814     for (const MDNode *N : G.POT)
815       M.mapToSelf(N);
816     return &const_cast<MDNode &>(FirstN);
817   }
818 
819   // Update graph with all nodes that have changed.
820   G.propagateChanges();
821 
822   // Map all the nodes in the graph.
823   mapNodesInPOT(G);
824 
825   // Return the original node, remapped.
826   return *getMappedOp(&FirstN);
827 }
828 
829 std::optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
830   // If the value already exists in the map, use it.
831   if (std::optional<Metadata *> NewMD = getVM().getMappedMD(MD))
832     return *NewMD;
833 
834   if (isa<MDString>(MD))
835     return const_cast<Metadata *>(MD);
836 
837   // This is a module-level metadata.  If nothing at the module level is
838   // changing, use an identity mapping.
839   if ((Flags & RF_NoModuleLevelChanges))
840     return const_cast<Metadata *>(MD);
841 
842   if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
843     // Don't memoize ConstantAsMetadata.  Instead of lasting until the
844     // LLVMContext is destroyed, they can be deleted when the GlobalValue they
845     // reference is destructed.  These aren't super common, so the extra
846     // indirection isn't that expensive.
847     return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
848   }
849 
850   assert(isa<MDNode>(MD) && "Expected a metadata node");
851 
852   return std::nullopt;
853 }
854 
855 Metadata *Mapper::mapMetadata(const Metadata *MD) {
856   assert(MD && "Expected valid metadata");
857   assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
858 
859   if (std::optional<Metadata *> NewMD = mapSimpleMetadata(MD))
860     return *NewMD;
861 
862   return MDNodeMapper(*this).map(*cast<MDNode>(MD));
863 }
864 
865 void Mapper::flush() {
866   // Flush out the worklist of global values.
867   while (!Worklist.empty()) {
868     WorklistEntry E = Worklist.pop_back_val();
869     CurrentMCID = E.MCID;
870     switch (E.Kind) {
871     case WorklistEntry::MapGlobalInit:
872       E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
873       remapGlobalObjectMetadata(*E.Data.GVInit.GV);
874       break;
875     case WorklistEntry::MapAppendingVar: {
876       unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
877       // mapAppendingVariable call can change AppendingInits if initalizer for
878       // the variable depends on another appending global, because of that inits
879       // need to be extracted and updated before the call.
880       SmallVector<Constant *, 8> NewInits(
881           drop_begin(AppendingInits, PrefixSize));
882       AppendingInits.resize(PrefixSize);
883       mapAppendingVariable(*E.Data.AppendingGV.GV,
884                            E.Data.AppendingGV.InitPrefix,
885                            E.AppendingGVIsOldCtorDtor, ArrayRef(NewInits));
886       break;
887     }
888     case WorklistEntry::MapAliasOrIFunc: {
889       GlobalValue *GV = E.Data.AliasOrIFunc.GV;
890       Constant *Target = mapConstant(E.Data.AliasOrIFunc.Target);
891       if (auto *GA = dyn_cast<GlobalAlias>(GV))
892         GA->setAliasee(Target);
893       else if (auto *GI = dyn_cast<GlobalIFunc>(GV))
894         GI->setResolver(Target);
895       else
896         llvm_unreachable("Not alias or ifunc");
897       break;
898     }
899     case WorklistEntry::RemapFunction:
900       remapFunction(*E.Data.RemapF);
901       break;
902     }
903   }
904   CurrentMCID = 0;
905 
906   // Finish logic for block addresses now that all global values have been
907   // handled.
908   while (!DelayedBBs.empty()) {
909     DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
910     BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
911     DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
912   }
913 }
914 
915 void Mapper::remapInstruction(Instruction *I) {
916   // Remap operands.
917   for (Use &Op : I->operands()) {
918     Value *V = mapValue(Op);
919     // If we aren't ignoring missing entries, assert that something happened.
920     if (V)
921       Op = V;
922     else
923       assert((Flags & RF_IgnoreMissingLocals) &&
924              "Referenced value not in value map!");
925   }
926 
927   // Remap phi nodes' incoming blocks.
928   if (PHINode *PN = dyn_cast<PHINode>(I)) {
929     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
930       Value *V = mapValue(PN->getIncomingBlock(i));
931       // If we aren't ignoring missing entries, assert that something happened.
932       if (V)
933         PN->setIncomingBlock(i, cast<BasicBlock>(V));
934       else
935         assert((Flags & RF_IgnoreMissingLocals) &&
936                "Referenced block not in value map!");
937     }
938   }
939 
940   // Remap attached metadata.
941   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
942   I->getAllMetadata(MDs);
943   for (const auto &MI : MDs) {
944     MDNode *Old = MI.second;
945     MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
946     if (New != Old)
947       I->setMetadata(MI.first, New);
948   }
949 
950   if (!TypeMapper)
951     return;
952 
953   // If the instruction's type is being remapped, do so now.
954   if (auto *CB = dyn_cast<CallBase>(I)) {
955     SmallVector<Type *, 3> Tys;
956     FunctionType *FTy = CB->getFunctionType();
957     Tys.reserve(FTy->getNumParams());
958     for (Type *Ty : FTy->params())
959       Tys.push_back(TypeMapper->remapType(Ty));
960     CB->mutateFunctionType(FunctionType::get(
961         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
962 
963     LLVMContext &C = CB->getContext();
964     AttributeList Attrs = CB->getAttributes();
965     for (unsigned i = 0; i < Attrs.getNumAttrSets(); ++i) {
966       for (int AttrIdx = Attribute::FirstTypeAttr;
967            AttrIdx <= Attribute::LastTypeAttr; AttrIdx++) {
968         Attribute::AttrKind TypedAttr = (Attribute::AttrKind)AttrIdx;
969         if (Type *Ty =
970                 Attrs.getAttributeAtIndex(i, TypedAttr).getValueAsType()) {
971           Attrs = Attrs.replaceAttributeTypeAtIndex(C, i, TypedAttr,
972                                                     TypeMapper->remapType(Ty));
973           break;
974         }
975       }
976     }
977     CB->setAttributes(Attrs);
978     return;
979   }
980   if (auto *AI = dyn_cast<AllocaInst>(I))
981     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
982   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
983     GEP->setSourceElementType(
984         TypeMapper->remapType(GEP->getSourceElementType()));
985     GEP->setResultElementType(
986         TypeMapper->remapType(GEP->getResultElementType()));
987   }
988   I->mutateType(TypeMapper->remapType(I->getType()));
989 }
990 
991 void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
992   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
993   GO.getAllMetadata(MDs);
994   GO.clearMetadata();
995   for (const auto &I : MDs)
996     GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
997 }
998 
999 void Mapper::remapFunction(Function &F) {
1000   // Remap the operands.
1001   for (Use &Op : F.operands())
1002     if (Op)
1003       Op = mapValue(Op);
1004 
1005   // Remap the metadata attachments.
1006   remapGlobalObjectMetadata(F);
1007 
1008   // Remap the argument types.
1009   if (TypeMapper)
1010     for (Argument &A : F.args())
1011       A.mutateType(TypeMapper->remapType(A.getType()));
1012 
1013   // Remap the instructions.
1014   for (BasicBlock &BB : F)
1015     for (Instruction &I : BB)
1016       remapInstruction(&I);
1017 }
1018 
1019 void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1020                                   bool IsOldCtorDtor,
1021                                   ArrayRef<Constant *> NewMembers) {
1022   SmallVector<Constant *, 16> Elements;
1023   if (InitPrefix) {
1024     unsigned NumElements =
1025         cast<ArrayType>(InitPrefix->getType())->getNumElements();
1026     for (unsigned I = 0; I != NumElements; ++I)
1027       Elements.push_back(InitPrefix->getAggregateElement(I));
1028   }
1029 
1030   PointerType *VoidPtrTy;
1031   Type *EltTy;
1032   if (IsOldCtorDtor) {
1033     // FIXME: This upgrade is done during linking to support the C API.  See
1034     // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
1035     VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
1036     auto &ST = *cast<StructType>(NewMembers.front()->getType());
1037     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
1038     EltTy = StructType::get(GV.getContext(), Tys, false);
1039   }
1040 
1041   for (auto *V : NewMembers) {
1042     Constant *NewV;
1043     if (IsOldCtorDtor) {
1044       auto *S = cast<ConstantStruct>(V);
1045       auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
1046       auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
1047       Constant *Null = Constant::getNullValue(VoidPtrTy);
1048       NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
1049     } else {
1050       NewV = cast_or_null<Constant>(mapValue(V));
1051     }
1052     Elements.push_back(NewV);
1053   }
1054 
1055   GV.setInitializer(
1056       ConstantArray::get(cast<ArrayType>(GV.getValueType()), Elements));
1057 }
1058 
1059 void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1060                                           unsigned MCID) {
1061   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1062   assert(MCID < MCs.size() && "Invalid mapping context");
1063 
1064   WorklistEntry WE;
1065   WE.Kind = WorklistEntry::MapGlobalInit;
1066   WE.MCID = MCID;
1067   WE.Data.GVInit.GV = &GV;
1068   WE.Data.GVInit.Init = &Init;
1069   Worklist.push_back(WE);
1070 }
1071 
1072 void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1073                                           Constant *InitPrefix,
1074                                           bool IsOldCtorDtor,
1075                                           ArrayRef<Constant *> NewMembers,
1076                                           unsigned MCID) {
1077   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1078   assert(MCID < MCs.size() && "Invalid mapping context");
1079 
1080   WorklistEntry WE;
1081   WE.Kind = WorklistEntry::MapAppendingVar;
1082   WE.MCID = MCID;
1083   WE.Data.AppendingGV.GV = &GV;
1084   WE.Data.AppendingGV.InitPrefix = InitPrefix;
1085   WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
1086   WE.AppendingGVNumNewMembers = NewMembers.size();
1087   Worklist.push_back(WE);
1088   AppendingInits.append(NewMembers.begin(), NewMembers.end());
1089 }
1090 
1091 void Mapper::scheduleMapAliasOrIFunc(GlobalValue &GV, Constant &Target,
1092                                      unsigned MCID) {
1093   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
1094   assert((isa<GlobalAlias>(GV) || isa<GlobalIFunc>(GV)) &&
1095          "Should be alias or ifunc");
1096   assert(MCID < MCs.size() && "Invalid mapping context");
1097 
1098   WorklistEntry WE;
1099   WE.Kind = WorklistEntry::MapAliasOrIFunc;
1100   WE.MCID = MCID;
1101   WE.Data.AliasOrIFunc.GV = &GV;
1102   WE.Data.AliasOrIFunc.Target = &Target;
1103   Worklist.push_back(WE);
1104 }
1105 
1106 void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1107   assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
1108   assert(MCID < MCs.size() && "Invalid mapping context");
1109 
1110   WorklistEntry WE;
1111   WE.Kind = WorklistEntry::RemapFunction;
1112   WE.MCID = MCID;
1113   WE.Data.RemapF = &F;
1114   Worklist.push_back(WE);
1115 }
1116 
1117 void Mapper::addFlags(RemapFlags Flags) {
1118   assert(!hasWorkToDo() && "Expected to have flushed the worklist");
1119   this->Flags = this->Flags | Flags;
1120 }
1121 
1122 static Mapper *getAsMapper(void *pImpl) {
1123   return reinterpret_cast<Mapper *>(pImpl);
1124 }
1125 
1126 namespace {
1127 
1128 class FlushingMapper {
1129   Mapper &M;
1130 
1131 public:
1132   explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
1133     assert(!M.hasWorkToDo() && "Expected to be flushed");
1134   }
1135 
1136   ~FlushingMapper() { M.flush(); }
1137 
1138   Mapper *operator->() const { return &M; }
1139 };
1140 
1141 } // end anonymous namespace
1142 
1143 ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
1144                          ValueMapTypeRemapper *TypeMapper,
1145                          ValueMaterializer *Materializer)
1146     : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
1147 
1148 ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
1149 
1150 unsigned
1151 ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
1152                                              ValueMaterializer *Materializer) {
1153   return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
1154 }
1155 
1156 void ValueMapper::addFlags(RemapFlags Flags) {
1157   FlushingMapper(pImpl)->addFlags(Flags);
1158 }
1159 
1160 Value *ValueMapper::mapValue(const Value &V) {
1161   return FlushingMapper(pImpl)->mapValue(&V);
1162 }
1163 
1164 Constant *ValueMapper::mapConstant(const Constant &C) {
1165   return cast_or_null<Constant>(mapValue(C));
1166 }
1167 
1168 Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
1169   return FlushingMapper(pImpl)->mapMetadata(&MD);
1170 }
1171 
1172 MDNode *ValueMapper::mapMDNode(const MDNode &N) {
1173   return cast_or_null<MDNode>(mapMetadata(N));
1174 }
1175 
1176 void ValueMapper::remapInstruction(Instruction &I) {
1177   FlushingMapper(pImpl)->remapInstruction(&I);
1178 }
1179 
1180 void ValueMapper::remapFunction(Function &F) {
1181   FlushingMapper(pImpl)->remapFunction(F);
1182 }
1183 
1184 void ValueMapper::remapGlobalObjectMetadata(GlobalObject &GO) {
1185   FlushingMapper(pImpl)->remapGlobalObjectMetadata(GO);
1186 }
1187 
1188 void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
1189                                                Constant &Init,
1190                                                unsigned MCID) {
1191   getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
1192 }
1193 
1194 void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
1195                                                Constant *InitPrefix,
1196                                                bool IsOldCtorDtor,
1197                                                ArrayRef<Constant *> NewMembers,
1198                                                unsigned MCID) {
1199   getAsMapper(pImpl)->scheduleMapAppendingVariable(
1200       GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
1201 }
1202 
1203 void ValueMapper::scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee,
1204                                          unsigned MCID) {
1205   getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GA, Aliasee, MCID);
1206 }
1207 
1208 void ValueMapper::scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver,
1209                                          unsigned MCID) {
1210   getAsMapper(pImpl)->scheduleMapAliasOrIFunc(GI, Resolver, MCID);
1211 }
1212 
1213 void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
1214   getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
1215 }
1216