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