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