1f22ef01cSRoman Divacky //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file defines the MapValue function, which is shared by various parts of
11f22ef01cSRoman Divacky // the lib/Transforms/Utils library.
12f22ef01cSRoman Divacky //
13f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
14f22ef01cSRoman Divacky 
15e580952dSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
162cab237bSDimitry Andric #include "llvm/ADT/ArrayRef.h"
172cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
183ca95b02SDimitry Andric #include "llvm/ADT/DenseSet.h"
192cab237bSDimitry Andric #include "llvm/ADT/None.h"
202cab237bSDimitry Andric #include "llvm/ADT/Optional.h"
212cab237bSDimitry Andric #include "llvm/ADT/STLExtras.h"
222cab237bSDimitry Andric #include "llvm/ADT/SmallVector.h"
232cab237bSDimitry Andric #include "llvm/IR/Argument.h"
242cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
25ff0cc061SDimitry Andric #include "llvm/IR/CallSite.h"
262cab237bSDimitry Andric #include "llvm/IR/Constant.h"
27139f7f9bSDimitry Andric #include "llvm/IR/Constants.h"
28*842d113bSDimitry Andric #include "llvm/IR/DebugInfoMetadata.h"
292cab237bSDimitry Andric #include "llvm/IR/DerivedTypes.h"
30139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
313ca95b02SDimitry Andric #include "llvm/IR/GlobalAlias.h"
322cab237bSDimitry Andric #include "llvm/IR/GlobalObject.h"
333ca95b02SDimitry Andric #include "llvm/IR/GlobalVariable.h"
34139f7f9bSDimitry Andric #include "llvm/IR/InlineAsm.h"
352cab237bSDimitry Andric #include "llvm/IR/Instruction.h"
36139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
37139f7f9bSDimitry Andric #include "llvm/IR/Metadata.h"
387d523365SDimitry Andric #include "llvm/IR/Operator.h"
392cab237bSDimitry Andric #include "llvm/IR/Type.h"
402cab237bSDimitry Andric #include "llvm/IR/Value.h"
412cab237bSDimitry Andric #include "llvm/Support/Casting.h"
422cab237bSDimitry Andric #include <cassert>
432cab237bSDimitry Andric #include <limits>
442cab237bSDimitry Andric #include <memory>
452cab237bSDimitry Andric #include <utility>
462cab237bSDimitry Andric 
47f22ef01cSRoman Divacky using namespace llvm;
48f22ef01cSRoman Divacky 
4917a519f9SDimitry Andric // Out of line method to get vtable etc for class.
anchor()503861d79fSDimitry Andric void ValueMapTypeRemapper::anchor() {}
anchor()51f785676fSDimitry Andric void ValueMaterializer::anchor() {}
523ca95b02SDimitry Andric 
533ca95b02SDimitry Andric namespace {
543ca95b02SDimitry Andric 
553ca95b02SDimitry Andric /// A basic block used in a BlockAddress whose function body is not yet
563ca95b02SDimitry Andric /// materialized.
573ca95b02SDimitry Andric struct DelayedBasicBlock {
583ca95b02SDimitry Andric   BasicBlock *OldBB;
593ca95b02SDimitry Andric   std::unique_ptr<BasicBlock> TempBB;
603ca95b02SDimitry Andric 
DelayedBasicBlock__anonc32747150111::DelayedBasicBlock613ca95b02SDimitry Andric   DelayedBasicBlock(const BlockAddress &Old)
623ca95b02SDimitry Andric       : OldBB(Old.getBasicBlock()),
633ca95b02SDimitry Andric         TempBB(BasicBlock::Create(Old.getContext())) {}
643ca95b02SDimitry Andric };
653ca95b02SDimitry Andric 
663ca95b02SDimitry Andric struct WorklistEntry {
673ca95b02SDimitry Andric   enum EntryKind {
683ca95b02SDimitry Andric     MapGlobalInit,
693ca95b02SDimitry Andric     MapAppendingVar,
703ca95b02SDimitry Andric     MapGlobalAliasee,
713ca95b02SDimitry Andric     RemapFunction
723ca95b02SDimitry Andric   };
733ca95b02SDimitry Andric   struct GVInitTy {
743ca95b02SDimitry Andric     GlobalVariable *GV;
753ca95b02SDimitry Andric     Constant *Init;
763ca95b02SDimitry Andric   };
773ca95b02SDimitry Andric   struct AppendingGVTy {
783ca95b02SDimitry Andric     GlobalVariable *GV;
793ca95b02SDimitry Andric     Constant *InitPrefix;
803ca95b02SDimitry Andric   };
813ca95b02SDimitry Andric   struct GlobalAliaseeTy {
823ca95b02SDimitry Andric     GlobalAlias *GA;
833ca95b02SDimitry Andric     Constant *Aliasee;
843ca95b02SDimitry Andric   };
853ca95b02SDimitry Andric 
863ca95b02SDimitry Andric   unsigned Kind : 2;
873ca95b02SDimitry Andric   unsigned MCID : 29;
883ca95b02SDimitry Andric   unsigned AppendingGVIsOldCtorDtor : 1;
893ca95b02SDimitry Andric   unsigned AppendingGVNumNewMembers;
903ca95b02SDimitry Andric   union {
913ca95b02SDimitry Andric     GVInitTy GVInit;
923ca95b02SDimitry Andric     AppendingGVTy AppendingGV;
933ca95b02SDimitry Andric     GlobalAliaseeTy GlobalAliasee;
943ca95b02SDimitry Andric     Function *RemapF;
953ca95b02SDimitry Andric   } Data;
963ca95b02SDimitry Andric };
973ca95b02SDimitry Andric 
983ca95b02SDimitry Andric struct MappingContext {
993ca95b02SDimitry Andric   ValueToValueMapTy *VM;
1003ca95b02SDimitry Andric   ValueMaterializer *Materializer = nullptr;
1013ca95b02SDimitry Andric 
1023ca95b02SDimitry Andric   /// Construct a MappingContext with a value map and materializer.
MappingContext__anonc32747150111::MappingContext1033ca95b02SDimitry Andric   explicit MappingContext(ValueToValueMapTy &VM,
1043ca95b02SDimitry Andric                           ValueMaterializer *Materializer = nullptr)
1053ca95b02SDimitry Andric       : VM(&VM), Materializer(Materializer) {}
1063ca95b02SDimitry Andric };
1073ca95b02SDimitry Andric 
1083ca95b02SDimitry Andric class Mapper {
1093ca95b02SDimitry Andric   friend class MDNodeMapper;
1103ca95b02SDimitry Andric 
1113ca95b02SDimitry Andric #ifndef NDEBUG
1123ca95b02SDimitry Andric   DenseSet<GlobalValue *> AlreadyScheduled;
1133ca95b02SDimitry Andric #endif
1143ca95b02SDimitry Andric 
1153ca95b02SDimitry Andric   RemapFlags Flags;
1163ca95b02SDimitry Andric   ValueMapTypeRemapper *TypeMapper;
1173ca95b02SDimitry Andric   unsigned CurrentMCID = 0;
1183ca95b02SDimitry Andric   SmallVector<MappingContext, 2> MCs;
1193ca95b02SDimitry Andric   SmallVector<WorklistEntry, 4> Worklist;
1203ca95b02SDimitry Andric   SmallVector<DelayedBasicBlock, 1> DelayedBBs;
1213ca95b02SDimitry Andric   SmallVector<Constant *, 16> AppendingInits;
1223ca95b02SDimitry Andric 
1233ca95b02SDimitry Andric public:
Mapper(ValueToValueMapTy & VM,RemapFlags Flags,ValueMapTypeRemapper * TypeMapper,ValueMaterializer * Materializer)1243ca95b02SDimitry Andric   Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
1253ca95b02SDimitry Andric          ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
1263ca95b02SDimitry Andric       : Flags(Flags), TypeMapper(TypeMapper),
1273ca95b02SDimitry Andric         MCs(1, MappingContext(VM, Materializer)) {}
1283ca95b02SDimitry Andric 
1293ca95b02SDimitry Andric   /// ValueMapper should explicitly call \a flush() before destruction.
~Mapper()1303ca95b02SDimitry Andric   ~Mapper() { assert(!hasWorkToDo() && "Expected to be flushed"); }
1313ca95b02SDimitry Andric 
hasWorkToDo() const1323ca95b02SDimitry Andric   bool hasWorkToDo() const { return !Worklist.empty(); }
1333ca95b02SDimitry Andric 
1343ca95b02SDimitry Andric   unsigned
registerAlternateMappingContext(ValueToValueMapTy & VM,ValueMaterializer * Materializer=nullptr)1353ca95b02SDimitry Andric   registerAlternateMappingContext(ValueToValueMapTy &VM,
1363ca95b02SDimitry Andric                                   ValueMaterializer *Materializer = nullptr) {
1373ca95b02SDimitry Andric     MCs.push_back(MappingContext(VM, Materializer));
1383ca95b02SDimitry Andric     return MCs.size() - 1;
1393ca95b02SDimitry Andric   }
1403ca95b02SDimitry Andric 
1413ca95b02SDimitry Andric   void addFlags(RemapFlags Flags);
1423ca95b02SDimitry Andric 
1430f5676f4SDimitry Andric   void remapGlobalObjectMetadata(GlobalObject &GO);
1440f5676f4SDimitry Andric 
1453ca95b02SDimitry Andric   Value *mapValue(const Value *V);
1463ca95b02SDimitry Andric   void remapInstruction(Instruction *I);
1473ca95b02SDimitry Andric   void remapFunction(Function &F);
1483ca95b02SDimitry Andric 
mapConstant(const Constant * C)1493ca95b02SDimitry Andric   Constant *mapConstant(const Constant *C) {
1503ca95b02SDimitry Andric     return cast_or_null<Constant>(mapValue(C));
1513ca95b02SDimitry Andric   }
1523ca95b02SDimitry Andric 
1533ca95b02SDimitry Andric   /// Map metadata.
1543ca95b02SDimitry Andric   ///
1553ca95b02SDimitry Andric   /// Find the mapping for MD.  Guarantees that the return will be resolved
1563ca95b02SDimitry Andric   /// (not an MDNode, or MDNode::isResolved() returns true).
1573ca95b02SDimitry Andric   Metadata *mapMetadata(const Metadata *MD);
1583ca95b02SDimitry Andric 
1593ca95b02SDimitry Andric   void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
1603ca95b02SDimitry Andric                                     unsigned MCID);
1613ca95b02SDimitry Andric   void scheduleMapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1623ca95b02SDimitry Andric                                     bool IsOldCtorDtor,
1633ca95b02SDimitry Andric                                     ArrayRef<Constant *> NewMembers,
1643ca95b02SDimitry Andric                                     unsigned MCID);
1653ca95b02SDimitry Andric   void scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
1663ca95b02SDimitry Andric                                 unsigned MCID);
1673ca95b02SDimitry Andric   void scheduleRemapFunction(Function &F, unsigned MCID);
1683ca95b02SDimitry Andric 
1693ca95b02SDimitry Andric   void flush();
1703ca95b02SDimitry Andric 
1713ca95b02SDimitry Andric private:
1723ca95b02SDimitry Andric   void mapGlobalInitializer(GlobalVariable &GV, Constant &Init);
1733ca95b02SDimitry Andric   void mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
1743ca95b02SDimitry Andric                             bool IsOldCtorDtor,
1753ca95b02SDimitry Andric                             ArrayRef<Constant *> NewMembers);
1763ca95b02SDimitry Andric   void mapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee);
1773ca95b02SDimitry Andric   void remapFunction(Function &F, ValueToValueMapTy &VM);
1783ca95b02SDimitry Andric 
getVM()1793ca95b02SDimitry Andric   ValueToValueMapTy &getVM() { return *MCs[CurrentMCID].VM; }
getMaterializer()1803ca95b02SDimitry Andric   ValueMaterializer *getMaterializer() { return MCs[CurrentMCID].Materializer; }
1813ca95b02SDimitry Andric 
1823ca95b02SDimitry Andric   Value *mapBlockAddress(const BlockAddress &BA);
1833ca95b02SDimitry Andric 
1843ca95b02SDimitry Andric   /// Map metadata that doesn't require visiting operands.
1853ca95b02SDimitry Andric   Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
1863ca95b02SDimitry Andric 
1873ca95b02SDimitry Andric   Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
1883ca95b02SDimitry Andric   Metadata *mapToSelf(const Metadata *MD);
1893ca95b02SDimitry Andric };
1903ca95b02SDimitry Andric 
1913ca95b02SDimitry Andric class MDNodeMapper {
1923ca95b02SDimitry Andric   Mapper &M;
1933ca95b02SDimitry Andric 
1943ca95b02SDimitry Andric   /// Data about a node in \a UniquedGraph.
1953ca95b02SDimitry Andric   struct Data {
1963ca95b02SDimitry Andric     bool HasChanged = false;
1972cab237bSDimitry Andric     unsigned ID = std::numeric_limits<unsigned>::max();
1983ca95b02SDimitry Andric     TempMDNode Placeholder;
1993ca95b02SDimitry Andric   };
2003ca95b02SDimitry Andric 
2013ca95b02SDimitry Andric   /// A graph of uniqued nodes.
2023ca95b02SDimitry Andric   struct UniquedGraph {
2033ca95b02SDimitry Andric     SmallDenseMap<const Metadata *, Data, 32> Info; // Node properties.
2043ca95b02SDimitry Andric     SmallVector<MDNode *, 16> POT;                  // Post-order traversal.
2053ca95b02SDimitry Andric 
2063ca95b02SDimitry Andric     /// Propagate changed operands through the post-order traversal.
2073ca95b02SDimitry Andric     ///
2083ca95b02SDimitry Andric     /// Iteratively update \a Data::HasChanged for each node based on \a
2093ca95b02SDimitry Andric     /// Data::HasChanged of its operands, until fixed point.
2103ca95b02SDimitry Andric     void propagateChanges();
2113ca95b02SDimitry Andric 
2123ca95b02SDimitry Andric     /// Get a forward reference to a node to use as an operand.
2133ca95b02SDimitry Andric     Metadata &getFwdReference(MDNode &Op);
2143ca95b02SDimitry Andric   };
2153ca95b02SDimitry Andric 
2163ca95b02SDimitry Andric   /// Worklist of distinct nodes whose operands need to be remapped.
2173ca95b02SDimitry Andric   SmallVector<MDNode *, 16> DistinctWorklist;
2183ca95b02SDimitry Andric 
2193ca95b02SDimitry Andric   // Storage for a UniquedGraph.
2203ca95b02SDimitry Andric   SmallDenseMap<const Metadata *, Data, 32> InfoStorage;
2213ca95b02SDimitry Andric   SmallVector<MDNode *, 16> POTStorage;
2223ca95b02SDimitry Andric 
2233ca95b02SDimitry Andric public:
MDNodeMapper(Mapper & M)2243ca95b02SDimitry Andric   MDNodeMapper(Mapper &M) : M(M) {}
2253ca95b02SDimitry Andric 
2263ca95b02SDimitry Andric   /// Map a metadata node (and its transitive operands).
2273ca95b02SDimitry Andric   ///
2283ca95b02SDimitry Andric   /// Map all the (unmapped) nodes in the subgraph under \c N.  The iterative
2293ca95b02SDimitry Andric   /// algorithm handles distinct nodes and uniqued node subgraphs using
2303ca95b02SDimitry Andric   /// different strategies.
2313ca95b02SDimitry Andric   ///
2323ca95b02SDimitry Andric   /// Distinct nodes are immediately mapped and added to \a DistinctWorklist
2333ca95b02SDimitry Andric   /// using \a mapDistinctNode().  Their mapping can always be computed
2343ca95b02SDimitry Andric   /// immediately without visiting operands, even if their operands change.
2353ca95b02SDimitry Andric   ///
2363ca95b02SDimitry Andric   /// The mapping for uniqued nodes depends on whether their operands change.
2373ca95b02SDimitry Andric   /// \a mapTopLevelUniquedNode() traverses the transitive uniqued subgraph of
2383ca95b02SDimitry Andric   /// a node to calculate uniqued node mappings in bulk.  Distinct leafs are
2393ca95b02SDimitry Andric   /// added to \a DistinctWorklist with \a mapDistinctNode().
2403ca95b02SDimitry Andric   ///
2413ca95b02SDimitry Andric   /// After mapping \c N itself, this function remaps the operands of the
2423ca95b02SDimitry Andric   /// distinct nodes in \a DistinctWorklist until the entire subgraph under \c
2433ca95b02SDimitry Andric   /// N has been mapped.
2443ca95b02SDimitry Andric   Metadata *map(const MDNode &N);
2453ca95b02SDimitry Andric 
2463ca95b02SDimitry Andric private:
2473ca95b02SDimitry Andric   /// Map a top-level uniqued node and the uniqued subgraph underneath it.
2483ca95b02SDimitry Andric   ///
2493ca95b02SDimitry Andric   /// This builds up a post-order traversal of the (unmapped) uniqued subgraph
2503ca95b02SDimitry Andric   /// underneath \c FirstN and calculates the nodes' mapping.  Each node uses
2513ca95b02SDimitry Andric   /// the identity mapping (\a Mapper::mapToSelf()) as long as all of its
2523ca95b02SDimitry Andric   /// operands uses the identity mapping.
2533ca95b02SDimitry Andric   ///
2543ca95b02SDimitry Andric   /// The algorithm works as follows:
2553ca95b02SDimitry Andric   ///
2563ca95b02SDimitry Andric   ///  1. \a createPOT(): traverse the uniqued subgraph under \c FirstN and
2573ca95b02SDimitry Andric   ///     save the post-order traversal in the given \a UniquedGraph, tracking
2583ca95b02SDimitry Andric   ///     nodes' operands change.
2593ca95b02SDimitry Andric   ///
2603ca95b02SDimitry Andric   ///  2. \a UniquedGraph::propagateChanges(): propagate changed operands
2613ca95b02SDimitry Andric   ///     through the \a UniquedGraph until fixed point, following the rule
2623ca95b02SDimitry Andric   ///     that if a node changes, any node that references must also change.
2633ca95b02SDimitry Andric   ///
2643ca95b02SDimitry Andric   ///  3. \a mapNodesInPOT(): map the uniqued nodes, creating new uniqued nodes
2653ca95b02SDimitry Andric   ///     (referencing new operands) where necessary.
2663ca95b02SDimitry Andric   Metadata *mapTopLevelUniquedNode(const MDNode &FirstN);
2673ca95b02SDimitry Andric 
2683ca95b02SDimitry Andric   /// Try to map the operand of an \a MDNode.
2693ca95b02SDimitry Andric   ///
2703ca95b02SDimitry Andric   /// If \c Op is already mapped, return the mapping.  If it's not an \a
2713ca95b02SDimitry Andric   /// MDNode, compute and return the mapping.  If it's a distinct \a MDNode,
2723ca95b02SDimitry Andric   /// return the result of \a mapDistinctNode().
2733ca95b02SDimitry Andric   ///
2743ca95b02SDimitry Andric   /// \return None if \c Op is an unmapped uniqued \a MDNode.
2753ca95b02SDimitry Andric   /// \post getMappedOp(Op) only returns None if this returns None.
2763ca95b02SDimitry Andric   Optional<Metadata *> tryToMapOperand(const Metadata *Op);
2773ca95b02SDimitry Andric 
2783ca95b02SDimitry Andric   /// Map a distinct node.
2793ca95b02SDimitry Andric   ///
2803ca95b02SDimitry Andric   /// Return the mapping for the distinct node \c N, saving the result in \a
2813ca95b02SDimitry Andric   /// DistinctWorklist for later remapping.
2823ca95b02SDimitry Andric   ///
2833ca95b02SDimitry Andric   /// \pre \c N is not yet mapped.
2843ca95b02SDimitry Andric   /// \pre \c N.isDistinct().
2853ca95b02SDimitry Andric   MDNode *mapDistinctNode(const MDNode &N);
2863ca95b02SDimitry Andric 
2873ca95b02SDimitry Andric   /// Get a previously mapped node.
2883ca95b02SDimitry Andric   Optional<Metadata *> getMappedOp(const Metadata *Op) const;
2893ca95b02SDimitry Andric 
2903ca95b02SDimitry Andric   /// Create a post-order traversal of an unmapped uniqued node subgraph.
2913ca95b02SDimitry Andric   ///
2923ca95b02SDimitry Andric   /// This traverses the metadata graph deeply enough to map \c FirstN.  It
2933ca95b02SDimitry Andric   /// uses \a tryToMapOperand() (via \a Mapper::mapSimplifiedNode()), so any
2943ca95b02SDimitry Andric   /// metadata that has already been mapped will not be part of the POT.
2953ca95b02SDimitry Andric   ///
2963ca95b02SDimitry Andric   /// Each node that has a changed operand from outside the graph (e.g., a
2973ca95b02SDimitry Andric   /// distinct node, an already-mapped uniqued node, or \a ConstantAsMetadata)
2983ca95b02SDimitry Andric   /// is marked with \a Data::HasChanged.
2993ca95b02SDimitry Andric   ///
3003ca95b02SDimitry Andric   /// \return \c true if any nodes in \c G have \a Data::HasChanged.
3013ca95b02SDimitry Andric   /// \post \c G.POT is a post-order traversal ending with \c FirstN.
3023ca95b02SDimitry Andric   /// \post \a Data::hasChanged in \c G.Info indicates whether any node needs
3033ca95b02SDimitry Andric   /// to change because of operands outside the graph.
3043ca95b02SDimitry Andric   bool createPOT(UniquedGraph &G, const MDNode &FirstN);
3053ca95b02SDimitry Andric 
3063ca95b02SDimitry Andric   /// Visit the operands of a uniqued node in the POT.
3073ca95b02SDimitry Andric   ///
3083ca95b02SDimitry Andric   /// Visit the operands in the range from \c I to \c E, returning the first
3093ca95b02SDimitry Andric   /// uniqued node we find that isn't yet in \c G.  \c I is always advanced to
3103ca95b02SDimitry Andric   /// where to continue the loop through the operands.
3113ca95b02SDimitry Andric   ///
3123ca95b02SDimitry Andric   /// This sets \c HasChanged if any of the visited operands change.
3133ca95b02SDimitry Andric   MDNode *visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
3143ca95b02SDimitry Andric                         MDNode::op_iterator E, bool &HasChanged);
3153ca95b02SDimitry Andric 
3163ca95b02SDimitry Andric   /// Map all the nodes in the given uniqued graph.
3173ca95b02SDimitry Andric   ///
3183ca95b02SDimitry Andric   /// This visits all the nodes in \c G in post-order, using the identity
3193ca95b02SDimitry Andric   /// mapping or creating a new node depending on \a Data::HasChanged.
3203ca95b02SDimitry Andric   ///
3213ca95b02SDimitry Andric   /// \pre \a getMappedOp() returns None for nodes in \c G, but not for any of
3223ca95b02SDimitry Andric   /// their operands outside of \c G.
3233ca95b02SDimitry Andric   /// \pre \a Data::HasChanged is true for a node in \c G iff any of its
3243ca95b02SDimitry Andric   /// operands have changed.
3253ca95b02SDimitry Andric   /// \post \a getMappedOp() returns the mapped node for every node in \c G.
3263ca95b02SDimitry Andric   void mapNodesInPOT(UniquedGraph &G);
3273ca95b02SDimitry Andric 
3283ca95b02SDimitry Andric   /// Remap a node's operands using the given functor.
3293ca95b02SDimitry Andric   ///
3303ca95b02SDimitry Andric   /// Iterate through the operands of \c N and update them in place using \c
3313ca95b02SDimitry Andric   /// mapOperand.
3323ca95b02SDimitry Andric   ///
3333ca95b02SDimitry Andric   /// \pre N.isDistinct() or N.isTemporary().
3343ca95b02SDimitry Andric   template <class OperandMapper>
3353ca95b02SDimitry Andric   void remapOperands(MDNode &N, OperandMapper mapOperand);
3363ca95b02SDimitry Andric };
3373ca95b02SDimitry Andric 
3382cab237bSDimitry Andric } // end anonymous namespace
3393ca95b02SDimitry Andric 
mapValue(const Value * V)3403ca95b02SDimitry Andric Value *Mapper::mapValue(const Value *V) {
3413ca95b02SDimitry Andric   ValueToValueMapTy::iterator I = getVM().find(V);
342f22ef01cSRoman Divacky 
3432754fe60SDimitry Andric   // If the value already exists in the map, use it.
3443ca95b02SDimitry Andric   if (I != getVM().end()) {
3453ca95b02SDimitry Andric     assert(I->second && "Unexpected null mapping");
3463ca95b02SDimitry Andric     return I->second;
3473ca95b02SDimitry Andric   }
348f22ef01cSRoman Divacky 
349f785676fSDimitry Andric   // If we have a materializer and it can materialize a value, use that.
3503ca95b02SDimitry Andric   if (auto *Materializer = getMaterializer()) {
3513ca95b02SDimitry Andric     if (Value *NewV = Materializer->materialize(const_cast<Value *>(V))) {
3523ca95b02SDimitry Andric       getVM()[V] = NewV;
3537d523365SDimitry Andric       return NewV;
3547d523365SDimitry Andric     }
355f785676fSDimitry Andric   }
356f785676fSDimitry Andric 
357e580952dSDimitry Andric   // Global values do not need to be seeded into the VM if they
358e580952dSDimitry Andric   // are using the identity mapping.
3597d523365SDimitry Andric   if (isa<GlobalValue>(V)) {
3603ca95b02SDimitry Andric     if (Flags & RF_NullMapMissingGlobalValues)
3617d523365SDimitry Andric       return nullptr;
3623ca95b02SDimitry Andric     return getVM()[V] = const_cast<Value *>(V);
3637d523365SDimitry Andric   }
364f22ef01cSRoman Divacky 
36517a519f9SDimitry Andric   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
36617a519f9SDimitry Andric     // Inline asm may need *type* remapping.
36717a519f9SDimitry Andric     FunctionType *NewTy = IA->getFunctionType();
36817a519f9SDimitry Andric     if (TypeMapper) {
36917a519f9SDimitry Andric       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
37017a519f9SDimitry Andric 
37117a519f9SDimitry Andric       if (NewTy != IA->getFunctionType())
37217a519f9SDimitry Andric         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
37317a519f9SDimitry Andric                            IA->hasSideEffects(), IA->isAlignStack());
37417a519f9SDimitry Andric     }
37517a519f9SDimitry Andric 
3763ca95b02SDimitry Andric     return getVM()[V] = const_cast<Value *>(V);
37717a519f9SDimitry Andric   }
37817a519f9SDimitry Andric 
37939d628a0SDimitry Andric   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
38039d628a0SDimitry Andric     const Metadata *MD = MDV->getMetadata();
3813ca95b02SDimitry Andric 
3823ca95b02SDimitry Andric     if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
3833ca95b02SDimitry Andric       // Look through to grab the local value.
3843ca95b02SDimitry Andric       if (Value *LV = mapValue(LAM->getValue())) {
3853ca95b02SDimitry Andric         if (V == LAM->getValue())
3863ca95b02SDimitry Andric           return const_cast<Value *>(V);
3873ca95b02SDimitry Andric         return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
3883ca95b02SDimitry Andric       }
3893ca95b02SDimitry Andric 
3903ca95b02SDimitry Andric       // FIXME: always return nullptr once Verifier::verifyDominatesUse()
3913ca95b02SDimitry Andric       // ensures metadata operands only reference defined SSA values.
3923ca95b02SDimitry Andric       return (Flags & RF_IgnoreMissingLocals)
3933ca95b02SDimitry Andric                  ? nullptr
3943ca95b02SDimitry Andric                  : MetadataAsValue::get(V->getContext(),
3953ca95b02SDimitry Andric                                         MDTuple::get(V->getContext(), None));
3963ca95b02SDimitry Andric     }
3973ca95b02SDimitry Andric 
3982754fe60SDimitry Andric     // If this is a module-level metadata and we know that nothing at the module
3992754fe60SDimitry Andric     // level is changing, then use an identity mapping.
4003ca95b02SDimitry Andric     if (Flags & RF_NoModuleLevelChanges)
4013ca95b02SDimitry Andric       return getVM()[V] = const_cast<Value *>(V);
4022754fe60SDimitry Andric 
4033ca95b02SDimitry Andric     // Map the metadata and turn it into a value.
4043ca95b02SDimitry Andric     auto *MappedMD = mapMetadata(MD);
4053ca95b02SDimitry Andric     if (MD == MappedMD)
4063ca95b02SDimitry Andric       return getVM()[V] = const_cast<Value *>(V);
4073ca95b02SDimitry Andric     return getVM()[V] = MetadataAsValue::get(V->getContext(), MappedMD);
408f22ef01cSRoman Divacky   }
409f22ef01cSRoman Divacky 
4102754fe60SDimitry Andric   // Okay, this either must be a constant (which may or may not be mappable) or
4112754fe60SDimitry Andric   // is something that is not in the mapping table.
412f22ef01cSRoman Divacky   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
41391bc56edSDimitry Andric   if (!C)
41491bc56edSDimitry Andric     return nullptr;
415f22ef01cSRoman Divacky 
4163ca95b02SDimitry Andric   if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
4173ca95b02SDimitry Andric     return mapBlockAddress(*BA);
4183ca95b02SDimitry Andric 
4193ca95b02SDimitry Andric   auto mapValueOrNull = [this](Value *V) {
4203ca95b02SDimitry Andric     auto Mapped = mapValue(V);
4213ca95b02SDimitry Andric     assert((Mapped || (Flags & RF_NullMapMissingGlobalValues)) &&
4223ca95b02SDimitry Andric            "Unexpected null mapping for constant operand without "
4233ca95b02SDimitry Andric            "NullMapMissingGlobalValues flag");
4243ca95b02SDimitry Andric     return Mapped;
4253ca95b02SDimitry Andric   };
426f22ef01cSRoman Divacky 
42717a519f9SDimitry Andric   // Otherwise, we have some other constant to remap.  Start by checking to see
42817a519f9SDimitry Andric   // if all operands have an identity remapping.
42917a519f9SDimitry Andric   unsigned OpNo = 0, NumOperands = C->getNumOperands();
43091bc56edSDimitry Andric   Value *Mapped = nullptr;
43117a519f9SDimitry Andric   for (; OpNo != NumOperands; ++OpNo) {
43217a519f9SDimitry Andric     Value *Op = C->getOperand(OpNo);
4333ca95b02SDimitry Andric     Mapped = mapValueOrNull(Op);
4343ca95b02SDimitry Andric     if (!Mapped)
4353ca95b02SDimitry Andric       return nullptr;
4363ca95b02SDimitry Andric     if (Mapped != Op)
4373ca95b02SDimitry Andric       break;
43817a519f9SDimitry Andric   }
4392754fe60SDimitry Andric 
44017a519f9SDimitry Andric   // See if the type mapper wants to remap the type as well.
44117a519f9SDimitry Andric   Type *NewTy = C->getType();
44217a519f9SDimitry Andric   if (TypeMapper)
44317a519f9SDimitry Andric     NewTy = TypeMapper->remapType(NewTy);
44417a519f9SDimitry Andric 
44517a519f9SDimitry Andric   // If the result type and all operands match up, then just insert an identity
44617a519f9SDimitry Andric   // mapping.
44717a519f9SDimitry Andric   if (OpNo == NumOperands && NewTy == C->getType())
4483ca95b02SDimitry Andric     return getVM()[V] = C;
44917a519f9SDimitry Andric 
45017a519f9SDimitry Andric   // Okay, we need to create a new constant.  We've already processed some or
45117a519f9SDimitry Andric   // all of the operands, set them all up now.
45217a519f9SDimitry Andric   SmallVector<Constant*, 8> Ops;
45317a519f9SDimitry Andric   Ops.reserve(NumOperands);
45417a519f9SDimitry Andric   for (unsigned j = 0; j != OpNo; ++j)
45517a519f9SDimitry Andric     Ops.push_back(cast<Constant>(C->getOperand(j)));
45617a519f9SDimitry Andric 
45717a519f9SDimitry Andric   // If one of the operands mismatch, push it and the other mapped operands.
45817a519f9SDimitry Andric   if (OpNo != NumOperands) {
4592754fe60SDimitry Andric     Ops.push_back(cast<Constant>(Mapped));
4602754fe60SDimitry Andric 
4612754fe60SDimitry Andric     // Map the rest of the operands that aren't processed yet.
4623ca95b02SDimitry Andric     for (++OpNo; OpNo != NumOperands; ++OpNo) {
4633ca95b02SDimitry Andric       Mapped = mapValueOrNull(C->getOperand(OpNo));
4643ca95b02SDimitry Andric       if (!Mapped)
4653ca95b02SDimitry Andric         return nullptr;
4663ca95b02SDimitry Andric       Ops.push_back(cast<Constant>(Mapped));
4673ca95b02SDimitry Andric     }
4682754fe60SDimitry Andric   }
4697d523365SDimitry Andric   Type *NewSrcTy = nullptr;
4707d523365SDimitry Andric   if (TypeMapper)
4717d523365SDimitry Andric     if (auto *GEPO = dyn_cast<GEPOperator>(C))
4727d523365SDimitry Andric       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
4732754fe60SDimitry Andric 
47417a519f9SDimitry Andric   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
4753ca95b02SDimitry Andric     return getVM()[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
47617a519f9SDimitry Andric   if (isa<ConstantArray>(C))
4773ca95b02SDimitry Andric     return getVM()[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
47817a519f9SDimitry Andric   if (isa<ConstantStruct>(C))
4793ca95b02SDimitry Andric     return getVM()[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
48017a519f9SDimitry Andric   if (isa<ConstantVector>(C))
4813ca95b02SDimitry Andric     return getVM()[V] = ConstantVector::get(Ops);
48217a519f9SDimitry Andric   // If this is a no-operand constant, it must be because the type was remapped.
48317a519f9SDimitry Andric   if (isa<UndefValue>(C))
4843ca95b02SDimitry Andric     return getVM()[V] = UndefValue::get(NewTy);
48517a519f9SDimitry Andric   if (isa<ConstantAggregateZero>(C))
4863ca95b02SDimitry Andric     return getVM()[V] = ConstantAggregateZero::get(NewTy);
48717a519f9SDimitry Andric   assert(isa<ConstantPointerNull>(C));
4883ca95b02SDimitry Andric   return getVM()[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
4892754fe60SDimitry Andric }
4902754fe60SDimitry Andric 
mapBlockAddress(const BlockAddress & BA)4913ca95b02SDimitry Andric Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
4923ca95b02SDimitry Andric   Function *F = cast<Function>(mapValue(BA.getFunction()));
4933ca95b02SDimitry Andric 
4943ca95b02SDimitry Andric   // F may not have materialized its initializer.  In that case, create a
4953ca95b02SDimitry Andric   // dummy basic block for now, and replace it once we've materialized all
4963ca95b02SDimitry Andric   // the initializers.
4973ca95b02SDimitry Andric   BasicBlock *BB;
4983ca95b02SDimitry Andric   if (F->empty()) {
4993ca95b02SDimitry Andric     DelayedBBs.push_back(DelayedBasicBlock(BA));
5003ca95b02SDimitry Andric     BB = DelayedBBs.back().TempBB.get();
5013ca95b02SDimitry Andric   } else {
5023ca95b02SDimitry Andric     BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
5037d523365SDimitry Andric   }
5043ca95b02SDimitry Andric 
5053ca95b02SDimitry Andric   return getVM()[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
5063ca95b02SDimitry Andric }
5073ca95b02SDimitry Andric 
mapToMetadata(const Metadata * Key,Metadata * Val)5083ca95b02SDimitry Andric Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
5093ca95b02SDimitry Andric   getVM().MD()[Key].reset(Val);
51039d628a0SDimitry Andric   return Val;
51139d628a0SDimitry Andric }
51239d628a0SDimitry Andric 
mapToSelf(const Metadata * MD)5133ca95b02SDimitry Andric Metadata *Mapper::mapToSelf(const Metadata *MD) {
5143ca95b02SDimitry Andric   return mapToMetadata(MD, const_cast<Metadata *>(MD));
51539d628a0SDimitry Andric }
51639d628a0SDimitry Andric 
tryToMapOperand(const Metadata * Op)5173ca95b02SDimitry Andric Optional<Metadata *> MDNodeMapper::tryToMapOperand(const Metadata *Op) {
51839d628a0SDimitry Andric   if (!Op)
51939d628a0SDimitry Andric     return nullptr;
5207d523365SDimitry Andric 
5213ca95b02SDimitry Andric   if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
5223ca95b02SDimitry Andric #ifndef NDEBUG
5233ca95b02SDimitry Andric     if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
5243ca95b02SDimitry Andric       assert((!*MappedOp || M.getVM().count(CMD->getValue()) ||
5253ca95b02SDimitry Andric               M.getVM().getMappedMD(Op)) &&
5263ca95b02SDimitry Andric              "Expected Value to be memoized");
5273ca95b02SDimitry Andric     else
5283ca95b02SDimitry Andric       assert((isa<MDString>(Op) || M.getVM().getMappedMD(Op)) &&
5293ca95b02SDimitry Andric              "Expected result to be memoized");
5303ca95b02SDimitry Andric #endif
5313ca95b02SDimitry Andric     return *MappedOp;
5323ca95b02SDimitry Andric   }
5333ca95b02SDimitry Andric 
5343ca95b02SDimitry Andric   const MDNode &N = *cast<MDNode>(Op);
5353ca95b02SDimitry Andric   if (N.isDistinct())
5363ca95b02SDimitry Andric     return mapDistinctNode(N);
5373ca95b02SDimitry Andric   return None;
5383ca95b02SDimitry Andric }
5393ca95b02SDimitry Andric 
cloneOrBuildODR(const MDNode & N)540*842d113bSDimitry Andric static Metadata *cloneOrBuildODR(const MDNode &N) {
541*842d113bSDimitry Andric   auto *CT = dyn_cast<DICompositeType>(&N);
542*842d113bSDimitry Andric   // If ODR type uniquing is enabled, we would have uniqued composite types
543*842d113bSDimitry Andric   // with identifiers during bitcode reading, so we can just use CT.
544*842d113bSDimitry Andric   if (CT && CT->getContext().isODRUniquingDebugTypes() &&
545*842d113bSDimitry Andric       CT->getIdentifier() != "")
546*842d113bSDimitry Andric     return const_cast<DICompositeType *>(CT);
547*842d113bSDimitry Andric   return MDNode::replaceWithDistinct(N.clone());
548*842d113bSDimitry Andric }
549*842d113bSDimitry Andric 
mapDistinctNode(const MDNode & N)5503ca95b02SDimitry Andric MDNode *MDNodeMapper::mapDistinctNode(const MDNode &N) {
5513ca95b02SDimitry Andric   assert(N.isDistinct() && "Expected a distinct node");
5523ca95b02SDimitry Andric   assert(!M.getVM().getMappedMD(&N) && "Expected an unmapped node");
553*842d113bSDimitry Andric   DistinctWorklist.push_back(
554*842d113bSDimitry Andric       cast<MDNode>((M.Flags & RF_MoveDistinctMDs)
5553ca95b02SDimitry Andric                        ? M.mapToSelf(&N)
556*842d113bSDimitry Andric                        : M.mapToMetadata(&N, cloneOrBuildODR(N))));
5573ca95b02SDimitry Andric   return DistinctWorklist.back();
5583ca95b02SDimitry Andric }
5593ca95b02SDimitry Andric 
wrapConstantAsMetadata(const ConstantAsMetadata & CMD,Value * MappedV)5603ca95b02SDimitry Andric static ConstantAsMetadata *wrapConstantAsMetadata(const ConstantAsMetadata &CMD,
5613ca95b02SDimitry Andric                                                   Value *MappedV) {
5623ca95b02SDimitry Andric   if (CMD.getValue() == MappedV)
5633ca95b02SDimitry Andric     return const_cast<ConstantAsMetadata *>(&CMD);
5643ca95b02SDimitry Andric   return MappedV ? ConstantAsMetadata::getConstant(MappedV) : nullptr;
5653ca95b02SDimitry Andric }
5663ca95b02SDimitry Andric 
getMappedOp(const Metadata * Op) const5673ca95b02SDimitry Andric Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
5683ca95b02SDimitry Andric   if (!Op)
5697d523365SDimitry Andric     return nullptr;
5707d523365SDimitry Andric 
5713ca95b02SDimitry Andric   if (Optional<Metadata *> MappedOp = M.getVM().getMappedMD(Op))
5723ca95b02SDimitry Andric     return *MappedOp;
5733ca95b02SDimitry Andric 
5743ca95b02SDimitry Andric   if (isa<MDString>(Op))
5753ca95b02SDimitry Andric     return const_cast<Metadata *>(Op);
5763ca95b02SDimitry Andric 
5773ca95b02SDimitry Andric   if (auto *CMD = dyn_cast<ConstantAsMetadata>(Op))
5783ca95b02SDimitry Andric     return wrapConstantAsMetadata(*CMD, M.getVM().lookup(CMD->getValue()));
5793ca95b02SDimitry Andric 
5803ca95b02SDimitry Andric   return None;
5813ca95b02SDimitry Andric }
5823ca95b02SDimitry Andric 
getFwdReference(MDNode & Op)5833ca95b02SDimitry Andric Metadata &MDNodeMapper::UniquedGraph::getFwdReference(MDNode &Op) {
5843ca95b02SDimitry Andric   auto Where = Info.find(&Op);
5853ca95b02SDimitry Andric   assert(Where != Info.end() && "Expected a valid reference");
5863ca95b02SDimitry Andric 
5873ca95b02SDimitry Andric   auto &OpD = Where->second;
5883ca95b02SDimitry Andric   if (!OpD.HasChanged)
58939d628a0SDimitry Andric     return Op;
59039d628a0SDimitry Andric 
5913ca95b02SDimitry Andric   // Lazily construct a temporary node.
5923ca95b02SDimitry Andric   if (!OpD.Placeholder)
5933ca95b02SDimitry Andric     OpD.Placeholder = Op.clone();
5943ca95b02SDimitry Andric 
5953ca95b02SDimitry Andric   return *OpD.Placeholder;
5963ca95b02SDimitry Andric }
5973ca95b02SDimitry Andric 
5983ca95b02SDimitry Andric template <class OperandMapper>
remapOperands(MDNode & N,OperandMapper mapOperand)5993ca95b02SDimitry Andric void MDNodeMapper::remapOperands(MDNode &N, OperandMapper mapOperand) {
6003ca95b02SDimitry Andric   assert(!N.isUniqued() && "Expected distinct or temporary nodes");
6013ca95b02SDimitry Andric   for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
6023ca95b02SDimitry Andric     Metadata *Old = N.getOperand(I);
6033ca95b02SDimitry Andric     Metadata *New = mapOperand(Old);
6043ca95b02SDimitry Andric 
6053ca95b02SDimitry Andric     if (Old != New)
6063ca95b02SDimitry Andric       N.replaceOperandWith(I, New);
6073ca95b02SDimitry Andric   }
6083ca95b02SDimitry Andric }
6093ca95b02SDimitry Andric 
6103ca95b02SDimitry Andric namespace {
6112cab237bSDimitry Andric 
6123ca95b02SDimitry Andric /// An entry in the worklist for the post-order traversal.
6133ca95b02SDimitry Andric struct POTWorklistEntry {
6143ca95b02SDimitry Andric   MDNode *N;              ///< Current node.
6153ca95b02SDimitry Andric   MDNode::op_iterator Op; ///< Current operand of \c N.
6163ca95b02SDimitry Andric 
6173ca95b02SDimitry Andric   /// Keep a flag of whether operands have changed in the worklist to avoid
6183ca95b02SDimitry Andric   /// hitting the map in \a UniquedGraph.
6193ca95b02SDimitry Andric   bool HasChanged = false;
6203ca95b02SDimitry Andric 
POTWorklistEntry__anonc32747150411::POTWorklistEntry6213ca95b02SDimitry Andric   POTWorklistEntry(MDNode &N) : N(&N), Op(N.op_begin()) {}
6223ca95b02SDimitry Andric };
6232cab237bSDimitry Andric 
6242cab237bSDimitry Andric } // end anonymous namespace
6253ca95b02SDimitry Andric 
createPOT(UniquedGraph & G,const MDNode & FirstN)6263ca95b02SDimitry Andric bool MDNodeMapper::createPOT(UniquedGraph &G, const MDNode &FirstN) {
6273ca95b02SDimitry Andric   assert(G.Info.empty() && "Expected a fresh traversal");
6283ca95b02SDimitry Andric   assert(FirstN.isUniqued() && "Expected uniqued node in POT");
6293ca95b02SDimitry Andric 
6303ca95b02SDimitry Andric   // Construct a post-order traversal of the uniqued subgraph under FirstN.
6313ca95b02SDimitry Andric   bool AnyChanges = false;
6323ca95b02SDimitry Andric   SmallVector<POTWorklistEntry, 16> Worklist;
6333ca95b02SDimitry Andric   Worklist.push_back(POTWorklistEntry(const_cast<MDNode &>(FirstN)));
6343ca95b02SDimitry Andric   (void)G.Info[&FirstN];
6353ca95b02SDimitry Andric   while (!Worklist.empty()) {
6363ca95b02SDimitry Andric     // Start or continue the traversal through the this node's operands.
6373ca95b02SDimitry Andric     auto &WE = Worklist.back();
6383ca95b02SDimitry Andric     if (MDNode *N = visitOperands(G, WE.Op, WE.N->op_end(), WE.HasChanged)) {
6393ca95b02SDimitry Andric       // Push a new node to traverse first.
6403ca95b02SDimitry Andric       Worklist.push_back(POTWorklistEntry(*N));
6413ca95b02SDimitry Andric       continue;
6423ca95b02SDimitry Andric     }
6433ca95b02SDimitry Andric 
6443ca95b02SDimitry Andric     // Push the node onto the POT.
6453ca95b02SDimitry Andric     assert(WE.N->isUniqued() && "Expected only uniqued nodes");
6463ca95b02SDimitry Andric     assert(WE.Op == WE.N->op_end() && "Expected to visit all operands");
6473ca95b02SDimitry Andric     auto &D = G.Info[WE.N];
6483ca95b02SDimitry Andric     AnyChanges |= D.HasChanged = WE.HasChanged;
6493ca95b02SDimitry Andric     D.ID = G.POT.size();
6503ca95b02SDimitry Andric     G.POT.push_back(WE.N);
6513ca95b02SDimitry Andric 
6523ca95b02SDimitry Andric     // Pop the node off the worklist.
6533ca95b02SDimitry Andric     Worklist.pop_back();
6543ca95b02SDimitry Andric   }
6553ca95b02SDimitry Andric   return AnyChanges;
6563ca95b02SDimitry Andric }
6573ca95b02SDimitry Andric 
visitOperands(UniquedGraph & G,MDNode::op_iterator & I,MDNode::op_iterator E,bool & HasChanged)6583ca95b02SDimitry Andric MDNode *MDNodeMapper::visitOperands(UniquedGraph &G, MDNode::op_iterator &I,
6593ca95b02SDimitry Andric                                     MDNode::op_iterator E, bool &HasChanged) {
6603ca95b02SDimitry Andric   while (I != E) {
6613ca95b02SDimitry Andric     Metadata *Op = *I++; // Increment even on early return.
6623ca95b02SDimitry Andric     if (Optional<Metadata *> MappedOp = tryToMapOperand(Op)) {
6633ca95b02SDimitry Andric       // Check if the operand changes.
6643ca95b02SDimitry Andric       HasChanged |= Op != *MappedOp;
6653ca95b02SDimitry Andric       continue;
6663ca95b02SDimitry Andric     }
6673ca95b02SDimitry Andric 
6683ca95b02SDimitry Andric     // A uniqued metadata node.
6693ca95b02SDimitry Andric     MDNode &OpN = *cast<MDNode>(Op);
6703ca95b02SDimitry Andric     assert(OpN.isUniqued() &&
6713ca95b02SDimitry Andric            "Only uniqued operands cannot be mapped immediately");
6723ca95b02SDimitry Andric     if (G.Info.insert(std::make_pair(&OpN, Data())).second)
6733ca95b02SDimitry Andric       return &OpN; // This is a new one.  Return it.
6743ca95b02SDimitry Andric   }
67539d628a0SDimitry Andric   return nullptr;
67639d628a0SDimitry Andric }
67739d628a0SDimitry Andric 
propagateChanges()6783ca95b02SDimitry Andric void MDNodeMapper::UniquedGraph::propagateChanges() {
6793ca95b02SDimitry Andric   bool AnyChanges;
6803ca95b02SDimitry Andric   do {
6813ca95b02SDimitry Andric     AnyChanges = false;
6823ca95b02SDimitry Andric     for (MDNode *N : POT) {
6833ca95b02SDimitry Andric       auto &D = Info[N];
6843ca95b02SDimitry Andric       if (D.HasChanged)
6853ca95b02SDimitry Andric         continue;
6863ca95b02SDimitry Andric 
6872cab237bSDimitry Andric       if (llvm::none_of(N->operands(), [&](const Metadata *Op) {
6883ca95b02SDimitry Andric             auto Where = Info.find(Op);
6893ca95b02SDimitry Andric             return Where != Info.end() && Where->second.HasChanged;
6903ca95b02SDimitry Andric           }))
6913ca95b02SDimitry Andric         continue;
6923ca95b02SDimitry Andric 
6933ca95b02SDimitry Andric       AnyChanges = D.HasChanged = true;
6943ca95b02SDimitry Andric     }
6953ca95b02SDimitry Andric   } while (AnyChanges);
6963ca95b02SDimitry Andric }
6973ca95b02SDimitry Andric 
mapNodesInPOT(UniquedGraph & G)6983ca95b02SDimitry Andric void MDNodeMapper::mapNodesInPOT(UniquedGraph &G) {
6993ca95b02SDimitry Andric   // Construct uniqued nodes, building forward references as necessary.
7003ca95b02SDimitry Andric   SmallVector<MDNode *, 16> CyclicNodes;
7013ca95b02SDimitry Andric   for (auto *N : G.POT) {
7023ca95b02SDimitry Andric     auto &D = G.Info[N];
7033ca95b02SDimitry Andric     if (!D.HasChanged) {
7043ca95b02SDimitry Andric       // The node hasn't changed.
7053ca95b02SDimitry Andric       M.mapToSelf(N);
7063ca95b02SDimitry Andric       continue;
7073ca95b02SDimitry Andric     }
7083ca95b02SDimitry Andric 
7093ca95b02SDimitry Andric     // Remember whether this node had a placeholder.
7103ca95b02SDimitry Andric     bool HadPlaceholder(D.Placeholder);
7113ca95b02SDimitry Andric 
7123ca95b02SDimitry Andric     // Clone the uniqued node and remap the operands.
7133ca95b02SDimitry Andric     TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
7143ca95b02SDimitry Andric     remapOperands(*ClonedN, [this, &D, &G](Metadata *Old) {
7153ca95b02SDimitry Andric       if (Optional<Metadata *> MappedOp = getMappedOp(Old))
7163ca95b02SDimitry Andric         return *MappedOp;
7177a7e6055SDimitry Andric       (void)D;
7183ca95b02SDimitry Andric       assert(G.Info[Old].ID > D.ID && "Expected a forward reference");
7193ca95b02SDimitry Andric       return &G.getFwdReference(*cast<MDNode>(Old));
7203ca95b02SDimitry Andric     });
7213ca95b02SDimitry Andric 
7223ca95b02SDimitry Andric     auto *NewN = MDNode::replaceWithUniqued(std::move(ClonedN));
7233ca95b02SDimitry Andric     M.mapToMetadata(N, NewN);
7243ca95b02SDimitry Andric 
7253ca95b02SDimitry Andric     // Nodes that were referenced out of order in the POT are involved in a
7263ca95b02SDimitry Andric     // uniquing cycle.
7273ca95b02SDimitry Andric     if (HadPlaceholder)
7283ca95b02SDimitry Andric       CyclicNodes.push_back(NewN);
7293ca95b02SDimitry Andric   }
7303ca95b02SDimitry Andric 
7313ca95b02SDimitry Andric   // Resolve cycles.
7323ca95b02SDimitry Andric   for (auto *N : CyclicNodes)
7333ca95b02SDimitry Andric     if (!N->isResolved())
734444ed5c5SDimitry Andric       N->resolveCycles();
735444ed5c5SDimitry Andric }
7367d523365SDimitry Andric 
map(const MDNode & N)7373ca95b02SDimitry Andric Metadata *MDNodeMapper::map(const MDNode &N) {
7383ca95b02SDimitry Andric   assert(DistinctWorklist.empty() && "MDNodeMapper::map is not recursive");
7393ca95b02SDimitry Andric   assert(!(M.Flags & RF_NoModuleLevelChanges) &&
7403ca95b02SDimitry Andric          "MDNodeMapper::map assumes module-level changes");
74139d628a0SDimitry Andric 
742ff0cc061SDimitry Andric   // Require resolved nodes whenever metadata might be remapped.
7433ca95b02SDimitry Andric   assert(N.isResolved() && "Unexpected unresolved node");
7447d523365SDimitry Andric 
7453ca95b02SDimitry Andric   Metadata *MappedN =
7463ca95b02SDimitry Andric       N.isUniqued() ? mapTopLevelUniquedNode(N) : mapDistinctNode(N);
7477d523365SDimitry Andric   while (!DistinctWorklist.empty())
7483ca95b02SDimitry Andric     remapOperands(*DistinctWorklist.pop_back_val(), [this](Metadata *Old) {
7493ca95b02SDimitry Andric       if (Optional<Metadata *> MappedOp = tryToMapOperand(Old))
7503ca95b02SDimitry Andric         return *MappedOp;
7513ca95b02SDimitry Andric       return mapTopLevelUniquedNode(*cast<MDNode>(Old));
7523ca95b02SDimitry Andric     });
7533ca95b02SDimitry Andric   return MappedN;
75439d628a0SDimitry Andric }
75539d628a0SDimitry Andric 
mapTopLevelUniquedNode(const MDNode & FirstN)7563ca95b02SDimitry Andric Metadata *MDNodeMapper::mapTopLevelUniquedNode(const MDNode &FirstN) {
7573ca95b02SDimitry Andric   assert(FirstN.isUniqued() && "Expected uniqued node");
7583ca95b02SDimitry Andric 
7593ca95b02SDimitry Andric   // Create a post-order traversal of uniqued nodes under FirstN.
7603ca95b02SDimitry Andric   UniquedGraph G;
7613ca95b02SDimitry Andric   if (!createPOT(G, FirstN)) {
7623ca95b02SDimitry Andric     // Return early if no nodes have changed.
7633ca95b02SDimitry Andric     for (const MDNode *N : G.POT)
7643ca95b02SDimitry Andric       M.mapToSelf(N);
7653ca95b02SDimitry Andric     return &const_cast<MDNode &>(FirstN);
76639d628a0SDimitry Andric   }
76739d628a0SDimitry Andric 
7683ca95b02SDimitry Andric   // Update graph with all nodes that have changed.
7693ca95b02SDimitry Andric   G.propagateChanges();
7703ca95b02SDimitry Andric 
7713ca95b02SDimitry Andric   // Map all the nodes in the graph.
7723ca95b02SDimitry Andric   mapNodesInPOT(G);
7733ca95b02SDimitry Andric 
7743ca95b02SDimitry Andric   // Return the original node, remapped.
7753ca95b02SDimitry Andric   return *getMappedOp(&FirstN);
7763ca95b02SDimitry Andric }
7773ca95b02SDimitry Andric 
7783ca95b02SDimitry Andric namespace {
7793ca95b02SDimitry Andric 
7803ca95b02SDimitry Andric struct MapMetadataDisabler {
7813ca95b02SDimitry Andric   ValueToValueMapTy &VM;
7823ca95b02SDimitry Andric 
MapMetadataDisabler__anonc32747150811::MapMetadataDisabler7833ca95b02SDimitry Andric   MapMetadataDisabler(ValueToValueMapTy &VM) : VM(VM) {
7843ca95b02SDimitry Andric     VM.disableMapMetadata();
7853ca95b02SDimitry Andric   }
7862cab237bSDimitry Andric 
~MapMetadataDisabler__anonc32747150811::MapMetadataDisabler7873ca95b02SDimitry Andric   ~MapMetadataDisabler() { VM.enableMapMetadata(); }
7883ca95b02SDimitry Andric };
7893ca95b02SDimitry Andric 
7902cab237bSDimitry Andric } // end anonymous namespace
7913ca95b02SDimitry Andric 
mapSimpleMetadata(const Metadata * MD)7923ca95b02SDimitry Andric Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
7933ca95b02SDimitry Andric   // If the value already exists in the map, use it.
7943ca95b02SDimitry Andric   if (Optional<Metadata *> NewMD = getVM().getMappedMD(MD))
7953ca95b02SDimitry Andric     return *NewMD;
7963ca95b02SDimitry Andric 
7973ca95b02SDimitry Andric   if (isa<MDString>(MD))
7983ca95b02SDimitry Andric     return const_cast<Metadata *>(MD);
7993ca95b02SDimitry Andric 
8003ca95b02SDimitry Andric   // This is a module-level metadata.  If nothing at the module level is
8013ca95b02SDimitry Andric   // changing, use an identity mapping.
8023ca95b02SDimitry Andric   if ((Flags & RF_NoModuleLevelChanges))
8033ca95b02SDimitry Andric     return const_cast<Metadata *>(MD);
8043ca95b02SDimitry Andric 
8053ca95b02SDimitry Andric   if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
8063ca95b02SDimitry Andric     // Disallow recursion into metadata mapping through mapValue.
8073ca95b02SDimitry Andric     MapMetadataDisabler MMD(getVM());
8083ca95b02SDimitry Andric 
8093ca95b02SDimitry Andric     // Don't memoize ConstantAsMetadata.  Instead of lasting until the
8103ca95b02SDimitry Andric     // LLVMContext is destroyed, they can be deleted when the GlobalValue they
8113ca95b02SDimitry Andric     // reference is destructed.  These aren't super common, so the extra
8123ca95b02SDimitry Andric     // indirection isn't that expensive.
8133ca95b02SDimitry Andric     return wrapConstantAsMetadata(*CMD, mapValue(CMD->getValue()));
8143ca95b02SDimitry Andric   }
8153ca95b02SDimitry Andric 
8163ca95b02SDimitry Andric   assert(isa<MDNode>(MD) && "Expected a metadata node");
8173ca95b02SDimitry Andric 
8183ca95b02SDimitry Andric   return None;
8193ca95b02SDimitry Andric }
8203ca95b02SDimitry Andric 
mapMetadata(const Metadata * MD)8213ca95b02SDimitry Andric Metadata *Mapper::mapMetadata(const Metadata *MD) {
8223ca95b02SDimitry Andric   assert(MD && "Expected valid metadata");
8233ca95b02SDimitry Andric   assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
8243ca95b02SDimitry Andric 
8253ca95b02SDimitry Andric   if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
8263ca95b02SDimitry Andric     return *NewMD;
8273ca95b02SDimitry Andric 
8283ca95b02SDimitry Andric   return MDNodeMapper(*this).map(*cast<MDNode>(MD));
8293ca95b02SDimitry Andric }
8303ca95b02SDimitry Andric 
flush()8313ca95b02SDimitry Andric void Mapper::flush() {
8323ca95b02SDimitry Andric   // Flush out the worklist of global values.
8333ca95b02SDimitry Andric   while (!Worklist.empty()) {
8343ca95b02SDimitry Andric     WorklistEntry E = Worklist.pop_back_val();
8353ca95b02SDimitry Andric     CurrentMCID = E.MCID;
8363ca95b02SDimitry Andric     switch (E.Kind) {
8373ca95b02SDimitry Andric     case WorklistEntry::MapGlobalInit:
8383ca95b02SDimitry Andric       E.Data.GVInit.GV->setInitializer(mapConstant(E.Data.GVInit.Init));
8390f5676f4SDimitry Andric       remapGlobalObjectMetadata(*E.Data.GVInit.GV);
8403ca95b02SDimitry Andric       break;
8413ca95b02SDimitry Andric     case WorklistEntry::MapAppendingVar: {
8423ca95b02SDimitry Andric       unsigned PrefixSize = AppendingInits.size() - E.AppendingGVNumNewMembers;
8433ca95b02SDimitry Andric       mapAppendingVariable(*E.Data.AppendingGV.GV,
8443ca95b02SDimitry Andric                            E.Data.AppendingGV.InitPrefix,
8453ca95b02SDimitry Andric                            E.AppendingGVIsOldCtorDtor,
8463ca95b02SDimitry Andric                            makeArrayRef(AppendingInits).slice(PrefixSize));
8473ca95b02SDimitry Andric       AppendingInits.resize(PrefixSize);
8483ca95b02SDimitry Andric       break;
8493ca95b02SDimitry Andric     }
8503ca95b02SDimitry Andric     case WorklistEntry::MapGlobalAliasee:
8513ca95b02SDimitry Andric       E.Data.GlobalAliasee.GA->setAliasee(
8523ca95b02SDimitry Andric           mapConstant(E.Data.GlobalAliasee.Aliasee));
8533ca95b02SDimitry Andric       break;
8543ca95b02SDimitry Andric     case WorklistEntry::RemapFunction:
8553ca95b02SDimitry Andric       remapFunction(*E.Data.RemapF);
8563ca95b02SDimitry Andric       break;
8573ca95b02SDimitry Andric     }
8583ca95b02SDimitry Andric   }
8593ca95b02SDimitry Andric   CurrentMCID = 0;
8603ca95b02SDimitry Andric 
8613ca95b02SDimitry Andric   // Finish logic for block addresses now that all global values have been
8623ca95b02SDimitry Andric   // handled.
8633ca95b02SDimitry Andric   while (!DelayedBBs.empty()) {
8643ca95b02SDimitry Andric     DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
8653ca95b02SDimitry Andric     BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
8663ca95b02SDimitry Andric     DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
8673ca95b02SDimitry Andric   }
8683ca95b02SDimitry Andric }
8693ca95b02SDimitry Andric 
remapInstruction(Instruction * I)8703ca95b02SDimitry Andric void Mapper::remapInstruction(Instruction *I) {
871e580952dSDimitry Andric   // Remap operands.
8723ca95b02SDimitry Andric   for (Use &Op : I->operands()) {
8733ca95b02SDimitry Andric     Value *V = mapValue(Op);
8742754fe60SDimitry Andric     // If we aren't ignoring missing entries, assert that something happened.
87591bc56edSDimitry Andric     if (V)
8763ca95b02SDimitry Andric       Op = V;
8772754fe60SDimitry Andric     else
8783ca95b02SDimitry Andric       assert((Flags & RF_IgnoreMissingLocals) &&
8792754fe60SDimitry Andric              "Referenced value not in value map!");
880f22ef01cSRoman Divacky   }
881f22ef01cSRoman Divacky 
88217a519f9SDimitry Andric   // Remap phi nodes' incoming blocks.
88317a519f9SDimitry Andric   if (PHINode *PN = dyn_cast<PHINode>(I)) {
88417a519f9SDimitry Andric     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
8853ca95b02SDimitry Andric       Value *V = mapValue(PN->getIncomingBlock(i));
88617a519f9SDimitry Andric       // If we aren't ignoring missing entries, assert that something happened.
88791bc56edSDimitry Andric       if (V)
88817a519f9SDimitry Andric         PN->setIncomingBlock(i, cast<BasicBlock>(V));
88917a519f9SDimitry Andric       else
8903ca95b02SDimitry Andric         assert((Flags & RF_IgnoreMissingLocals) &&
89117a519f9SDimitry Andric                "Referenced block not in value map!");
89217a519f9SDimitry Andric     }
89317a519f9SDimitry Andric   }
89417a519f9SDimitry Andric 
8956122f3e6SDimitry Andric   // Remap attached metadata.
896e580952dSDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
8976122f3e6SDimitry Andric   I->getAllMetadata(MDs);
8987d523365SDimitry Andric   for (const auto &MI : MDs) {
8997d523365SDimitry Andric     MDNode *Old = MI.second;
9003ca95b02SDimitry Andric     MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
901e580952dSDimitry Andric     if (New != Old)
9027d523365SDimitry Andric       I->setMetadata(MI.first, New);
903e580952dSDimitry Andric   }
90417a519f9SDimitry Andric 
905ff0cc061SDimitry Andric   if (!TypeMapper)
906ff0cc061SDimitry Andric     return;
907ff0cc061SDimitry Andric 
90817a519f9SDimitry Andric   // If the instruction's type is being remapped, do so now.
909ff0cc061SDimitry Andric   if (auto CS = CallSite(I)) {
910ff0cc061SDimitry Andric     SmallVector<Type *, 3> Tys;
911ff0cc061SDimitry Andric     FunctionType *FTy = CS.getFunctionType();
912ff0cc061SDimitry Andric     Tys.reserve(FTy->getNumParams());
913ff0cc061SDimitry Andric     for (Type *Ty : FTy->params())
914ff0cc061SDimitry Andric       Tys.push_back(TypeMapper->remapType(Ty));
915ff0cc061SDimitry Andric     CS.mutateFunctionType(FunctionType::get(
916ff0cc061SDimitry Andric         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
917ff0cc061SDimitry Andric     return;
918ff0cc061SDimitry Andric   }
919ff0cc061SDimitry Andric   if (auto *AI = dyn_cast<AllocaInst>(I))
920ff0cc061SDimitry Andric     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
92197bc6c73SDimitry Andric   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
922ff0cc061SDimitry Andric     GEP->setSourceElementType(
923ff0cc061SDimitry Andric         TypeMapper->remapType(GEP->getSourceElementType()));
92497bc6c73SDimitry Andric     GEP->setResultElementType(
92597bc6c73SDimitry Andric         TypeMapper->remapType(GEP->getResultElementType()));
92697bc6c73SDimitry Andric   }
92717a519f9SDimitry Andric   I->mutateType(TypeMapper->remapType(I->getType()));
928e580952dSDimitry Andric }
9293ca95b02SDimitry Andric 
remapGlobalObjectMetadata(GlobalObject & GO)9300f5676f4SDimitry Andric void Mapper::remapGlobalObjectMetadata(GlobalObject &GO) {
9310f5676f4SDimitry Andric   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
9320f5676f4SDimitry Andric   GO.getAllMetadata(MDs);
9330f5676f4SDimitry Andric   GO.clearMetadata();
9340f5676f4SDimitry Andric   for (const auto &I : MDs)
9350f5676f4SDimitry Andric     GO.addMetadata(I.first, *cast<MDNode>(mapMetadata(I.second)));
9360f5676f4SDimitry Andric }
9370f5676f4SDimitry Andric 
remapFunction(Function & F)9383ca95b02SDimitry Andric void Mapper::remapFunction(Function &F) {
9393ca95b02SDimitry Andric   // Remap the operands.
9403ca95b02SDimitry Andric   for (Use &Op : F.operands())
9413ca95b02SDimitry Andric     if (Op)
9423ca95b02SDimitry Andric       Op = mapValue(Op);
9433ca95b02SDimitry Andric 
9443ca95b02SDimitry Andric   // Remap the metadata attachments.
9450f5676f4SDimitry Andric   remapGlobalObjectMetadata(F);
9463ca95b02SDimitry Andric 
9473ca95b02SDimitry Andric   // Remap the argument types.
9483ca95b02SDimitry Andric   if (TypeMapper)
9493ca95b02SDimitry Andric     for (Argument &A : F.args())
9503ca95b02SDimitry Andric       A.mutateType(TypeMapper->remapType(A.getType()));
9513ca95b02SDimitry Andric 
9523ca95b02SDimitry Andric   // Remap the instructions.
9533ca95b02SDimitry Andric   for (BasicBlock &BB : F)
9543ca95b02SDimitry Andric     for (Instruction &I : BB)
9553ca95b02SDimitry Andric       remapInstruction(&I);
9563ca95b02SDimitry Andric }
9573ca95b02SDimitry Andric 
mapAppendingVariable(GlobalVariable & GV,Constant * InitPrefix,bool IsOldCtorDtor,ArrayRef<Constant * > NewMembers)9583ca95b02SDimitry Andric void Mapper::mapAppendingVariable(GlobalVariable &GV, Constant *InitPrefix,
9593ca95b02SDimitry Andric                                   bool IsOldCtorDtor,
9603ca95b02SDimitry Andric                                   ArrayRef<Constant *> NewMembers) {
9613ca95b02SDimitry Andric   SmallVector<Constant *, 16> Elements;
9623ca95b02SDimitry Andric   if (InitPrefix) {
9633ca95b02SDimitry Andric     unsigned NumElements =
9643ca95b02SDimitry Andric         cast<ArrayType>(InitPrefix->getType())->getNumElements();
9653ca95b02SDimitry Andric     for (unsigned I = 0; I != NumElements; ++I)
9663ca95b02SDimitry Andric       Elements.push_back(InitPrefix->getAggregateElement(I));
9673ca95b02SDimitry Andric   }
9683ca95b02SDimitry Andric 
9693ca95b02SDimitry Andric   PointerType *VoidPtrTy;
9703ca95b02SDimitry Andric   Type *EltTy;
9713ca95b02SDimitry Andric   if (IsOldCtorDtor) {
9723ca95b02SDimitry Andric     // FIXME: This upgrade is done during linking to support the C API.  See
9733ca95b02SDimitry Andric     // also IRLinker::linkAppendingVarProto() in IRMover.cpp.
9743ca95b02SDimitry Andric     VoidPtrTy = Type::getInt8Ty(GV.getContext())->getPointerTo();
9753ca95b02SDimitry Andric     auto &ST = *cast<StructType>(NewMembers.front()->getType());
9763ca95b02SDimitry Andric     Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
9773ca95b02SDimitry Andric     EltTy = StructType::get(GV.getContext(), Tys, false);
9783ca95b02SDimitry Andric   }
9793ca95b02SDimitry Andric 
9803ca95b02SDimitry Andric   for (auto *V : NewMembers) {
9813ca95b02SDimitry Andric     Constant *NewV;
9823ca95b02SDimitry Andric     if (IsOldCtorDtor) {
9833ca95b02SDimitry Andric       auto *S = cast<ConstantStruct>(V);
9845517e702SDimitry Andric       auto *E1 = cast<Constant>(mapValue(S->getOperand(0)));
9855517e702SDimitry Andric       auto *E2 = cast<Constant>(mapValue(S->getOperand(1)));
9865517e702SDimitry Andric       Constant *Null = Constant::getNullValue(VoidPtrTy);
9875517e702SDimitry Andric       NewV = ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null);
9883ca95b02SDimitry Andric     } else {
9893ca95b02SDimitry Andric       NewV = cast_or_null<Constant>(mapValue(V));
9903ca95b02SDimitry Andric     }
9913ca95b02SDimitry Andric     Elements.push_back(NewV);
9923ca95b02SDimitry Andric   }
9933ca95b02SDimitry Andric 
9943ca95b02SDimitry Andric   GV.setInitializer(ConstantArray::get(
9953ca95b02SDimitry Andric       cast<ArrayType>(GV.getType()->getElementType()), Elements));
9963ca95b02SDimitry Andric }
9973ca95b02SDimitry Andric 
scheduleMapGlobalInitializer(GlobalVariable & GV,Constant & Init,unsigned MCID)9983ca95b02SDimitry Andric void Mapper::scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init,
9993ca95b02SDimitry Andric                                           unsigned MCID) {
10003ca95b02SDimitry Andric   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
10013ca95b02SDimitry Andric   assert(MCID < MCs.size() && "Invalid mapping context");
10023ca95b02SDimitry Andric 
10033ca95b02SDimitry Andric   WorklistEntry WE;
10043ca95b02SDimitry Andric   WE.Kind = WorklistEntry::MapGlobalInit;
10053ca95b02SDimitry Andric   WE.MCID = MCID;
10063ca95b02SDimitry Andric   WE.Data.GVInit.GV = &GV;
10073ca95b02SDimitry Andric   WE.Data.GVInit.Init = &Init;
10083ca95b02SDimitry Andric   Worklist.push_back(WE);
10093ca95b02SDimitry Andric }
10103ca95b02SDimitry Andric 
scheduleMapAppendingVariable(GlobalVariable & GV,Constant * InitPrefix,bool IsOldCtorDtor,ArrayRef<Constant * > NewMembers,unsigned MCID)10113ca95b02SDimitry Andric void Mapper::scheduleMapAppendingVariable(GlobalVariable &GV,
10123ca95b02SDimitry Andric                                           Constant *InitPrefix,
10133ca95b02SDimitry Andric                                           bool IsOldCtorDtor,
10143ca95b02SDimitry Andric                                           ArrayRef<Constant *> NewMembers,
10153ca95b02SDimitry Andric                                           unsigned MCID) {
10163ca95b02SDimitry Andric   assert(AlreadyScheduled.insert(&GV).second && "Should not reschedule");
10173ca95b02SDimitry Andric   assert(MCID < MCs.size() && "Invalid mapping context");
10183ca95b02SDimitry Andric 
10193ca95b02SDimitry Andric   WorklistEntry WE;
10203ca95b02SDimitry Andric   WE.Kind = WorklistEntry::MapAppendingVar;
10213ca95b02SDimitry Andric   WE.MCID = MCID;
10223ca95b02SDimitry Andric   WE.Data.AppendingGV.GV = &GV;
10233ca95b02SDimitry Andric   WE.Data.AppendingGV.InitPrefix = InitPrefix;
10243ca95b02SDimitry Andric   WE.AppendingGVIsOldCtorDtor = IsOldCtorDtor;
10253ca95b02SDimitry Andric   WE.AppendingGVNumNewMembers = NewMembers.size();
10263ca95b02SDimitry Andric   Worklist.push_back(WE);
10273ca95b02SDimitry Andric   AppendingInits.append(NewMembers.begin(), NewMembers.end());
10283ca95b02SDimitry Andric }
10293ca95b02SDimitry Andric 
scheduleMapGlobalAliasee(GlobalAlias & GA,Constant & Aliasee,unsigned MCID)10303ca95b02SDimitry Andric void Mapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
10313ca95b02SDimitry Andric                                       unsigned MCID) {
10323ca95b02SDimitry Andric   assert(AlreadyScheduled.insert(&GA).second && "Should not reschedule");
10333ca95b02SDimitry Andric   assert(MCID < MCs.size() && "Invalid mapping context");
10343ca95b02SDimitry Andric 
10353ca95b02SDimitry Andric   WorklistEntry WE;
10363ca95b02SDimitry Andric   WE.Kind = WorklistEntry::MapGlobalAliasee;
10373ca95b02SDimitry Andric   WE.MCID = MCID;
10383ca95b02SDimitry Andric   WE.Data.GlobalAliasee.GA = &GA;
10393ca95b02SDimitry Andric   WE.Data.GlobalAliasee.Aliasee = &Aliasee;
10403ca95b02SDimitry Andric   Worklist.push_back(WE);
10413ca95b02SDimitry Andric }
10423ca95b02SDimitry Andric 
scheduleRemapFunction(Function & F,unsigned MCID)10433ca95b02SDimitry Andric void Mapper::scheduleRemapFunction(Function &F, unsigned MCID) {
10443ca95b02SDimitry Andric   assert(AlreadyScheduled.insert(&F).second && "Should not reschedule");
10453ca95b02SDimitry Andric   assert(MCID < MCs.size() && "Invalid mapping context");
10463ca95b02SDimitry Andric 
10473ca95b02SDimitry Andric   WorklistEntry WE;
10483ca95b02SDimitry Andric   WE.Kind = WorklistEntry::RemapFunction;
10493ca95b02SDimitry Andric   WE.MCID = MCID;
10503ca95b02SDimitry Andric   WE.Data.RemapF = &F;
10513ca95b02SDimitry Andric   Worklist.push_back(WE);
10523ca95b02SDimitry Andric }
10533ca95b02SDimitry Andric 
addFlags(RemapFlags Flags)10543ca95b02SDimitry Andric void Mapper::addFlags(RemapFlags Flags) {
10553ca95b02SDimitry Andric   assert(!hasWorkToDo() && "Expected to have flushed the worklist");
10563ca95b02SDimitry Andric   this->Flags = this->Flags | Flags;
10573ca95b02SDimitry Andric }
10583ca95b02SDimitry Andric 
getAsMapper(void * pImpl)10593ca95b02SDimitry Andric static Mapper *getAsMapper(void *pImpl) {
10603ca95b02SDimitry Andric   return reinterpret_cast<Mapper *>(pImpl);
10613ca95b02SDimitry Andric }
10623ca95b02SDimitry Andric 
10633ca95b02SDimitry Andric namespace {
10643ca95b02SDimitry Andric 
10653ca95b02SDimitry Andric class FlushingMapper {
10663ca95b02SDimitry Andric   Mapper &M;
10673ca95b02SDimitry Andric 
10683ca95b02SDimitry Andric public:
FlushingMapper(void * pImpl)10693ca95b02SDimitry Andric   explicit FlushingMapper(void *pImpl) : M(*getAsMapper(pImpl)) {
10703ca95b02SDimitry Andric     assert(!M.hasWorkToDo() && "Expected to be flushed");
10713ca95b02SDimitry Andric   }
10722cab237bSDimitry Andric 
~FlushingMapper()10733ca95b02SDimitry Andric   ~FlushingMapper() { M.flush(); }
10742cab237bSDimitry Andric 
operator ->() const10753ca95b02SDimitry Andric   Mapper *operator->() const { return &M; }
10763ca95b02SDimitry Andric };
10773ca95b02SDimitry Andric 
10782cab237bSDimitry Andric } // end anonymous namespace
10793ca95b02SDimitry Andric 
ValueMapper(ValueToValueMapTy & VM,RemapFlags Flags,ValueMapTypeRemapper * TypeMapper,ValueMaterializer * Materializer)10803ca95b02SDimitry Andric ValueMapper::ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags,
10813ca95b02SDimitry Andric                          ValueMapTypeRemapper *TypeMapper,
10823ca95b02SDimitry Andric                          ValueMaterializer *Materializer)
10833ca95b02SDimitry Andric     : pImpl(new Mapper(VM, Flags, TypeMapper, Materializer)) {}
10843ca95b02SDimitry Andric 
~ValueMapper()10853ca95b02SDimitry Andric ValueMapper::~ValueMapper() { delete getAsMapper(pImpl); }
10863ca95b02SDimitry Andric 
10873ca95b02SDimitry Andric unsigned
registerAlternateMappingContext(ValueToValueMapTy & VM,ValueMaterializer * Materializer)10883ca95b02SDimitry Andric ValueMapper::registerAlternateMappingContext(ValueToValueMapTy &VM,
10893ca95b02SDimitry Andric                                              ValueMaterializer *Materializer) {
10903ca95b02SDimitry Andric   return getAsMapper(pImpl)->registerAlternateMappingContext(VM, Materializer);
10913ca95b02SDimitry Andric }
10923ca95b02SDimitry Andric 
addFlags(RemapFlags Flags)10933ca95b02SDimitry Andric void ValueMapper::addFlags(RemapFlags Flags) {
10943ca95b02SDimitry Andric   FlushingMapper(pImpl)->addFlags(Flags);
10953ca95b02SDimitry Andric }
10963ca95b02SDimitry Andric 
mapValue(const Value & V)10973ca95b02SDimitry Andric Value *ValueMapper::mapValue(const Value &V) {
10983ca95b02SDimitry Andric   return FlushingMapper(pImpl)->mapValue(&V);
10993ca95b02SDimitry Andric }
11003ca95b02SDimitry Andric 
mapConstant(const Constant & C)11013ca95b02SDimitry Andric Constant *ValueMapper::mapConstant(const Constant &C) {
11023ca95b02SDimitry Andric   return cast_or_null<Constant>(mapValue(C));
11033ca95b02SDimitry Andric }
11043ca95b02SDimitry Andric 
mapMetadata(const Metadata & MD)11053ca95b02SDimitry Andric Metadata *ValueMapper::mapMetadata(const Metadata &MD) {
11063ca95b02SDimitry Andric   return FlushingMapper(pImpl)->mapMetadata(&MD);
11073ca95b02SDimitry Andric }
11083ca95b02SDimitry Andric 
mapMDNode(const MDNode & N)11093ca95b02SDimitry Andric MDNode *ValueMapper::mapMDNode(const MDNode &N) {
11103ca95b02SDimitry Andric   return cast_or_null<MDNode>(mapMetadata(N));
11113ca95b02SDimitry Andric }
11123ca95b02SDimitry Andric 
remapInstruction(Instruction & I)11133ca95b02SDimitry Andric void ValueMapper::remapInstruction(Instruction &I) {
11143ca95b02SDimitry Andric   FlushingMapper(pImpl)->remapInstruction(&I);
11153ca95b02SDimitry Andric }
11163ca95b02SDimitry Andric 
remapFunction(Function & F)11173ca95b02SDimitry Andric void ValueMapper::remapFunction(Function &F) {
11183ca95b02SDimitry Andric   FlushingMapper(pImpl)->remapFunction(F);
11193ca95b02SDimitry Andric }
11203ca95b02SDimitry Andric 
scheduleMapGlobalInitializer(GlobalVariable & GV,Constant & Init,unsigned MCID)11213ca95b02SDimitry Andric void ValueMapper::scheduleMapGlobalInitializer(GlobalVariable &GV,
11223ca95b02SDimitry Andric                                                Constant &Init,
11233ca95b02SDimitry Andric                                                unsigned MCID) {
11243ca95b02SDimitry Andric   getAsMapper(pImpl)->scheduleMapGlobalInitializer(GV, Init, MCID);
11253ca95b02SDimitry Andric }
11263ca95b02SDimitry Andric 
scheduleMapAppendingVariable(GlobalVariable & GV,Constant * InitPrefix,bool IsOldCtorDtor,ArrayRef<Constant * > NewMembers,unsigned MCID)11273ca95b02SDimitry Andric void ValueMapper::scheduleMapAppendingVariable(GlobalVariable &GV,
11283ca95b02SDimitry Andric                                                Constant *InitPrefix,
11293ca95b02SDimitry Andric                                                bool IsOldCtorDtor,
11303ca95b02SDimitry Andric                                                ArrayRef<Constant *> NewMembers,
11313ca95b02SDimitry Andric                                                unsigned MCID) {
11323ca95b02SDimitry Andric   getAsMapper(pImpl)->scheduleMapAppendingVariable(
11333ca95b02SDimitry Andric       GV, InitPrefix, IsOldCtorDtor, NewMembers, MCID);
11343ca95b02SDimitry Andric }
11353ca95b02SDimitry Andric 
scheduleMapGlobalAliasee(GlobalAlias & GA,Constant & Aliasee,unsigned MCID)11363ca95b02SDimitry Andric void ValueMapper::scheduleMapGlobalAliasee(GlobalAlias &GA, Constant &Aliasee,
11373ca95b02SDimitry Andric                                            unsigned MCID) {
11383ca95b02SDimitry Andric   getAsMapper(pImpl)->scheduleMapGlobalAliasee(GA, Aliasee, MCID);
11393ca95b02SDimitry Andric }
11403ca95b02SDimitry Andric 
scheduleRemapFunction(Function & F,unsigned MCID)11413ca95b02SDimitry Andric void ValueMapper::scheduleRemapFunction(Function &F, unsigned MCID) {
11423ca95b02SDimitry Andric   getAsMapper(pImpl)->scheduleRemapFunction(F, MCID);
11433ca95b02SDimitry Andric }
1144