ValueMapper.cpp 41 KB

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