NamedMDNode is never used so there is no need to enumerate it here.
[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/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Module.h"
18 #include "llvm/TypeSymbolTable.h"
19 #include "llvm/ValueSymbolTable.h"
20 #include "llvm/Instructions.h"
21 #include <algorithm>
22 using namespace llvm;
23
24 static bool isSingleValueType(const std::pair<const llvm::Type*,
25                               unsigned int> &P) {
26   return P.first->isSingleValueType();
27 }
28
29 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
30   return isa<IntegerType>(V.first->getType());
31 }
32
33 static bool CompareByFrequency(const std::pair<const llvm::Type*,
34                                unsigned int> &P1,
35                                const std::pair<const llvm::Type*,
36                                unsigned int> &P2) {
37   return P1.second > P2.second;
38 }
39
40 /// ValueEnumerator - Enumerate module-level information.
41 ValueEnumerator::ValueEnumerator(const Module *M) {
42   InstructionCount = 0;
43
44   // Enumerate the global variables.
45   for (Module::const_global_iterator I = M->global_begin(),
46          E = M->global_end(); I != E; ++I)
47     EnumerateValue(I);
48
49   // Enumerate the functions.
50   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
51     EnumerateValue(I);
52     EnumerateAttributes(cast<Function>(I)->getAttributes());
53   }
54
55   // Enumerate the aliases.
56   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
57        I != E; ++I)
58     EnumerateValue(I);
59
60   // Remember what is the cutoff between globalvalue's and other constants.
61   unsigned FirstConstant = Values.size();
62
63   // Enumerate the global variable initializers.
64   for (Module::const_global_iterator I = M->global_begin(),
65          E = M->global_end(); I != E; ++I)
66     if (I->hasInitializer())
67       EnumerateValue(I->getInitializer());
68
69   // Enumerate the aliasees.
70   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
71        I != E; ++I)
72     EnumerateValue(I->getAliasee());
73
74   // Enumerate types used by the type symbol table.
75   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
76
77   // Insert constants and metadata  that are named at module level into the slot 
78   // pool so that the module symbol table can refer to them...
79   EnumerateValueSymbolTable(M->getValueSymbolTable());
80   EnumerateMDSymbolTable(M->getMDSymbolTable());
81
82   SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
83
84   // Enumerate types used by function bodies and argument lists.
85   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
86
87     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
88          I != E; ++I)
89       EnumerateType(I->getType());
90
91     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
92       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
93         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
94              OI != E; ++OI)
95           EnumerateOperandType(*OI);
96         EnumerateType(I->getType());
97         if (const CallInst *CI = dyn_cast<CallInst>(I))
98           EnumerateAttributes(CI->getAttributes());
99         else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
100           EnumerateAttributes(II->getAttributes());
101
102         // Enumerate metadata attached with this instruction.
103         MDs.clear();
104         I->getAllMetadata(MDs);
105         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
106           EnumerateMetadata(MDs[i].second);
107       }
108   }
109
110   // Optimize constant ordering.
111   OptimizeConstants(FirstConstant, Values.size());
112
113   // Sort the type table by frequency so that most commonly used types are early
114   // in the table (have low bit-width).
115   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
116
117   // Partition the Type ID's so that the single-value types occur before the
118   // aggregate types.  This allows the aggregate types to be dropped from the
119   // type table after parsing the global variable initializers.
120   std::partition(Types.begin(), Types.end(), isSingleValueType);
121
122   // Now that we rearranged the type table, rebuild TypeMap.
123   for (unsigned i = 0, e = Types.size(); i != e; ++i)
124     TypeMap[Types[i].first] = i+1;
125 }
126
127 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
128   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
129   assert (I != InstructionMap.end() && "Instruction is not mapped!");
130     return I->second;
131 }
132
133 void ValueEnumerator::setInstructionID(const Instruction *I) {
134   InstructionMap[I] = InstructionCount++;
135 }
136
137 unsigned ValueEnumerator::getValueID(const Value *V) const {
138   if (isa<MetadataBase>(V)) {
139     ValueMapType::const_iterator I = MDValueMap.find(V);
140     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
141     return I->second-1;
142   }
143
144   ValueMapType::const_iterator I = ValueMap.find(V);
145   assert(I != ValueMap.end() && "Value not in slotcalculator!");
146   return I->second-1;
147 }
148
149 // Optimize constant ordering.
150 namespace {
151   struct CstSortPredicate {
152     ValueEnumerator &VE;
153     explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
154     bool operator()(const std::pair<const Value*, unsigned> &LHS,
155                     const std::pair<const Value*, unsigned> &RHS) {
156       // Sort by plane.
157       if (LHS.first->getType() != RHS.first->getType())
158         return VE.getTypeID(LHS.first->getType()) <
159                VE.getTypeID(RHS.first->getType());
160       // Then by frequency.
161       return LHS.second > RHS.second;
162     }
163   };
164 }
165
166 /// OptimizeConstants - Reorder constant pool for denser encoding.
167 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
168   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
169
170   CstSortPredicate P(*this);
171   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
172
173   // Ensure that integer constants are at the start of the constant pool.  This
174   // is important so that GEP structure indices come before gep constant exprs.
175   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
176                  isIntegerValue);
177
178   // Rebuild the modified portion of ValueMap.
179   for (; CstStart != CstEnd; ++CstStart)
180     ValueMap[Values[CstStart].first] = CstStart+1;
181 }
182
183
184 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
185 /// table.
186 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
187   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
188        TI != TE; ++TI)
189     EnumerateType(TI->second);
190 }
191
192 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
193 /// table into the values table.
194 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
195   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
196        VI != VE; ++VI)
197     EnumerateValue(VI->getValue());
198 }
199
200 /// EnumerateMDSymbolTable - Insert all of the values in the specified metadata
201 /// table.
202 void ValueEnumerator::EnumerateMDSymbolTable(const MDSymbolTable &MST) {
203   for (MDSymbolTable::const_iterator MI = MST.begin(), ME = MST.end();
204        MI != ME; ++MI)
205     EnumerateValue(MI->getValue());
206 }
207
208 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
209   // Check to see if it's already in!
210   unsigned &MDValueID = MDValueMap[MD];
211   if (MDValueID) {
212     // Increment use count.
213     MDValues[MDValueID-1].second++;
214     return;
215   }
216
217   // Enumerate the type of this value.
218   EnumerateType(MD->getType());
219
220   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
221     if (MDNode *E = MD->getOperand(i))
222       EnumerateValue(E);
223   MDValues.push_back(std::make_pair(MD, 1U));
224   MDValueMap[MD] = Values.size();
225 }
226
227 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
228   // Check to see if it's already in!
229   unsigned &MDValueID = MDValueMap[MD];
230   if (MDValueID) {
231     // Increment use count.
232     MDValues[MDValueID-1].second++;
233     return;
234   }
235
236   // Enumerate the type of this value.
237   EnumerateType(MD->getType());
238
239   if (const MDNode *N = dyn_cast<MDNode>(MD)) {
240     MDValues.push_back(std::make_pair(MD, 1U));
241     MDValueMap[MD] = MDValues.size();
242     MDValueID = MDValues.size();
243     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {    
244       if (Value *V = N->getOperand(i))
245         EnumerateValue(V);
246       else
247         EnumerateType(Type::getVoidTy(MD->getContext()));
248     }
249     return;
250   }
251   
252   // Add the value.
253   assert(isa<MDString>(MD) && "Unknown metadata kind");
254   MDValues.push_back(std::make_pair(MD, 1U));
255   MDValueID = MDValues.size();
256 }
257
258 void ValueEnumerator::EnumerateValue(const Value *V) {
259   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
260   if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
261     return EnumerateMetadata(MB);
262   else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
263     return EnumerateNamedMDNode(NMD);
264
265   // Check to see if it's already in!
266   unsigned &ValueID = ValueMap[V];
267   if (ValueID) {
268     // Increment use count.
269     Values[ValueID-1].second++;
270     return;
271   }
272
273   // Enumerate the type of this value.
274   EnumerateType(V->getType());
275
276   if (const Constant *C = dyn_cast<Constant>(V)) {
277     if (isa<GlobalValue>(C)) {
278       // Initializers for globals are handled explicitly elsewhere.
279     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
280       // Do not enumerate the initializers for an array of simple characters.
281       // The initializers just polute the value table, and we emit the strings
282       // specially.
283     } else if (C->getNumOperands()) {
284       // If a constant has operands, enumerate them.  This makes sure that if a
285       // constant has uses (for example an array of const ints), that they are
286       // inserted also.
287
288       // We prefer to enumerate them with values before we enumerate the user
289       // itself.  This makes it more likely that we can avoid forward references
290       // in the reader.  We know that there can be no cycles in the constants
291       // graph that don't go through a global variable.
292       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
293            I != E; ++I)
294         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
295           EnumerateValue(*I);
296
297       // Finally, add the value.  Doing this could make the ValueID reference be
298       // dangling, don't reuse it.
299       Values.push_back(std::make_pair(V, 1U));
300       ValueMap[V] = Values.size();
301       return;
302     }
303   }
304
305   // Add the value.
306   Values.push_back(std::make_pair(V, 1U));
307   ValueID = Values.size();
308 }
309
310
311 void ValueEnumerator::EnumerateType(const Type *Ty) {
312   unsigned &TypeID = TypeMap[Ty];
313
314   if (TypeID) {
315     // If we've already seen this type, just increase its occurrence count.
316     Types[TypeID-1].second++;
317     return;
318   }
319
320   // First time we saw this type, add it.
321   Types.push_back(std::make_pair(Ty, 1U));
322   TypeID = Types.size();
323
324   // Enumerate subtypes.
325   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
326        I != E; ++I)
327     EnumerateType(*I);
328 }
329
330 // Enumerate the types for the specified value.  If the value is a constant,
331 // walk through it, enumerating the types of the constant.
332 void ValueEnumerator::EnumerateOperandType(const Value *V) {
333   EnumerateType(V->getType());
334   if (const Constant *C = dyn_cast<Constant>(V)) {
335     // If this constant is already enumerated, ignore it, we know its type must
336     // be enumerated.
337     if (ValueMap.count(V)) return;
338
339     // This constant may have operands, make sure to enumerate the types in
340     // them.
341     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
342       const User *Op = C->getOperand(i);
343       
344       // Don't enumerate basic blocks here, this happens as operands to
345       // blockaddress.
346       if (isa<BasicBlock>(Op)) continue;
347       
348       EnumerateOperandType(cast<Constant>(Op));
349     }
350
351     if (const MDNode *N = dyn_cast<MDNode>(V)) {
352       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
353         if (Value *Elem = N->getOperand(i))
354           EnumerateOperandType(Elem);
355     }
356   } else if (isa<MDString>(V) || isa<MDNode>(V))
357     EnumerateValue(V);
358 }
359
360 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
361   if (PAL.isEmpty()) return;  // null is always 0.
362   // Do a lookup.
363   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
364   if (Entry == 0) {
365     // Never saw this before, add it.
366     Attributes.push_back(PAL);
367     Entry = Attributes.size();
368   }
369 }
370
371
372 void ValueEnumerator::incorporateFunction(const Function &F) {
373   NumModuleValues = Values.size();
374
375   // Adding function arguments to the value table.
376   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
377       I != E; ++I)
378     EnumerateValue(I);
379
380   FirstFuncConstantID = Values.size();
381
382   // Add all function-level constants to the value table.
383   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
384     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
385       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
386            OI != E; ++OI) {
387         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
388             isa<InlineAsm>(*OI))
389           EnumerateValue(*OI);
390       }
391     BasicBlocks.push_back(BB);
392     ValueMap[BB] = BasicBlocks.size();
393   }
394
395   // Optimize the constant layout.
396   OptimizeConstants(FirstFuncConstantID, Values.size());
397
398   // Add the function's parameter attributes so they are available for use in
399   // the function's instruction.
400   EnumerateAttributes(F.getAttributes());
401
402   FirstInstID = Values.size();
403
404   // Add all of the instructions.
405   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
406     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
407       if (!I->getType()->isVoidTy())
408         EnumerateValue(I);
409     }
410   }
411 }
412
413 void ValueEnumerator::purgeFunction() {
414   /// Remove purged values from the ValueMap.
415   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
416     ValueMap.erase(Values[i].first);
417   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
418     ValueMap.erase(BasicBlocks[i]);
419
420   Values.resize(NumModuleValues);
421   BasicBlocks.clear();
422 }
423
424 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
425                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
426   unsigned Counter = 0;
427   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
428     IDMap[BB] = ++Counter;
429 }
430
431 /// getGlobalBasicBlockID - This returns the function-specific ID for the
432 /// specified basic block.  This is relatively expensive information, so it
433 /// should only be used by rare constructs such as address-of-label.
434 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
435   unsigned &Idx = GlobalBasicBlockIDs[BB];
436   if (Idx != 0)
437     return Idx-1;
438
439   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
440   return getGlobalBasicBlockID(BB);
441 }
442