1 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ValueEnumerator class.
12 //===----------------------------------------------------------------------===//
14 #include "ValueEnumerator.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/LLVMContext.h"
18 #include "llvm/Metadata.h"
19 #include "llvm/Module.h"
20 #include "llvm/TypeSymbolTable.h"
21 #include "llvm/ValueSymbolTable.h"
22 #include "llvm/Instructions.h"
26 static bool isSingleValueType(const std::pair<const llvm::Type*,
28 return P.first->isSingleValueType();
31 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
32 return isa<IntegerType>(V.first->getType());
35 static bool CompareByFrequency(const std::pair<const llvm::Type*,
37 const std::pair<const llvm::Type*,
39 return P1.second > P2.second;
42 /// ValueEnumerator - Enumerate module-level information.
43 ValueEnumerator::ValueEnumerator(const Module *M) {
46 // Enumerate the global variables.
47 for (Module::const_global_iterator I = M->global_begin(),
48 E = M->global_end(); I != E; ++I)
51 // Enumerate the functions.
52 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
54 EnumerateAttributes(cast<Function>(I)->getAttributes());
57 // Enumerate the aliases.
58 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
62 // Remember what is the cutoff between globalvalue's and other constants.
63 unsigned FirstConstant = Values.size();
65 // Enumerate the global variable initializers.
66 for (Module::const_global_iterator I = M->global_begin(),
67 E = M->global_end(); I != E; ++I)
68 if (I->hasInitializer())
69 EnumerateValue(I->getInitializer());
71 // Enumerate the aliasees.
72 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
74 EnumerateValue(I->getAliasee());
76 // Enumerate types used by the type symbol table.
77 EnumerateTypeSymbolTable(M->getTypeSymbolTable());
79 // Insert constants that are named at module level into the slot pool so that
80 // the module symbol table can refer to them...
81 EnumerateValueSymbolTable(M->getValueSymbolTable());
83 // Enumerate types used by function bodies and argument lists.
84 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
86 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
88 EnumerateType(I->getType());
90 MetadataContext &TheMetadata = F->getContext().getMetadata();
91 typedef SmallVector<std::pair<unsigned, TrackingVH<MDNode> >, 2> MDMapTy;
93 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
94 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
95 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
97 EnumerateOperandType(*OI);
98 EnumerateType(I->getType());
99 if (const CallInst *CI = dyn_cast<CallInst>(I))
100 EnumerateAttributes(CI->getAttributes());
101 else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
102 EnumerateAttributes(II->getAttributes());
104 // Enumerate metadata attached with this instruction.
106 TheMetadata.getMDs(I, MDs);
107 for (MDMapTy::const_iterator MI = MDs.begin(), ME = MDs.end(); MI != ME;
109 EnumerateMetadata(MI->second);
113 // Optimize constant ordering.
114 OptimizeConstants(FirstConstant, Values.size());
116 // Sort the type table by frequency so that most commonly used types are early
117 // in the table (have low bit-width).
118 std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
120 // Partition the Type ID's so that the single-value types occur before the
121 // aggregate types. This allows the aggregate types to be dropped from the
122 // type table after parsing the global variable initializers.
123 std::partition(Types.begin(), Types.end(), isSingleValueType);
125 // Now that we rearranged the type table, rebuild TypeMap.
126 for (unsigned i = 0, e = Types.size(); i != e; ++i)
127 TypeMap[Types[i].first] = i+1;
130 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
131 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
132 assert (I != InstructionMap.end() && "Instruction is not mapped!");
136 void ValueEnumerator::setInstructionID(const Instruction *I) {
137 InstructionMap[I] = InstructionCount++;
140 unsigned ValueEnumerator::getValueID(const Value *V) const {
141 if (isa<MetadataBase>(V)) {
142 ValueMapType::const_iterator I = MDValueMap.find(V);
143 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
147 ValueMapType::const_iterator I = ValueMap.find(V);
148 assert(I != ValueMap.end() && "Value not in slotcalculator!");
152 // Optimize constant ordering.
154 struct CstSortPredicate {
156 explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
157 bool operator()(const std::pair<const Value*, unsigned> &LHS,
158 const std::pair<const Value*, unsigned> &RHS) {
160 if (LHS.first->getType() != RHS.first->getType())
161 return VE.getTypeID(LHS.first->getType()) <
162 VE.getTypeID(RHS.first->getType());
163 // Then by frequency.
164 return LHS.second > RHS.second;
169 /// OptimizeConstants - Reorder constant pool for denser encoding.
170 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
171 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
173 CstSortPredicate P(*this);
174 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
176 // Ensure that integer constants are at the start of the constant pool. This
177 // is important so that GEP structure indices come before gep constant exprs.
178 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
181 // Rebuild the modified portion of ValueMap.
182 for (; CstStart != CstEnd; ++CstStart)
183 ValueMap[Values[CstStart].first] = CstStart+1;
187 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
189 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
190 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
192 EnumerateType(TI->second);
195 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
196 /// table into the values table.
197 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
198 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
200 EnumerateValue(VI->getValue());
203 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
204 // Check to see if it's already in!
205 unsigned &MDValueID = MDValueMap[MD];
207 // Increment use count.
208 MDValues[MDValueID-1].second++;
212 // Enumerate the type of this value.
213 EnumerateType(MD->getType());
215 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
216 MDValues.push_back(std::make_pair(MD, 1U));
217 MDValueMap[MD] = MDValues.size();
218 MDValueID = MDValues.size();
219 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i) {
220 if (Value *V = N->getElement(i))
223 EnumerateType(Type::getVoidTy(MD->getContext()));
228 if (const NamedMDNode *N = dyn_cast<NamedMDNode>(MD)) {
229 for(NamedMDNode::const_elem_iterator I = N->elem_begin(),
230 E = N->elem_end(); I != E; ++I) {
231 MetadataBase *M = *I;
234 MDValues.push_back(std::make_pair(MD, 1U));
235 MDValueMap[MD] = Values.size();
240 MDValues.push_back(std::make_pair(MD, 1U));
241 MDValueID = MDValues.size();
244 void ValueEnumerator::EnumerateValue(const Value *V) {
245 assert(V->getType() != Type::getVoidTy(V->getContext()) &&
246 "Can't insert void values!");
247 if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
248 return EnumerateMetadata(MB);
250 // Check to see if it's already in!
251 unsigned &ValueID = ValueMap[V];
253 // Increment use count.
254 Values[ValueID-1].second++;
258 // Enumerate the type of this value.
259 EnumerateType(V->getType());
261 if (const Constant *C = dyn_cast<Constant>(V)) {
262 if (isa<GlobalValue>(C)) {
263 // Initializers for globals are handled explicitly elsewhere.
264 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
265 // Do not enumerate the initializers for an array of simple characters.
266 // The initializers just polute the value table, and we emit the strings
268 } else if (isa<BlockAddress>(C)) {
269 // Don't enumerate function or block.
270 } else if (C->getNumOperands()) {
271 // If a constant has operands, enumerate them. This makes sure that if a
272 // constant has uses (for example an array of const ints), that they are
275 // We prefer to enumerate them with values before we enumerate the user
276 // itself. This makes it more likely that we can avoid forward references
277 // in the reader. We know that there can be no cycles in the constants
278 // graph that don't go through a global variable.
279 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
283 // Finally, add the value. Doing this could make the ValueID reference be
284 // dangling, don't reuse it.
285 Values.push_back(std::make_pair(V, 1U));
286 ValueMap[V] = Values.size();
292 Values.push_back(std::make_pair(V, 1U));
293 ValueID = Values.size();
297 void ValueEnumerator::EnumerateType(const Type *Ty) {
298 unsigned &TypeID = TypeMap[Ty];
301 // If we've already seen this type, just increase its occurrence count.
302 Types[TypeID-1].second++;
306 // First time we saw this type, add it.
307 Types.push_back(std::make_pair(Ty, 1U));
308 TypeID = Types.size();
310 // Enumerate subtypes.
311 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
316 // Enumerate the types for the specified value. If the value is a constant,
317 // walk through it, enumerating the types of the constant.
318 void ValueEnumerator::EnumerateOperandType(const Value *V) {
319 EnumerateType(V->getType());
320 if (const Constant *C = dyn_cast<Constant>(V)) {
321 // If this constant is already enumerated, ignore it, we know its type must
323 if (ValueMap.count(V)) return;
325 // This constant may have operands, make sure to enumerate the types in
327 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
328 const User *Op = C->getOperand(i);
330 // Don't enumerate basic blocks here, this happens as operands to
332 if (isa<BasicBlock>(Op)) continue;
334 EnumerateOperandType(cast<Constant>(Op));
337 if (const MDNode *N = dyn_cast<MDNode>(V)) {
338 for (unsigned i = 0, e = N->getNumElements(); i != e; ++i)
339 if (Value *Elem = N->getElement(i))
340 EnumerateOperandType(Elem);
342 } else if (isa<MDString>(V) || isa<MDNode>(V))
346 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
347 if (PAL.isEmpty()) return; // null is always 0.
349 unsigned &Entry = AttributeMap[PAL.getRawPointer()];
351 // Never saw this before, add it.
352 Attributes.push_back(PAL);
353 Entry = Attributes.size();
358 void ValueEnumerator::incorporateFunction(const Function &F) {
359 NumModuleValues = Values.size();
361 // Adding function arguments to the value table.
362 for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
366 FirstFuncConstantID = Values.size();
368 // Add all function-level constants to the value table.
369 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
370 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
371 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
373 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
377 BasicBlocks.push_back(BB);
378 ValueMap[BB] = BasicBlocks.size();
381 // Optimize the constant layout.
382 OptimizeConstants(FirstFuncConstantID, Values.size());
384 // Add the function's parameter attributes so they are available for use in
385 // the function's instruction.
386 EnumerateAttributes(F.getAttributes());
388 FirstInstID = Values.size();
390 // Add all of the instructions.
391 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
392 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
393 if (I->getType() != Type::getVoidTy(F.getContext()))
399 void ValueEnumerator::purgeFunction() {
400 /// Remove purged values from the ValueMap.
401 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
402 ValueMap.erase(Values[i].first);
403 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
404 ValueMap.erase(BasicBlocks[i]);
406 Values.resize(NumModuleValues);
410 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
411 DenseMap<const BasicBlock*, unsigned> &IDMap) {
412 unsigned Counter = 0;
413 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
414 IDMap[BB] = ++Counter;
417 /// getGlobalBasicBlockID - This returns the function-specific ID for the
418 /// specified basic block. This is relatively expensive information, so it
419 /// should only be used by rare constructs such as address-of-label.
420 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
421 if (BB == 0) return 0;
422 unsigned &Idx = GlobalBasicBlockIDs[BB];
426 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
427 return getGlobalBasicBlockID(BB);