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