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