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