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