1 //===- ValueEnumerator.cpp - Number values and types for bitcode writer ---===// 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 implements the ValueEnumerator class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "ValueEnumerator.h" 14 #include "llvm/ADT/SmallVector.h" 15 #include "llvm/Config/llvm-config.h" 16 #include "llvm/IR/Argument.h" 17 #include "llvm/IR/BasicBlock.h" 18 #include "llvm/IR/Constant.h" 19 #include "llvm/IR/DebugInfoMetadata.h" 20 #include "llvm/IR/DerivedTypes.h" 21 #include "llvm/IR/Function.h" 22 #include "llvm/IR/GlobalAlias.h" 23 #include "llvm/IR/GlobalIFunc.h" 24 #include "llvm/IR/GlobalObject.h" 25 #include "llvm/IR/GlobalValue.h" 26 #include "llvm/IR/GlobalVariable.h" 27 #include "llvm/IR/Instruction.h" 28 #include "llvm/IR/Instructions.h" 29 #include "llvm/IR/Metadata.h" 30 #include "llvm/IR/Module.h" 31 #include "llvm/IR/Type.h" 32 #include "llvm/IR/Use.h" 33 #include "llvm/IR/User.h" 34 #include "llvm/IR/Value.h" 35 #include "llvm/IR/ValueSymbolTable.h" 36 #include "llvm/Support/Casting.h" 37 #include "llvm/Support/Compiler.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/MathExtras.h" 40 #include "llvm/Support/raw_ostream.h" 41 #include <algorithm> 42 #include <cstddef> 43 #include <iterator> 44 #include <tuple> 45 46 using namespace llvm; 47 48 namespace { 49 50 struct OrderMap { 51 DenseMap<const Value *, std::pair<unsigned, bool>> IDs; 52 unsigned LastGlobalConstantID = 0; 53 unsigned LastGlobalValueID = 0; 54 55 OrderMap() = default; 56 57 bool isGlobalConstant(unsigned ID) const { 58 return ID <= LastGlobalConstantID; 59 } 60 61 bool isGlobalValue(unsigned ID) const { 62 return ID <= LastGlobalValueID && !isGlobalConstant(ID); 63 } 64 65 unsigned size() const { return IDs.size(); } 66 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; } 67 68 std::pair<unsigned, bool> lookup(const Value *V) const { 69 return IDs.lookup(V); 70 } 71 72 void index(const Value *V) { 73 // Explicitly sequence get-size and insert-value operations to avoid UB. 74 unsigned ID = IDs.size() + 1; 75 IDs[V].first = ID; 76 } 77 }; 78 79 } // end anonymous namespace 80 81 static void orderValue(const Value *V, OrderMap &OM) { 82 if (OM.lookup(V).first) 83 return; 84 85 if (const Constant *C = dyn_cast<Constant>(V)) { 86 if (C->getNumOperands() && !isa<GlobalValue>(C)) { 87 for (const Value *Op : C->operands()) 88 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op)) 89 orderValue(Op, OM); 90 if (auto *CE = dyn_cast<ConstantExpr>(C)) 91 if (CE->getOpcode() == Instruction::ShuffleVector) 92 orderValue(CE->getShuffleMaskForBitcode(), OM); 93 } 94 } 95 96 // Note: we cannot cache this lookup above, since inserting into the map 97 // changes the map's size, and thus affects the other IDs. 98 OM.index(V); 99 } 100 101 static OrderMap orderModule(const Module &M) { 102 // This needs to match the order used by ValueEnumerator::ValueEnumerator() 103 // and ValueEnumerator::incorporateFunction(). 104 OrderMap OM; 105 106 // In the reader, initializers of GlobalValues are set *after* all the 107 // globals have been read. Rather than awkwardly modeling this behaviour 108 // directly in predictValueUseListOrderImpl(), just assign IDs to 109 // initializers of GlobalValues before GlobalValues themselves to model this 110 // implicitly. 111 for (const GlobalVariable &G : M.globals()) 112 if (G.hasInitializer()) 113 if (!isa<GlobalValue>(G.getInitializer())) 114 orderValue(G.getInitializer(), OM); 115 for (const GlobalAlias &A : M.aliases()) 116 if (!isa<GlobalValue>(A.getAliasee())) 117 orderValue(A.getAliasee(), OM); 118 for (const GlobalIFunc &I : M.ifuncs()) 119 if (!isa<GlobalValue>(I.getResolver())) 120 orderValue(I.getResolver(), OM); 121 for (const Function &F : M) { 122 for (const Use &U : F.operands()) 123 if (!isa<GlobalValue>(U.get())) 124 orderValue(U.get(), OM); 125 } 126 127 // As constants used in metadata operands are emitted as module-level 128 // constants, we must order them before other operands. Also, we must order 129 // these before global values, as these will be read before setting the 130 // global values' initializers. The latter matters for constants which have 131 // uses towards other constants that are used as initializers. 132 auto orderConstantValue = [&OM](const Value *V) { 133 if ((isa<Constant>(V) && !isa<GlobalValue>(V)) || isa<InlineAsm>(V)) 134 orderValue(V, OM); 135 }; 136 for (const Function &F : M) { 137 if (F.isDeclaration()) 138 continue; 139 for (const BasicBlock &BB : F) 140 for (const Instruction &I : BB) 141 for (const Value *V : I.operands()) { 142 if (const auto *MAV = dyn_cast<MetadataAsValue>(V)) { 143 if (const auto *VAM = 144 dyn_cast<ValueAsMetadata>(MAV->getMetadata())) { 145 orderConstantValue(VAM->getValue()); 146 } else if (const auto *AL = 147 dyn_cast<DIArgList>(MAV->getMetadata())) { 148 for (const auto *VAM : AL->getArgs()) 149 orderConstantValue(VAM->getValue()); 150 } 151 } 152 } 153 } 154 OM.LastGlobalConstantID = OM.size(); 155 156 // Initializers of GlobalValues are processed in 157 // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather 158 // than ValueEnumerator, and match the code in predictValueUseListOrderImpl() 159 // by giving IDs in reverse order. 160 // 161 // Since GlobalValues never reference each other directly (just through 162 // initializers), their relative IDs only matter for determining order of 163 // uses in their initializers. 164 for (const Function &F : M) 165 orderValue(&F, OM); 166 for (const GlobalAlias &A : M.aliases()) 167 orderValue(&A, OM); 168 for (const GlobalIFunc &I : M.ifuncs()) 169 orderValue(&I, OM); 170 for (const GlobalVariable &G : M.globals()) 171 orderValue(&G, OM); 172 OM.LastGlobalValueID = OM.size(); 173 174 for (const Function &F : M) { 175 if (F.isDeclaration()) 176 continue; 177 // Here we need to match the union of ValueEnumerator::incorporateFunction() 178 // and WriteFunction(). Basic blocks are implicitly declared before 179 // anything else (by declaring their size). 180 for (const BasicBlock &BB : F) 181 orderValue(&BB, OM); 182 for (const Argument &A : F.args()) 183 orderValue(&A, OM); 184 for (const BasicBlock &BB : F) 185 for (const Instruction &I : BB) { 186 for (const Value *Op : I.operands()) 187 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) || 188 isa<InlineAsm>(*Op)) 189 orderValue(Op, OM); 190 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 191 orderValue(SVI->getShuffleMaskForBitcode(), OM); 192 } 193 for (const BasicBlock &BB : F) 194 for (const Instruction &I : BB) 195 orderValue(&I, OM); 196 } 197 return OM; 198 } 199 200 static void predictValueUseListOrderImpl(const Value *V, const Function *F, 201 unsigned ID, const OrderMap &OM, 202 UseListOrderStack &Stack) { 203 // Predict use-list order for this one. 204 using Entry = std::pair<const Use *, unsigned>; 205 SmallVector<Entry, 64> List; 206 for (const Use &U : V->uses()) 207 // Check if this user will be serialized. 208 if (OM.lookup(U.getUser()).first) 209 List.push_back(std::make_pair(&U, List.size())); 210 211 if (List.size() < 2) 212 // We may have lost some users. 213 return; 214 215 bool IsGlobalValue = OM.isGlobalValue(ID); 216 llvm::sort(List, [&](const Entry &L, const Entry &R) { 217 const Use *LU = L.first; 218 const Use *RU = R.first; 219 if (LU == RU) 220 return false; 221 222 auto LID = OM.lookup(LU->getUser()).first; 223 auto RID = OM.lookup(RU->getUser()).first; 224 225 // Global values are processed in reverse order. 226 // 227 // Moreover, initializers of GlobalValues are set *after* all the globals 228 // have been read (despite having earlier IDs). Rather than awkwardly 229 // modeling this behaviour here, orderModule() has assigned IDs to 230 // initializers of GlobalValues before GlobalValues themselves. 231 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID)) 232 return LID < RID; 233 234 // If ID is 4, then expect: 7 6 5 1 2 3. 235 if (LID < RID) { 236 if (RID <= ID) 237 if (!IsGlobalValue) // GlobalValue uses don't get reversed. 238 return true; 239 return false; 240 } 241 if (RID < LID) { 242 if (LID <= ID) 243 if (!IsGlobalValue) // GlobalValue uses don't get reversed. 244 return false; 245 return true; 246 } 247 248 // LID and RID are equal, so we have different operands of the same user. 249 // Assume operands are added in order for all instructions. 250 if (LID <= ID) 251 if (!IsGlobalValue) // GlobalValue uses don't get reversed. 252 return LU->getOperandNo() < RU->getOperandNo(); 253 return LU->getOperandNo() > RU->getOperandNo(); 254 }); 255 256 if (llvm::is_sorted(List, [](const Entry &L, const Entry &R) { 257 return L.second < R.second; 258 })) 259 // Order is already correct. 260 return; 261 262 // Store the shuffle. 263 Stack.emplace_back(V, F, List.size()); 264 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size"); 265 for (size_t I = 0, E = List.size(); I != E; ++I) 266 Stack.back().Shuffle[I] = List[I].second; 267 } 268 269 static void predictValueUseListOrder(const Value *V, const Function *F, 270 OrderMap &OM, UseListOrderStack &Stack) { 271 auto &IDPair = OM[V]; 272 assert(IDPair.first && "Unmapped value"); 273 if (IDPair.second) 274 // Already predicted. 275 return; 276 277 // Do the actual prediction. 278 IDPair.second = true; 279 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end()) 280 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack); 281 282 // Recursive descent into constants. 283 if (const Constant *C = dyn_cast<Constant>(V)) { 284 if (C->getNumOperands()) { // Visit GlobalValues. 285 for (const Value *Op : C->operands()) 286 if (isa<Constant>(Op)) // Visit GlobalValues. 287 predictValueUseListOrder(Op, F, OM, Stack); 288 if (auto *CE = dyn_cast<ConstantExpr>(C)) 289 if (CE->getOpcode() == Instruction::ShuffleVector) 290 predictValueUseListOrder(CE->getShuffleMaskForBitcode(), F, OM, 291 Stack); 292 } 293 } 294 } 295 296 static UseListOrderStack predictUseListOrder(const Module &M) { 297 OrderMap OM = orderModule(M); 298 299 // Use-list orders need to be serialized after all the users have been added 300 // to a value, or else the shuffles will be incomplete. Store them per 301 // function in a stack. 302 // 303 // Aside from function order, the order of values doesn't matter much here. 304 UseListOrderStack Stack; 305 306 // We want to visit the functions backward now so we can list function-local 307 // constants in the last Function they're used in. Module-level constants 308 // have already been visited above. 309 for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) { 310 const Function &F = *I; 311 if (F.isDeclaration()) 312 continue; 313 for (const BasicBlock &BB : F) 314 predictValueUseListOrder(&BB, &F, OM, Stack); 315 for (const Argument &A : F.args()) 316 predictValueUseListOrder(&A, &F, OM, Stack); 317 for (const BasicBlock &BB : F) 318 for (const Instruction &I : BB) { 319 for (const Value *Op : I.operands()) 320 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues. 321 predictValueUseListOrder(Op, &F, OM, Stack); 322 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 323 predictValueUseListOrder(SVI->getShuffleMaskForBitcode(), &F, OM, 324 Stack); 325 } 326 for (const BasicBlock &BB : F) 327 for (const Instruction &I : BB) 328 predictValueUseListOrder(&I, &F, OM, Stack); 329 } 330 331 // Visit globals last, since the module-level use-list block will be seen 332 // before the function bodies are processed. 333 for (const GlobalVariable &G : M.globals()) 334 predictValueUseListOrder(&G, nullptr, OM, Stack); 335 for (const Function &F : M) 336 predictValueUseListOrder(&F, nullptr, OM, Stack); 337 for (const GlobalAlias &A : M.aliases()) 338 predictValueUseListOrder(&A, nullptr, OM, Stack); 339 for (const GlobalIFunc &I : M.ifuncs()) 340 predictValueUseListOrder(&I, nullptr, OM, Stack); 341 for (const GlobalVariable &G : M.globals()) 342 if (G.hasInitializer()) 343 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack); 344 for (const GlobalAlias &A : M.aliases()) 345 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack); 346 for (const GlobalIFunc &I : M.ifuncs()) 347 predictValueUseListOrder(I.getResolver(), nullptr, OM, Stack); 348 for (const Function &F : M) { 349 for (const Use &U : F.operands()) 350 predictValueUseListOrder(U.get(), nullptr, OM, Stack); 351 } 352 353 return Stack; 354 } 355 356 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) { 357 return V.first->getType()->isIntOrIntVectorTy(); 358 } 359 360 ValueEnumerator::ValueEnumerator(const Module &M, 361 bool ShouldPreserveUseListOrder) 362 : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) { 363 if (ShouldPreserveUseListOrder) 364 UseListOrders = predictUseListOrder(M); 365 366 // Enumerate the global variables. 367 for (const GlobalVariable &GV : M.globals()) 368 EnumerateValue(&GV); 369 370 // Enumerate the functions. 371 for (const Function & F : M) { 372 EnumerateValue(&F); 373 EnumerateAttributes(F.getAttributes()); 374 } 375 376 // Enumerate the aliases. 377 for (const GlobalAlias &GA : M.aliases()) 378 EnumerateValue(&GA); 379 380 // Enumerate the ifuncs. 381 for (const GlobalIFunc &GIF : M.ifuncs()) 382 EnumerateValue(&GIF); 383 384 // Remember what is the cutoff between globalvalue's and other constants. 385 unsigned FirstConstant = Values.size(); 386 387 // Enumerate the global variable initializers and attributes. 388 for (const GlobalVariable &GV : M.globals()) { 389 if (GV.hasInitializer()) 390 EnumerateValue(GV.getInitializer()); 391 if (GV.hasAttributes()) 392 EnumerateAttributes(GV.getAttributesAsList(AttributeList::FunctionIndex)); 393 } 394 395 // Enumerate the aliasees. 396 for (const GlobalAlias &GA : M.aliases()) 397 EnumerateValue(GA.getAliasee()); 398 399 // Enumerate the ifunc resolvers. 400 for (const GlobalIFunc &GIF : M.ifuncs()) 401 EnumerateValue(GIF.getResolver()); 402 403 // Enumerate any optional Function data. 404 for (const Function &F : M) 405 for (const Use &U : F.operands()) 406 EnumerateValue(U.get()); 407 408 // Enumerate the metadata type. 409 // 410 // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode 411 // only encodes the metadata type when it's used as a value. 412 EnumerateType(Type::getMetadataTy(M.getContext())); 413 414 // Insert constants and metadata that are named at module level into the slot 415 // pool so that the module symbol table can refer to them... 416 EnumerateValueSymbolTable(M.getValueSymbolTable()); 417 EnumerateNamedMetadata(M); 418 419 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs; 420 for (const GlobalVariable &GV : M.globals()) { 421 MDs.clear(); 422 GV.getAllMetadata(MDs); 423 for (const auto &I : MDs) 424 // FIXME: Pass GV to EnumerateMetadata and arrange for the bitcode writer 425 // to write metadata to the global variable's own metadata block 426 // (PR28134). 427 EnumerateMetadata(nullptr, I.second); 428 } 429 430 // Enumerate types used by function bodies and argument lists. 431 for (const Function &F : M) { 432 for (const Argument &A : F.args()) 433 EnumerateType(A.getType()); 434 435 // Enumerate metadata attached to this function. 436 MDs.clear(); 437 F.getAllMetadata(MDs); 438 for (const auto &I : MDs) 439 EnumerateMetadata(F.isDeclaration() ? nullptr : &F, I.second); 440 441 for (const BasicBlock &BB : F) 442 for (const Instruction &I : BB) { 443 for (const Use &Op : I.operands()) { 444 auto *MD = dyn_cast<MetadataAsValue>(&Op); 445 if (!MD) { 446 EnumerateOperandType(Op); 447 continue; 448 } 449 450 // Local metadata is enumerated during function-incorporation, but 451 // any ConstantAsMetadata arguments in a DIArgList should be examined 452 // now. 453 if (isa<LocalAsMetadata>(MD->getMetadata())) 454 continue; 455 if (auto *AL = dyn_cast<DIArgList>(MD->getMetadata())) { 456 for (auto *VAM : AL->getArgs()) 457 if (isa<ConstantAsMetadata>(VAM)) 458 EnumerateMetadata(&F, VAM); 459 continue; 460 } 461 462 EnumerateMetadata(&F, MD->getMetadata()); 463 } 464 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 465 EnumerateType(SVI->getShuffleMaskForBitcode()->getType()); 466 if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) 467 EnumerateType(GEP->getSourceElementType()); 468 EnumerateType(I.getType()); 469 if (const auto *Call = dyn_cast<CallBase>(&I)) 470 EnumerateAttributes(Call->getAttributes()); 471 472 // Enumerate metadata attached with this instruction. 473 MDs.clear(); 474 I.getAllMetadataOtherThanDebugLoc(MDs); 475 for (unsigned i = 0, e = MDs.size(); i != e; ++i) 476 EnumerateMetadata(&F, MDs[i].second); 477 478 // Don't enumerate the location directly -- it has a special record 479 // type -- but enumerate its operands. 480 if (DILocation *L = I.getDebugLoc()) 481 for (const Metadata *Op : L->operands()) 482 EnumerateMetadata(&F, Op); 483 } 484 } 485 486 // Optimize constant ordering. 487 OptimizeConstants(FirstConstant, Values.size()); 488 489 // Organize metadata ordering. 490 organizeMetadata(); 491 } 492 493 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const { 494 InstructionMapType::const_iterator I = InstructionMap.find(Inst); 495 assert(I != InstructionMap.end() && "Instruction is not mapped!"); 496 return I->second; 497 } 498 499 unsigned ValueEnumerator::getComdatID(const Comdat *C) const { 500 unsigned ComdatID = Comdats.idFor(C); 501 assert(ComdatID && "Comdat not found!"); 502 return ComdatID; 503 } 504 505 void ValueEnumerator::setInstructionID(const Instruction *I) { 506 InstructionMap[I] = InstructionCount++; 507 } 508 509 unsigned ValueEnumerator::getValueID(const Value *V) const { 510 if (auto *MD = dyn_cast<MetadataAsValue>(V)) 511 return getMetadataID(MD->getMetadata()); 512 513 ValueMapType::const_iterator I = ValueMap.find(V); 514 assert(I != ValueMap.end() && "Value not in slotcalculator!"); 515 return I->second-1; 516 } 517 518 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 519 LLVM_DUMP_METHOD void ValueEnumerator::dump() const { 520 print(dbgs(), ValueMap, "Default"); 521 dbgs() << '\n'; 522 print(dbgs(), MetadataMap, "MetaData"); 523 dbgs() << '\n'; 524 } 525 #endif 526 527 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map, 528 const char *Name) const { 529 OS << "Map Name: " << Name << "\n"; 530 OS << "Size: " << Map.size() << "\n"; 531 for (ValueMapType::const_iterator I = Map.begin(), 532 E = Map.end(); I != E; ++I) { 533 const Value *V = I->first; 534 if (V->hasName()) 535 OS << "Value: " << V->getName(); 536 else 537 OS << "Value: [null]\n"; 538 V->print(errs()); 539 errs() << '\n'; 540 541 OS << " Uses(" << V->getNumUses() << "):"; 542 for (const Use &U : V->uses()) { 543 if (&U != &*V->use_begin()) 544 OS << ","; 545 if(U->hasName()) 546 OS << " " << U->getName(); 547 else 548 OS << " [null]"; 549 550 } 551 OS << "\n\n"; 552 } 553 } 554 555 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map, 556 const char *Name) const { 557 OS << "Map Name: " << Name << "\n"; 558 OS << "Size: " << Map.size() << "\n"; 559 for (auto I = Map.begin(), E = Map.end(); I != E; ++I) { 560 const Metadata *MD = I->first; 561 OS << "Metadata: slot = " << I->second.ID << "\n"; 562 OS << "Metadata: function = " << I->second.F << "\n"; 563 MD->print(OS); 564 OS << "\n"; 565 } 566 } 567 568 /// OptimizeConstants - Reorder constant pool for denser encoding. 569 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) { 570 if (CstStart == CstEnd || CstStart+1 == CstEnd) return; 571 572 if (ShouldPreserveUseListOrder) 573 // Optimizing constants makes the use-list order difficult to predict. 574 // Disable it for now when trying to preserve the order. 575 return; 576 577 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd, 578 [this](const std::pair<const Value *, unsigned> &LHS, 579 const std::pair<const Value *, unsigned> &RHS) { 580 // Sort by plane. 581 if (LHS.first->getType() != RHS.first->getType()) 582 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType()); 583 // Then by frequency. 584 return LHS.second > RHS.second; 585 }); 586 587 // Ensure that integer and vector of integer constants are at the start of the 588 // constant pool. This is important so that GEP structure indices come before 589 // gep constant exprs. 590 std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd, 591 isIntOrIntVectorValue); 592 593 // Rebuild the modified portion of ValueMap. 594 for (; CstStart != CstEnd; ++CstStart) 595 ValueMap[Values[CstStart].first] = CstStart+1; 596 } 597 598 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol 599 /// table into the values table. 600 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) { 601 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); 602 VI != VE; ++VI) 603 EnumerateValue(VI->getValue()); 604 } 605 606 /// Insert all of the values referenced by named metadata in the specified 607 /// module. 608 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) { 609 for (const auto &I : M.named_metadata()) 610 EnumerateNamedMDNode(&I); 611 } 612 613 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) { 614 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i) 615 EnumerateMetadata(nullptr, MD->getOperand(i)); 616 } 617 618 unsigned ValueEnumerator::getMetadataFunctionID(const Function *F) const { 619 return F ? getValueID(F) + 1 : 0; 620 } 621 622 void ValueEnumerator::EnumerateMetadata(const Function *F, const Metadata *MD) { 623 EnumerateMetadata(getMetadataFunctionID(F), MD); 624 } 625 626 void ValueEnumerator::EnumerateFunctionLocalMetadata( 627 const Function &F, const LocalAsMetadata *Local) { 628 EnumerateFunctionLocalMetadata(getMetadataFunctionID(&F), Local); 629 } 630 631 void ValueEnumerator::EnumerateFunctionLocalListMetadata( 632 const Function &F, const DIArgList *ArgList) { 633 EnumerateFunctionLocalListMetadata(getMetadataFunctionID(&F), ArgList); 634 } 635 636 void ValueEnumerator::dropFunctionFromMetadata( 637 MetadataMapType::value_type &FirstMD) { 638 SmallVector<const MDNode *, 64> Worklist; 639 auto push = [&Worklist](MetadataMapType::value_type &MD) { 640 auto &Entry = MD.second; 641 642 // Nothing to do if this metadata isn't tagged. 643 if (!Entry.F) 644 return; 645 646 // Drop the function tag. 647 Entry.F = 0; 648 649 // If this is has an ID and is an MDNode, then its operands have entries as 650 // well. We need to drop the function from them too. 651 if (Entry.ID) 652 if (auto *N = dyn_cast<MDNode>(MD.first)) 653 Worklist.push_back(N); 654 }; 655 push(FirstMD); 656 while (!Worklist.empty()) 657 for (const Metadata *Op : Worklist.pop_back_val()->operands()) { 658 if (!Op) 659 continue; 660 auto MD = MetadataMap.find(Op); 661 if (MD != MetadataMap.end()) 662 push(*MD); 663 } 664 } 665 666 void ValueEnumerator::EnumerateMetadata(unsigned F, const Metadata *MD) { 667 // It's vital for reader efficiency that uniqued subgraphs are done in 668 // post-order; it's expensive when their operands have forward references. 669 // If a distinct node is referenced from a uniqued node, it'll be delayed 670 // until the uniqued subgraph has been completely traversed. 671 SmallVector<const MDNode *, 32> DelayedDistinctNodes; 672 673 // Start by enumerating MD, and then work through its transitive operands in 674 // post-order. This requires a depth-first search. 675 SmallVector<std::pair<const MDNode *, MDNode::op_iterator>, 32> Worklist; 676 if (const MDNode *N = enumerateMetadataImpl(F, MD)) 677 Worklist.push_back(std::make_pair(N, N->op_begin())); 678 679 while (!Worklist.empty()) { 680 const MDNode *N = Worklist.back().first; 681 682 // Enumerate operands until we hit a new node. We need to traverse these 683 // nodes' operands before visiting the rest of N's operands. 684 MDNode::op_iterator I = std::find_if( 685 Worklist.back().second, N->op_end(), 686 [&](const Metadata *MD) { return enumerateMetadataImpl(F, MD); }); 687 if (I != N->op_end()) { 688 auto *Op = cast<MDNode>(*I); 689 Worklist.back().second = ++I; 690 691 // Delay traversing Op if it's a distinct node and N is uniqued. 692 if (Op->isDistinct() && !N->isDistinct()) 693 DelayedDistinctNodes.push_back(Op); 694 else 695 Worklist.push_back(std::make_pair(Op, Op->op_begin())); 696 continue; 697 } 698 699 // All the operands have been visited. Now assign an ID. 700 Worklist.pop_back(); 701 MDs.push_back(N); 702 MetadataMap[N].ID = MDs.size(); 703 704 // Flush out any delayed distinct nodes; these are all the distinct nodes 705 // that are leaves in last uniqued subgraph. 706 if (Worklist.empty() || Worklist.back().first->isDistinct()) { 707 for (const MDNode *N : DelayedDistinctNodes) 708 Worklist.push_back(std::make_pair(N, N->op_begin())); 709 DelayedDistinctNodes.clear(); 710 } 711 } 712 } 713 714 const MDNode *ValueEnumerator::enumerateMetadataImpl(unsigned F, const Metadata *MD) { 715 if (!MD) 716 return nullptr; 717 718 assert( 719 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) && 720 "Invalid metadata kind"); 721 722 auto Insertion = MetadataMap.insert(std::make_pair(MD, MDIndex(F))); 723 MDIndex &Entry = Insertion.first->second; 724 if (!Insertion.second) { 725 // Already mapped. If F doesn't match the function tag, drop it. 726 if (Entry.hasDifferentFunction(F)) 727 dropFunctionFromMetadata(*Insertion.first); 728 return nullptr; 729 } 730 731 // Don't assign IDs to metadata nodes. 732 if (auto *N = dyn_cast<MDNode>(MD)) 733 return N; 734 735 // Save the metadata. 736 MDs.push_back(MD); 737 Entry.ID = MDs.size(); 738 739 // Enumerate the constant, if any. 740 if (auto *C = dyn_cast<ConstantAsMetadata>(MD)) 741 EnumerateValue(C->getValue()); 742 743 return nullptr; 744 } 745 746 /// EnumerateFunctionLocalMetadata - Incorporate function-local metadata 747 /// information reachable from the metadata. 748 void ValueEnumerator::EnumerateFunctionLocalMetadata( 749 unsigned F, const LocalAsMetadata *Local) { 750 assert(F && "Expected a function"); 751 752 // Check to see if it's already in! 753 MDIndex &Index = MetadataMap[Local]; 754 if (Index.ID) { 755 assert(Index.F == F && "Expected the same function"); 756 return; 757 } 758 759 MDs.push_back(Local); 760 Index.F = F; 761 Index.ID = MDs.size(); 762 763 EnumerateValue(Local->getValue()); 764 } 765 766 /// EnumerateFunctionLocalListMetadata - Incorporate function-local metadata 767 /// information reachable from the metadata. 768 void ValueEnumerator::EnumerateFunctionLocalListMetadata( 769 unsigned F, const DIArgList *ArgList) { 770 assert(F && "Expected a function"); 771 772 // Check to see if it's already in! 773 MDIndex &Index = MetadataMap[ArgList]; 774 if (Index.ID) { 775 assert(Index.F == F && "Expected the same function"); 776 return; 777 } 778 779 for (ValueAsMetadata *VAM : ArgList->getArgs()) { 780 if (isa<LocalAsMetadata>(VAM)) { 781 assert(MetadataMap.count(VAM) && 782 "LocalAsMetadata should be enumerated before DIArgList"); 783 assert(MetadataMap[VAM].F == F && 784 "Expected LocalAsMetadata in the same function"); 785 } else { 786 assert(isa<ConstantAsMetadata>(VAM) && 787 "Expected LocalAsMetadata or ConstantAsMetadata"); 788 assert(ValueMap.count(VAM->getValue()) && 789 "Constant should be enumerated beforeDIArgList"); 790 EnumerateMetadata(F, VAM); 791 } 792 } 793 794 MDs.push_back(ArgList); 795 Index.F = F; 796 Index.ID = MDs.size(); 797 } 798 799 static unsigned getMetadataTypeOrder(const Metadata *MD) { 800 // Strings are emitted in bulk and must come first. 801 if (isa<MDString>(MD)) 802 return 0; 803 804 // ConstantAsMetadata doesn't reference anything. We may as well shuffle it 805 // to the front since we can detect it. 806 auto *N = dyn_cast<MDNode>(MD); 807 if (!N) 808 return 1; 809 810 // The reader is fast forward references for distinct node operands, but slow 811 // when uniqued operands are unresolved. 812 return N->isDistinct() ? 2 : 3; 813 } 814 815 void ValueEnumerator::organizeMetadata() { 816 assert(MetadataMap.size() == MDs.size() && 817 "Metadata map and vector out of sync"); 818 819 if (MDs.empty()) 820 return; 821 822 // Copy out the index information from MetadataMap in order to choose a new 823 // order. 824 SmallVector<MDIndex, 64> Order; 825 Order.reserve(MetadataMap.size()); 826 for (const Metadata *MD : MDs) 827 Order.push_back(MetadataMap.lookup(MD)); 828 829 // Partition: 830 // - by function, then 831 // - by isa<MDString> 832 // and then sort by the original/current ID. Since the IDs are guaranteed to 833 // be unique, the result of std::sort will be deterministic. There's no need 834 // for std::stable_sort. 835 llvm::sort(Order, [this](MDIndex LHS, MDIndex RHS) { 836 return std::make_tuple(LHS.F, getMetadataTypeOrder(LHS.get(MDs)), LHS.ID) < 837 std::make_tuple(RHS.F, getMetadataTypeOrder(RHS.get(MDs)), RHS.ID); 838 }); 839 840 // Rebuild MDs, index the metadata ranges for each function in FunctionMDs, 841 // and fix up MetadataMap. 842 std::vector<const Metadata *> OldMDs; 843 MDs.swap(OldMDs); 844 MDs.reserve(OldMDs.size()); 845 for (unsigned I = 0, E = Order.size(); I != E && !Order[I].F; ++I) { 846 auto *MD = Order[I].get(OldMDs); 847 MDs.push_back(MD); 848 MetadataMap[MD].ID = I + 1; 849 if (isa<MDString>(MD)) 850 ++NumMDStrings; 851 } 852 853 // Return early if there's nothing for the functions. 854 if (MDs.size() == Order.size()) 855 return; 856 857 // Build the function metadata ranges. 858 MDRange R; 859 FunctionMDs.reserve(OldMDs.size()); 860 unsigned PrevF = 0; 861 for (unsigned I = MDs.size(), E = Order.size(), ID = MDs.size(); I != E; 862 ++I) { 863 unsigned F = Order[I].F; 864 if (!PrevF) { 865 PrevF = F; 866 } else if (PrevF != F) { 867 R.Last = FunctionMDs.size(); 868 std::swap(R, FunctionMDInfo[PrevF]); 869 R.First = FunctionMDs.size(); 870 871 ID = MDs.size(); 872 PrevF = F; 873 } 874 875 auto *MD = Order[I].get(OldMDs); 876 FunctionMDs.push_back(MD); 877 MetadataMap[MD].ID = ++ID; 878 if (isa<MDString>(MD)) 879 ++R.NumStrings; 880 } 881 R.Last = FunctionMDs.size(); 882 FunctionMDInfo[PrevF] = R; 883 } 884 885 void ValueEnumerator::incorporateFunctionMetadata(const Function &F) { 886 NumModuleMDs = MDs.size(); 887 888 auto R = FunctionMDInfo.lookup(getValueID(&F) + 1); 889 NumMDStrings = R.NumStrings; 890 MDs.insert(MDs.end(), FunctionMDs.begin() + R.First, 891 FunctionMDs.begin() + R.Last); 892 } 893 894 void ValueEnumerator::EnumerateValue(const Value *V) { 895 assert(!V->getType()->isVoidTy() && "Can't insert void values!"); 896 assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!"); 897 898 // Check to see if it's already in! 899 unsigned &ValueID = ValueMap[V]; 900 if (ValueID) { 901 // Increment use count. 902 Values[ValueID-1].second++; 903 return; 904 } 905 906 if (auto *GO = dyn_cast<GlobalObject>(V)) 907 if (const Comdat *C = GO->getComdat()) 908 Comdats.insert(C); 909 910 // Enumerate the type of this value. 911 EnumerateType(V->getType()); 912 913 if (const Constant *C = dyn_cast<Constant>(V)) { 914 if (isa<GlobalValue>(C)) { 915 // Initializers for globals are handled explicitly elsewhere. 916 } else if (C->getNumOperands()) { 917 // If a constant has operands, enumerate them. This makes sure that if a 918 // constant has uses (for example an array of const ints), that they are 919 // inserted also. 920 921 // We prefer to enumerate them with values before we enumerate the user 922 // itself. This makes it more likely that we can avoid forward references 923 // in the reader. We know that there can be no cycles in the constants 924 // graph that don't go through a global variable. 925 for (User::const_op_iterator I = C->op_begin(), E = C->op_end(); 926 I != E; ++I) 927 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress. 928 EnumerateValue(*I); 929 if (auto *CE = dyn_cast<ConstantExpr>(C)) 930 if (CE->getOpcode() == Instruction::ShuffleVector) 931 EnumerateValue(CE->getShuffleMaskForBitcode()); 932 933 // Finally, add the value. Doing this could make the ValueID reference be 934 // dangling, don't reuse it. 935 Values.push_back(std::make_pair(V, 1U)); 936 ValueMap[V] = Values.size(); 937 return; 938 } 939 } 940 941 // Add the value. 942 Values.push_back(std::make_pair(V, 1U)); 943 ValueID = Values.size(); 944 } 945 946 947 void ValueEnumerator::EnumerateType(Type *Ty) { 948 unsigned *TypeID = &TypeMap[Ty]; 949 950 // We've already seen this type. 951 if (*TypeID) 952 return; 953 954 // If it is a non-anonymous struct, mark the type as being visited so that we 955 // don't recursively visit it. This is safe because we allow forward 956 // references of these in the bitcode reader. 957 if (StructType *STy = dyn_cast<StructType>(Ty)) 958 if (!STy->isLiteral()) 959 *TypeID = ~0U; 960 961 // Enumerate all of the subtypes before we enumerate this type. This ensures 962 // that the type will be enumerated in an order that can be directly built. 963 for (Type *SubTy : Ty->subtypes()) 964 EnumerateType(SubTy); 965 966 // Refresh the TypeID pointer in case the table rehashed. 967 TypeID = &TypeMap[Ty]; 968 969 // Check to see if we got the pointer another way. This can happen when 970 // enumerating recursive types that hit the base case deeper than they start. 971 // 972 // If this is actually a struct that we are treating as forward ref'able, 973 // then emit the definition now that all of its contents are available. 974 if (*TypeID && *TypeID != ~0U) 975 return; 976 977 // Add this type now that its contents are all happily enumerated. 978 Types.push_back(Ty); 979 980 *TypeID = Types.size(); 981 } 982 983 // Enumerate the types for the specified value. If the value is a constant, 984 // walk through it, enumerating the types of the constant. 985 void ValueEnumerator::EnumerateOperandType(const Value *V) { 986 EnumerateType(V->getType()); 987 988 assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand"); 989 990 const Constant *C = dyn_cast<Constant>(V); 991 if (!C) 992 return; 993 994 // If this constant is already enumerated, ignore it, we know its type must 995 // be enumerated. 996 if (ValueMap.count(C)) 997 return; 998 999 // This constant may have operands, make sure to enumerate the types in 1000 // them. 1001 for (const Value *Op : C->operands()) { 1002 // Don't enumerate basic blocks here, this happens as operands to 1003 // blockaddress. 1004 if (isa<BasicBlock>(Op)) 1005 continue; 1006 1007 EnumerateOperandType(Op); 1008 } 1009 if (auto *CE = dyn_cast<ConstantExpr>(C)) 1010 if (CE->getOpcode() == Instruction::ShuffleVector) 1011 EnumerateOperandType(CE->getShuffleMaskForBitcode()); 1012 } 1013 1014 void ValueEnumerator::EnumerateAttributes(AttributeList PAL) { 1015 if (PAL.isEmpty()) return; // null is always 0. 1016 1017 // Do a lookup. 1018 unsigned &Entry = AttributeListMap[PAL]; 1019 if (Entry == 0) { 1020 // Never saw this before, add it. 1021 AttributeLists.push_back(PAL); 1022 Entry = AttributeLists.size(); 1023 } 1024 1025 // Do lookups for all attribute groups. 1026 for (unsigned i = PAL.index_begin(), e = PAL.index_end(); i != e; ++i) { 1027 AttributeSet AS = PAL.getAttributes(i); 1028 if (!AS.hasAttributes()) 1029 continue; 1030 IndexAndAttrSet Pair = {i, AS}; 1031 unsigned &Entry = AttributeGroupMap[Pair]; 1032 if (Entry == 0) { 1033 AttributeGroups.push_back(Pair); 1034 Entry = AttributeGroups.size(); 1035 } 1036 } 1037 } 1038 1039 void ValueEnumerator::incorporateFunction(const Function &F) { 1040 InstructionCount = 0; 1041 NumModuleValues = Values.size(); 1042 1043 // Add global metadata to the function block. This doesn't include 1044 // LocalAsMetadata. 1045 incorporateFunctionMetadata(F); 1046 1047 // Adding function arguments to the value table. 1048 for (const auto &I : F.args()) { 1049 EnumerateValue(&I); 1050 if (I.hasAttribute(Attribute::ByVal)) 1051 EnumerateType(I.getParamByValType()); 1052 else if (I.hasAttribute(Attribute::StructRet)) 1053 EnumerateType(I.getParamStructRetType()); 1054 else if (I.hasAttribute(Attribute::ByRef)) 1055 EnumerateType(I.getParamByRefType()); 1056 } 1057 FirstFuncConstantID = Values.size(); 1058 1059 // Add all function-level constants to the value table. 1060 for (const BasicBlock &BB : F) { 1061 for (const Instruction &I : BB) { 1062 for (const Use &OI : I.operands()) { 1063 if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI)) 1064 EnumerateValue(OI); 1065 } 1066 if (auto *SVI = dyn_cast<ShuffleVectorInst>(&I)) 1067 EnumerateValue(SVI->getShuffleMaskForBitcode()); 1068 } 1069 BasicBlocks.push_back(&BB); 1070 ValueMap[&BB] = BasicBlocks.size(); 1071 } 1072 1073 // Optimize the constant layout. 1074 OptimizeConstants(FirstFuncConstantID, Values.size()); 1075 1076 // Add the function's parameter attributes so they are available for use in 1077 // the function's instruction. 1078 EnumerateAttributes(F.getAttributes()); 1079 1080 FirstInstID = Values.size(); 1081 1082 SmallVector<LocalAsMetadata *, 8> FnLocalMDVector; 1083 SmallVector<DIArgList *, 8> ArgListMDVector; 1084 // Add all of the instructions. 1085 for (const BasicBlock &BB : F) { 1086 for (const Instruction &I : BB) { 1087 for (const Use &OI : I.operands()) { 1088 if (auto *MD = dyn_cast<MetadataAsValue>(&OI)) { 1089 if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata())) { 1090 // Enumerate metadata after the instructions they might refer to. 1091 FnLocalMDVector.push_back(Local); 1092 } else if (auto *ArgList = dyn_cast<DIArgList>(MD->getMetadata())) { 1093 ArgListMDVector.push_back(ArgList); 1094 for (ValueAsMetadata *VMD : ArgList->getArgs()) { 1095 if (auto *Local = dyn_cast<LocalAsMetadata>(VMD)) { 1096 // Enumerate metadata after the instructions they might refer 1097 // to. 1098 FnLocalMDVector.push_back(Local); 1099 } 1100 } 1101 } 1102 } 1103 } 1104 1105 if (!I.getType()->isVoidTy()) 1106 EnumerateValue(&I); 1107 } 1108 } 1109 1110 // Add all of the function-local metadata. 1111 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i) { 1112 // At this point, every local values have been incorporated, we shouldn't 1113 // have a metadata operand that references a value that hasn't been seen. 1114 assert(ValueMap.count(FnLocalMDVector[i]->getValue()) && 1115 "Missing value for metadata operand"); 1116 EnumerateFunctionLocalMetadata(F, FnLocalMDVector[i]); 1117 } 1118 // DIArgList entries must come after function-local metadata, as it is not 1119 // possible to forward-reference them. 1120 for (const DIArgList *ArgList : ArgListMDVector) 1121 EnumerateFunctionLocalListMetadata(F, ArgList); 1122 } 1123 1124 void ValueEnumerator::purgeFunction() { 1125 /// Remove purged values from the ValueMap. 1126 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i) 1127 ValueMap.erase(Values[i].first); 1128 for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i) 1129 MetadataMap.erase(MDs[i]); 1130 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i) 1131 ValueMap.erase(BasicBlocks[i]); 1132 1133 Values.resize(NumModuleValues); 1134 MDs.resize(NumModuleMDs); 1135 BasicBlocks.clear(); 1136 NumMDStrings = 0; 1137 } 1138 1139 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F, 1140 DenseMap<const BasicBlock*, unsigned> &IDMap) { 1141 unsigned Counter = 0; 1142 for (const BasicBlock &BB : *F) 1143 IDMap[&BB] = ++Counter; 1144 } 1145 1146 /// getGlobalBasicBlockID - This returns the function-specific ID for the 1147 /// specified basic block. This is relatively expensive information, so it 1148 /// should only be used by rare constructs such as address-of-label. 1149 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const { 1150 unsigned &Idx = GlobalBasicBlockIDs[BB]; 1151 if (Idx != 0) 1152 return Idx-1; 1153 1154 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs); 1155 return getGlobalBasicBlockID(BB); 1156 } 1157 1158 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const { 1159 return Log2_32_Ceil(getTypes().size() + 1); 1160 } 1161