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