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