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