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