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