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