a31a49277497ebf6b4b4a1f6b9e74716ffbbbf5d
[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/MDNode.h"
18 #include "llvm/Module.h"
19 #include "llvm/TypeSymbolTable.h"
20 #include "llvm/ValueSymbolTable.h"
21 #include "llvm/Instructions.h"
22 #include <algorithm>
23 using namespace llvm;
24
25 static bool isSingleValueType(const std::pair<const llvm::Type*,
26                               unsigned int> &P) {
27   return P.first->isSingleValueType();
28 }
29
30 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
31   return isa<IntegerType>(V.first->getType());
32 }
33
34 static bool CompareByFrequency(const std::pair<const llvm::Type*,
35                                unsigned int> &P1,
36                                const std::pair<const llvm::Type*,
37                                unsigned int> &P2) {
38   return P1.second > P2.second;
39 }
40
41 /// ValueEnumerator - Enumerate module-level information.
42 ValueEnumerator::ValueEnumerator(const Module *M) {
43   // Enumerate the global variables.
44   for (Module::const_global_iterator I = M->global_begin(),
45          E = M->global_end(); I != E; ++I)
46     EnumerateValue(I);
47
48   // Enumerate the functions.
49   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
50     EnumerateValue(I);
51     EnumerateAttributes(cast<Function>(I)->getAttributes());
52   }
53
54   // Enumerate the aliases.
55   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
56        I != E; ++I)
57     EnumerateValue(I);
58   
59   // Remember what is the cutoff between globalvalue's and other constants.
60   unsigned FirstConstant = Values.size();
61   
62   // Enumerate the global variable initializers.
63   for (Module::const_global_iterator I = M->global_begin(),
64          E = M->global_end(); I != E; ++I)
65     if (I->hasInitializer())
66       EnumerateValue(I->getInitializer());
67
68   // Enumerate the aliasees.
69   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
70        I != E; ++I)
71     EnumerateValue(I->getAliasee());
72   
73   // Enumerate types used by the type symbol table.
74   EnumerateTypeSymbolTable(M->getTypeSymbolTable());
75
76   // Insert constants that are named at module level into the slot pool so that
77   // the module symbol table can refer to them...
78   EnumerateValueSymbolTable(M->getValueSymbolTable());
79   
80   // Enumerate types used by function bodies and argument lists.
81   for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
82     
83     for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
84          I != E; ++I)
85       EnumerateType(I->getType());
86     
87     for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
88       for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
89         for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
90              OI != E; ++OI)
91           EnumerateOperandType(*OI);
92         EnumerateType(I->getType());
93         if (const CallInst *CI = dyn_cast<CallInst>(I))
94           EnumerateAttributes(CI->getAttributes());
95         else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
96           EnumerateAttributes(II->getAttributes());
97       }
98   }
99   
100   // Optimize constant ordering.
101   OptimizeConstants(FirstConstant, Values.size());
102     
103   // Sort the type table by frequency so that most commonly used types are early
104   // in the table (have low bit-width).
105   std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
106     
107   // Partition the Type ID's so that the single-value types occur before the
108   // aggregate types.  This allows the aggregate types to be dropped from the
109   // type table after parsing the global variable initializers.
110   std::partition(Types.begin(), Types.end(), isSingleValueType);
111
112   // Now that we rearranged the type table, rebuild TypeMap.
113   for (unsigned i = 0, e = Types.size(); i != e; ++i)
114     TypeMap[Types[i].first] = i+1;
115 }
116
117 // Optimize constant ordering.
118 namespace {
119   struct CstSortPredicate {
120     ValueEnumerator &VE;
121     explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
122     bool operator()(const std::pair<const Value*, unsigned> &LHS,
123                     const std::pair<const Value*, unsigned> &RHS) {
124       // Sort by plane.
125       if (LHS.first->getType() != RHS.first->getType())
126         return VE.getTypeID(LHS.first->getType()) < 
127                VE.getTypeID(RHS.first->getType());
128       // Then by frequency.
129       return LHS.second > RHS.second;
130     }
131   };
132 }
133
134 /// OptimizeConstants - Reorder constant pool for denser encoding.
135 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
136   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
137   
138   CstSortPredicate P(*this);
139   std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
140   
141   // Ensure that integer constants are at the start of the constant pool.  This
142   // is important so that GEP structure indices come before gep constant exprs.
143   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
144                  isIntegerValue);
145   
146   // Rebuild the modified portion of ValueMap.
147   for (; CstStart != CstEnd; ++CstStart)
148     ValueMap[Values[CstStart].first] = CstStart+1;
149 }
150
151
152 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
153 /// table.
154 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
155   for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end(); 
156        TI != TE; ++TI)
157     EnumerateType(TI->second);
158 }
159
160 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
161 /// table into the values table.
162 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
163   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end(); 
164        VI != VE; ++VI)
165     EnumerateValue(VI->getValue());
166 }
167
168 void ValueEnumerator::EnumerateValue(const Value *V) {
169   assert(V->getType() != Type::VoidTy && "Can't insert void values!");
170   
171   // Check to see if it's already in!
172   unsigned &ValueID = ValueMap[V];
173   if (ValueID) {
174     // Increment use count.
175     Values[ValueID-1].second++;
176     return;
177   }
178
179   // Enumerate the type of this value.
180   EnumerateType(V->getType());
181   
182   if (const Constant *C = dyn_cast<Constant>(V)) {
183     if (isa<GlobalValue>(C)) {
184       // Initializers for globals are handled explicitly elsewhere.
185     } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
186       // Do not enumerate the initializers for an array of simple characters.
187       // The initializers just polute the value table, and we emit the strings
188       // specially.
189     } else if (C->getNumOperands()) {
190       // If a constant has operands, enumerate them.  This makes sure that if a
191       // constant has uses (for example an array of const ints), that they are
192       // inserted also.
193       
194       // We prefer to enumerate them with values before we enumerate the user
195       // itself.  This makes it more likely that we can avoid forward references
196       // in the reader.  We know that there can be no cycles in the constants
197       // graph that don't go through a global variable.
198       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
199            I != E; ++I)
200         EnumerateValue(*I);
201       
202       // Finally, add the value.  Doing this could make the ValueID reference be
203       // dangling, don't reuse it.
204       Values.push_back(std::make_pair(V, 1U));
205       ValueMap[V] = Values.size();
206       return;
207     } else if (const MDNode *N = dyn_cast<MDNode>(C)) {
208       for (MDNode::const_elem_iterator I = N->elem_begin(), E = N->elem_end();
209            I != E; ++I) {
210         if (*I)
211           EnumerateValue(*I);
212         else
213           EnumerateType(Type::VoidTy);
214       }
215
216       Values.push_back(std::make_pair(V, 1U));
217       ValueMap[V] = Values.size();
218       return;
219     }
220   }
221   
222   // Add the value.
223   Values.push_back(std::make_pair(V, 1U));
224   ValueID = Values.size();
225 }
226
227
228 void ValueEnumerator::EnumerateType(const Type *Ty) {
229   unsigned &TypeID = TypeMap[Ty];
230   
231   if (TypeID) {
232     // If we've already seen this type, just increase its occurrence count.
233     Types[TypeID-1].second++;
234     return;
235   }
236   
237   // First time we saw this type, add it.
238   Types.push_back(std::make_pair(Ty, 1U));
239   TypeID = Types.size();
240   
241   // Enumerate subtypes.
242   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
243        I != E; ++I)
244     EnumerateType(*I);
245 }
246
247 // Enumerate the types for the specified value.  If the value is a constant,
248 // walk through it, enumerating the types of the constant.
249 void ValueEnumerator::EnumerateOperandType(const Value *V) {
250   EnumerateType(V->getType());
251   if (const Constant *C = dyn_cast<Constant>(V)) {
252     // If this constant is already enumerated, ignore it, we know its type must
253     // be enumerated.
254     if (ValueMap.count(V)) return;
255
256     // This constant may have operands, make sure to enumerate the types in
257     // them.
258     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i)
259       EnumerateOperandType(C->getOperand(i));
260
261     if (const MDNode *N = dyn_cast<MDNode>(V)) {
262       for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
263         Value *Elem = N->getElement(i);
264         if (Elem)
265           EnumerateOperandType(Elem);
266       }
267     }
268   } else if (const MDString *MDS = dyn_cast<MDString>(V))
269     EnumerateValue(V);
270 }
271
272 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
273   if (PAL.isEmpty()) return;  // null is always 0.
274   // Do a lookup.
275   unsigned &Entry = AttributeMap[PAL.getRawPointer()];
276   if (Entry == 0) {
277     // Never saw this before, add it.
278     Attributes.push_back(PAL);
279     Entry = Attributes.size();
280   }
281 }
282
283
284 void ValueEnumerator::incorporateFunction(const Function &F) {
285   NumModuleValues = Values.size();
286   
287   // Adding function arguments to the value table.
288   for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
289       I != E; ++I)
290     EnumerateValue(I);
291
292   FirstFuncConstantID = Values.size();
293   
294   // Add all function-level constants to the value table.
295   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
296     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
297       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end(); 
298            OI != E; ++OI) {
299         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
300             isa<InlineAsm>(*OI))
301           EnumerateValue(*OI);
302       }
303     BasicBlocks.push_back(BB);
304     ValueMap[BB] = BasicBlocks.size();
305   }
306   
307   // Optimize the constant layout.
308   OptimizeConstants(FirstFuncConstantID, Values.size());
309   
310   // Add the function's parameter attributes so they are available for use in
311   // the function's instruction.
312   EnumerateAttributes(F.getAttributes());
313
314   FirstInstID = Values.size();
315   
316   // Add all of the instructions.
317   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
318     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
319       if (I->getType() != Type::VoidTy)
320         EnumerateValue(I);
321     }
322   }
323 }
324
325 void ValueEnumerator::purgeFunction() {
326   /// Remove purged values from the ValueMap.
327   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
328     ValueMap.erase(Values[i].first);
329   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
330     ValueMap.erase(BasicBlocks[i]);
331     
332   Values.resize(NumModuleValues);
333   BasicBlocks.clear();
334 }
335