ValueMapper.cpp 41 KB

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