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