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