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 Function &F : M) {
90     for (const Use &U : F.operands())
91       if (!isa<GlobalValue>(U.get()))
92         orderValue(U.get(), OM);
93   }
94   OM.LastGlobalConstantID = OM.size();
95 
96   // Initializers of GlobalValues are processed in
97   // BitcodeReader::ResolveGlobalAndAliasInits().  Match the order there rather
98   // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
99   // by giving IDs in reverse order.
100   //
101   // Since GlobalValues never reference each other directly (just through
102   // initializers), their relative IDs only matter for determining order of
103   // uses in their initializers.
104   for (const Function &F : M)
105     orderValue(&F, OM);
106   for (const GlobalAlias &A : M.aliases())
107     orderValue(&A, OM);
108   for (const GlobalVariable &G : M.globals())
109     orderValue(&G, OM);
110   OM.LastGlobalValueID = OM.size();
111 
112   for (const Function &F : M) {
113     if (F.isDeclaration())
114       continue;
115     // Here we need to match the union of ValueEnumerator::incorporateFunction()
116     // and WriteFunction().  Basic blocks are implicitly declared before
117     // anything else (by declaring their size).
118     for (const BasicBlock &BB : F)
119       orderValue(&BB, OM);
120     for (const Argument &A : F.args())
121       orderValue(&A, OM);
122     for (const BasicBlock &BB : F)
123       for (const Instruction &I : BB)
124         for (const Value *Op : I.operands())
125           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
126               isa<InlineAsm>(*Op))
127             orderValue(Op, OM);
128     for (const BasicBlock &BB : F)
129       for (const Instruction &I : BB)
130         orderValue(&I, OM);
131   }
132   return OM;
133 }
134 
135 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
136                                          unsigned ID, const OrderMap &OM,
137                                          UseListOrderStack &Stack) {
138   // Predict use-list order for this one.
139   typedef std::pair<const Use *, unsigned> Entry;
140   SmallVector<Entry, 64> List;
141   for (const Use &U : V->uses())
142     // Check if this user will be serialized.
143     if (OM.lookup(U.getUser()).first)
144       List.push_back(std::make_pair(&U, List.size()));
145 
146   if (List.size() < 2)
147     // We may have lost some users.
148     return;
149 
150   bool IsGlobalValue = OM.isGlobalValue(ID);
151   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
152     const Use *LU = L.first;
153     const Use *RU = R.first;
154     if (LU == RU)
155       return false;
156 
157     auto LID = OM.lookup(LU->getUser()).first;
158     auto RID = OM.lookup(RU->getUser()).first;
159 
160     // Global values are processed in reverse order.
161     //
162     // Moreover, initializers of GlobalValues are set *after* all the globals
163     // have been read (despite having earlier IDs).  Rather than awkwardly
164     // modeling this behaviour here, orderModule() has assigned IDs to
165     // initializers of GlobalValues before GlobalValues themselves.
166     if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
167       return LID < RID;
168 
169     // If ID is 4, then expect: 7 6 5 1 2 3.
170     if (LID < RID) {
171       if (RID <= ID)
172         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
173           return true;
174       return false;
175     }
176     if (RID < LID) {
177       if (LID <= ID)
178         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
179           return false;
180       return true;
181     }
182 
183     // LID and RID are equal, so we have different operands of the same user.
184     // Assume operands are added in order for all instructions.
185     if (LID <= ID)
186       if (!IsGlobalValue) // GlobalValue uses don't get reversed.
187         return LU->getOperandNo() < RU->getOperandNo();
188     return LU->getOperandNo() > RU->getOperandNo();
189   });
190 
191   if (std::is_sorted(
192           List.begin(), List.end(),
193           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
194     // Order is already correct.
195     return;
196 
197   // Store the shuffle.
198   Stack.emplace_back(V, F, List.size());
199   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
200   for (size_t I = 0, E = List.size(); I != E; ++I)
201     Stack.back().Shuffle[I] = List[I].second;
202 }
203 
204 static void predictValueUseListOrder(const Value *V, const Function *F,
205                                      OrderMap &OM, UseListOrderStack &Stack) {
206   auto &IDPair = OM[V];
207   assert(IDPair.first && "Unmapped value");
208   if (IDPair.second)
209     // Already predicted.
210     return;
211 
212   // Do the actual prediction.
213   IDPair.second = true;
214   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
215     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
216 
217   // Recursive descent into constants.
218   if (const Constant *C = dyn_cast<Constant>(V))
219     if (C->getNumOperands()) // Visit GlobalValues.
220       for (const Value *Op : C->operands())
221         if (isa<Constant>(Op)) // Visit GlobalValues.
222           predictValueUseListOrder(Op, F, OM, Stack);
223 }
224 
225 static UseListOrderStack predictUseListOrder(const Module &M) {
226   OrderMap OM = orderModule(M);
227 
228   // Use-list orders need to be serialized after all the users have been added
229   // to a value, or else the shuffles will be incomplete.  Store them per
230   // function in a stack.
231   //
232   // Aside from function order, the order of values doesn't matter much here.
233   UseListOrderStack Stack;
234 
235   // We want to visit the functions backward now so we can list function-local
236   // constants in the last Function they're used in.  Module-level constants
237   // have already been visited above.
238   for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
239     const Function &F = *I;
240     if (F.isDeclaration())
241       continue;
242     for (const BasicBlock &BB : F)
243       predictValueUseListOrder(&BB, &F, OM, Stack);
244     for (const Argument &A : F.args())
245       predictValueUseListOrder(&A, &F, OM, Stack);
246     for (const BasicBlock &BB : F)
247       for (const Instruction &I : BB)
248         for (const Value *Op : I.operands())
249           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
250             predictValueUseListOrder(Op, &F, OM, Stack);
251     for (const BasicBlock &BB : F)
252       for (const Instruction &I : BB)
253         predictValueUseListOrder(&I, &F, OM, Stack);
254   }
255 
256   // Visit globals last, since the module-level use-list block will be seen
257   // before the function bodies are processed.
258   for (const GlobalVariable &G : M.globals())
259     predictValueUseListOrder(&G, nullptr, OM, Stack);
260   for (const Function &F : M)
261     predictValueUseListOrder(&F, nullptr, OM, Stack);
262   for (const GlobalAlias &A : M.aliases())
263     predictValueUseListOrder(&A, nullptr, OM, Stack);
264   for (const GlobalVariable &G : M.globals())
265     if (G.hasInitializer())
266       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
267   for (const GlobalAlias &A : M.aliases())
268     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
269   for (const Function &F : M) {
270     for (const Use &U : F.operands())
271       predictValueUseListOrder(U.get(), nullptr, OM, Stack);
272   }
273 
274   return Stack;
275 }
276 
277 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
278   return V.first->getType()->isIntOrIntVectorTy();
279 }
280 
281 ValueEnumerator::ValueEnumerator(const Module &M,
282                                  bool ShouldPreserveUseListOrder)
283     : ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
284   if (ShouldPreserveUseListOrder)
285     UseListOrders = predictUseListOrder(M);
286 
287   // Enumerate the global variables.
288   for (const GlobalVariable &GV : M.globals())
289     EnumerateValue(&GV);
290 
291   // Enumerate the functions.
292   for (const Function & F : M) {
293     EnumerateValue(&F);
294     EnumerateAttributes(F.getAttributes());
295   }
296 
297   // Enumerate the aliases.
298   for (const GlobalAlias &GA : M.aliases())
299     EnumerateValue(&GA);
300 
301   // Remember what is the cutoff between globalvalue's and other constants.
302   unsigned FirstConstant = Values.size();
303 
304   // Enumerate the global variable initializers.
305   for (const GlobalVariable &GV : M.globals())
306     if (GV.hasInitializer())
307       EnumerateValue(GV.getInitializer());
308 
309   // Enumerate the aliasees.
310   for (const GlobalAlias &GA : M.aliases())
311     EnumerateValue(GA.getAliasee());
312 
313   // Enumerate any optional Function data.
314   for (const Function &F : M)
315     for (const Use &U : F.operands())
316       EnumerateValue(U.get());
317 
318   // Enumerate the metadata type.
319   //
320   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
321   // only encodes the metadata type when it's used as a value.
322   EnumerateType(Type::getMetadataTy(M.getContext()));
323 
324   // Insert constants and metadata that are named at module level into the slot
325   // pool so that the module symbol table can refer to them...
326   EnumerateValueSymbolTable(M.getValueSymbolTable());
327   EnumerateNamedMetadata(M);
328 
329   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
330 
331   // Enumerate types used by function bodies and argument lists.
332   for (const Function &F : M) {
333     for (const Argument &A : F.args())
334       EnumerateType(A.getType());
335 
336     // Enumerate metadata attached to this function.
337     F.getAllMetadata(MDs);
338     for (const auto &I : MDs)
339       EnumerateMetadata(I.second);
340 
341     for (const BasicBlock &BB : F)
342       for (const Instruction &I : BB) {
343         for (const Use &Op : I.operands()) {
344           auto *MD = dyn_cast<MetadataAsValue>(&Op);
345           if (!MD) {
346             EnumerateOperandType(Op);
347             continue;
348           }
349 
350           // Local metadata is enumerated during function-incorporation.
351           if (isa<LocalAsMetadata>(MD->getMetadata()))
352             continue;
353 
354           EnumerateMetadata(MD->getMetadata());
355         }
356         EnumerateType(I.getType());
357         if (const CallInst *CI = dyn_cast<CallInst>(&I))
358           EnumerateAttributes(CI->getAttributes());
359         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
360           EnumerateAttributes(II->getAttributes());
361 
362         // Enumerate metadata attached with this instruction.
363         MDs.clear();
364         I.getAllMetadataOtherThanDebugLoc(MDs);
365         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
366           EnumerateMetadata(MDs[i].second);
367 
368         // Don't enumerate the location directly -- it has a special record
369         // type -- but enumerate its operands.
370         if (DILocation *L = I.getDebugLoc())
371           EnumerateMDNodeOperands(L);
372       }
373   }
374 
375   // Optimize constant ordering.
376   OptimizeConstants(FirstConstant, Values.size());
377 
378   // Organize metadata ordering.
379   organizeMetadata();
380 }
381 
382 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
383   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
384   assert(I != InstructionMap.end() && "Instruction is not mapped!");
385   return I->second;
386 }
387 
388 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
389   unsigned ComdatID = Comdats.idFor(C);
390   assert(ComdatID && "Comdat not found!");
391   return ComdatID;
392 }
393 
394 void ValueEnumerator::setInstructionID(const Instruction *I) {
395   InstructionMap[I] = InstructionCount++;
396 }
397 
398 unsigned ValueEnumerator::getValueID(const Value *V) const {
399   if (auto *MD = dyn_cast<MetadataAsValue>(V))
400     return getMetadataID(MD->getMetadata());
401 
402   ValueMapType::const_iterator I = ValueMap.find(V);
403   assert(I != ValueMap.end() && "Value not in slotcalculator!");
404   return I->second-1;
405 }
406 
407 LLVM_DUMP_METHOD void ValueEnumerator::dump() const {
408   print(dbgs(), ValueMap, "Default");
409   dbgs() << '\n';
410   print(dbgs(), MetadataMap, "MetaData");
411   dbgs() << '\n';
412 }
413 
414 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
415                             const char *Name) const {
416 
417   OS << "Map Name: " << Name << "\n";
418   OS << "Size: " << Map.size() << "\n";
419   for (ValueMapType::const_iterator I = Map.begin(),
420          E = Map.end(); I != E; ++I) {
421 
422     const Value *V = I->first;
423     if (V->hasName())
424       OS << "Value: " << V->getName();
425     else
426       OS << "Value: [null]\n";
427     V->dump();
428 
429     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
430     for (const Use &U : V->uses()) {
431       if (&U != &*V->use_begin())
432         OS << ",";
433       if(U->hasName())
434         OS << " " << U->getName();
435       else
436         OS << " [null]";
437 
438     }
439     OS <<  "\n\n";
440   }
441 }
442 
443 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
444                             const char *Name) const {
445 
446   OS << "Map Name: " << Name << "\n";
447   OS << "Size: " << Map.size() << "\n";
448   for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
449     const Metadata *MD = I->first;
450     OS << "Metadata: slot = " << I->second << "\n";
451     MD->print(OS);
452   }
453 }
454 
455 /// OptimizeConstants - Reorder constant pool for denser encoding.
456 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
457   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
458 
459   if (ShouldPreserveUseListOrder)
460     // Optimizing constants makes the use-list order difficult to predict.
461     // Disable it for now when trying to preserve the order.
462     return;
463 
464   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
465                    [this](const std::pair<const Value *, unsigned> &LHS,
466                           const std::pair<const Value *, unsigned> &RHS) {
467     // Sort by plane.
468     if (LHS.first->getType() != RHS.first->getType())
469       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
470     // Then by frequency.
471     return LHS.second > RHS.second;
472   });
473 
474   // Ensure that integer and vector of integer constants are at the start of the
475   // constant pool.  This is important so that GEP structure indices come before
476   // gep constant exprs.
477   std::stable_partition(Values.begin() + CstStart, Values.begin() + CstEnd,
478                         isIntOrIntVectorValue);
479 
480   // Rebuild the modified portion of ValueMap.
481   for (; CstStart != CstEnd; ++CstStart)
482     ValueMap[Values[CstStart].first] = CstStart+1;
483 }
484 
485 
486 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
487 /// table into the values table.
488 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
489   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
490        VI != VE; ++VI)
491     EnumerateValue(VI->getValue());
492 }
493 
494 /// Insert all of the values referenced by named metadata in the specified
495 /// module.
496 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
497   for (const auto &I : M.named_metadata())
498     EnumerateNamedMDNode(&I);
499 }
500 
501 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
502   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
503     EnumerateMetadata(MD->getOperand(i));
504 }
505 
506 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
507 /// and types referenced by the given MDNode.
508 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
509   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
510     Metadata *MD = N->getOperand(i);
511     if (!MD)
512       continue;
513     assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
514     EnumerateMetadata(MD);
515   }
516 }
517 
518 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
519   assert(
520       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
521       "Invalid metadata kind");
522 
523   // Insert a dummy ID to block the co-recursive call to
524   // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
525   //
526   // Return early if there's already an ID.
527   if (!MetadataMap.insert(std::make_pair(MD, 0)).second)
528     return;
529 
530   // Visit operands first to minimize RAUW.
531   if (auto *N = dyn_cast<MDNode>(MD))
532     EnumerateMDNodeOperands(N);
533   else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
534     EnumerateValue(C->getValue());
535   else
536     ++NumMDStrings;
537 
538   // Replace the dummy ID inserted above with the correct one.  MetadataMap may
539   // have changed by inserting operands, so we need a fresh lookup here.
540   MDs.push_back(MD);
541   MetadataMap[MD] = MDs.size();
542 }
543 
544 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
545 /// information reachable from the metadata.
546 void ValueEnumerator::EnumerateFunctionLocalMetadata(
547     const LocalAsMetadata *Local) {
548   // Check to see if it's already in!
549   unsigned &MetadataID = MetadataMap[Local];
550   if (MetadataID)
551     return;
552 
553   MDs.push_back(Local);
554   MetadataID = MDs.size();
555 
556   EnumerateValue(Local->getValue());
557 }
558 
559 void ValueEnumerator::organizeMetadata() {
560   if (!NumMDStrings)
561     return;
562 
563   // Put the strings first.
564   std::stable_partition(MDs.begin(), MDs.end(),
565                         [](const Metadata *MD) { return isa<MDString>(MD); });
566 
567   // Renumber.
568   for (unsigned I = 0, E = MDs.size(); I != E; ++I)
569     MetadataMap[MDs[I]] = I + 1;
570 }
571 
572 void ValueEnumerator::EnumerateValue(const Value *V) {
573   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
574   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
575 
576   // Check to see if it's already in!
577   unsigned &ValueID = ValueMap[V];
578   if (ValueID) {
579     // Increment use count.
580     Values[ValueID-1].second++;
581     return;
582   }
583 
584   if (auto *GO = dyn_cast<GlobalObject>(V))
585     if (const Comdat *C = GO->getComdat())
586       Comdats.insert(C);
587 
588   // Enumerate the type of this value.
589   EnumerateType(V->getType());
590 
591   if (const Constant *C = dyn_cast<Constant>(V)) {
592     if (isa<GlobalValue>(C)) {
593       // Initializers for globals are handled explicitly elsewhere.
594     } else if (C->getNumOperands()) {
595       // If a constant has operands, enumerate them.  This makes sure that if a
596       // constant has uses (for example an array of const ints), that they are
597       // inserted also.
598 
599       // We prefer to enumerate them with values before we enumerate the user
600       // itself.  This makes it more likely that we can avoid forward references
601       // in the reader.  We know that there can be no cycles in the constants
602       // graph that don't go through a global variable.
603       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
604            I != E; ++I)
605         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
606           EnumerateValue(*I);
607 
608       // Finally, add the value.  Doing this could make the ValueID reference be
609       // dangling, don't reuse it.
610       Values.push_back(std::make_pair(V, 1U));
611       ValueMap[V] = Values.size();
612       return;
613     }
614   }
615 
616   // Add the value.
617   Values.push_back(std::make_pair(V, 1U));
618   ValueID = Values.size();
619 }
620 
621 
622 void ValueEnumerator::EnumerateType(Type *Ty) {
623   unsigned *TypeID = &TypeMap[Ty];
624 
625   // We've already seen this type.
626   if (*TypeID)
627     return;
628 
629   // If it is a non-anonymous struct, mark the type as being visited so that we
630   // don't recursively visit it.  This is safe because we allow forward
631   // references of these in the bitcode reader.
632   if (StructType *STy = dyn_cast<StructType>(Ty))
633     if (!STy->isLiteral())
634       *TypeID = ~0U;
635 
636   // Enumerate all of the subtypes before we enumerate this type.  This ensures
637   // that the type will be enumerated in an order that can be directly built.
638   for (Type *SubTy : Ty->subtypes())
639     EnumerateType(SubTy);
640 
641   // Refresh the TypeID pointer in case the table rehashed.
642   TypeID = &TypeMap[Ty];
643 
644   // Check to see if we got the pointer another way.  This can happen when
645   // enumerating recursive types that hit the base case deeper than they start.
646   //
647   // If this is actually a struct that we are treating as forward ref'able,
648   // then emit the definition now that all of its contents are available.
649   if (*TypeID && *TypeID != ~0U)
650     return;
651 
652   // Add this type now that its contents are all happily enumerated.
653   Types.push_back(Ty);
654 
655   *TypeID = Types.size();
656 }
657 
658 // Enumerate the types for the specified value.  If the value is a constant,
659 // walk through it, enumerating the types of the constant.
660 void ValueEnumerator::EnumerateOperandType(const Value *V) {
661   EnumerateType(V->getType());
662 
663   assert(!isa<MetadataAsValue>(V) && "Unexpected metadata operand");
664 
665   const Constant *C = dyn_cast<Constant>(V);
666   if (!C)
667     return;
668 
669   // If this constant is already enumerated, ignore it, we know its type must
670   // be enumerated.
671   if (ValueMap.count(C))
672     return;
673 
674   // This constant may have operands, make sure to enumerate the types in
675   // them.
676   for (const Value *Op : C->operands()) {
677     // Don't enumerate basic blocks here, this happens as operands to
678     // blockaddress.
679     if (isa<BasicBlock>(Op))
680       continue;
681 
682     EnumerateOperandType(Op);
683   }
684 }
685 
686 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
687   if (PAL.isEmpty()) return;  // null is always 0.
688 
689   // Do a lookup.
690   unsigned &Entry = AttributeMap[PAL];
691   if (Entry == 0) {
692     // Never saw this before, add it.
693     Attribute.push_back(PAL);
694     Entry = Attribute.size();
695   }
696 
697   // Do lookups for all attribute groups.
698   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
699     AttributeSet AS = PAL.getSlotAttributes(i);
700     unsigned &Entry = AttributeGroupMap[AS];
701     if (Entry == 0) {
702       AttributeGroups.push_back(AS);
703       Entry = AttributeGroups.size();
704     }
705   }
706 }
707 
708 void ValueEnumerator::incorporateFunction(const Function &F) {
709   InstructionCount = 0;
710   NumModuleValues = Values.size();
711   NumModuleMDs = MDs.size();
712 
713   // Adding function arguments to the value table.
714   for (const auto &I : F.args())
715     EnumerateValue(&I);
716 
717   FirstFuncConstantID = Values.size();
718 
719   // Add all function-level constants to the value table.
720   for (const BasicBlock &BB : F) {
721     for (const Instruction &I : BB)
722       for (const Use &OI : I.operands()) {
723         if ((isa<Constant>(OI) && !isa<GlobalValue>(OI)) || isa<InlineAsm>(OI))
724           EnumerateValue(OI);
725       }
726     BasicBlocks.push_back(&BB);
727     ValueMap[&BB] = BasicBlocks.size();
728   }
729 
730   // Optimize the constant layout.
731   OptimizeConstants(FirstFuncConstantID, Values.size());
732 
733   // Add the function's parameter attributes so they are available for use in
734   // the function's instruction.
735   EnumerateAttributes(F.getAttributes());
736 
737   FirstInstID = Values.size();
738 
739   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
740   // Add all of the instructions.
741   for (const BasicBlock &BB : F) {
742     for (const Instruction &I : BB) {
743       for (const Use &OI : I.operands()) {
744         if (auto *MD = dyn_cast<MetadataAsValue>(&OI))
745           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
746             // Enumerate metadata after the instructions they might refer to.
747             FnLocalMDVector.push_back(Local);
748       }
749 
750       if (!I.getType()->isVoidTy())
751         EnumerateValue(&I);
752     }
753   }
754 
755   // Add all of the function-local metadata.
756   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
757     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
758 }
759 
760 void ValueEnumerator::purgeFunction() {
761   /// Remove purged values from the ValueMap.
762   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
763     ValueMap.erase(Values[i].first);
764   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
765     MetadataMap.erase(MDs[i]);
766   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
767     ValueMap.erase(BasicBlocks[i]);
768 
769   Values.resize(NumModuleValues);
770   MDs.resize(NumModuleMDs);
771   BasicBlocks.clear();
772 }
773 
774 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
775                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
776   unsigned Counter = 0;
777   for (const BasicBlock &BB : *F)
778     IDMap[&BB] = ++Counter;
779 }
780 
781 /// getGlobalBasicBlockID - This returns the function-specific ID for the
782 /// specified basic block.  This is relatively expensive information, so it
783 /// should only be used by rare constructs such as address-of-label.
784 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
785   unsigned &Idx = GlobalBasicBlockIDs[BB];
786   if (Idx != 0)
787     return Idx-1;
788 
789   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
790   return getGlobalBasicBlockID(BB);
791 }
792 
793 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
794   return Log2_32_Ceil(getTypes().size() + 1);
795 }
796