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/Module.h"
18 #include "llvm/TypeSymbolTable.h"
19 #include "llvm/ValueSymbolTable.h"
20 #include "llvm/Instructions.h"
24 static bool isSingleValueType(const std::pair<const llvm::Type*,
26 return P.first->isSingleValueType();
29 static bool isIntegerValue(const std::pair<const Value*, unsigned> &V) {
30 return isa<IntegerType>(V.first->getType());
33 static bool CompareByFrequency(const std::pair<const llvm::Type*,
35 const std::pair<const llvm::Type*,
37 return P1.second > P2.second;
40 /// ValueEnumerator - Enumerate module-level information.
41 ValueEnumerator::ValueEnumerator(const Module *M) {
44 // Enumerate the global variables.
45 for (Module::const_global_iterator I = M->global_begin(),
46 E = M->global_end(); I != E; ++I)
49 // Enumerate the functions.
50 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
52 EnumerateAttributes(cast<Function>(I)->getAttributes());
55 // Enumerate the aliases.
56 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
60 // Remember what is the cutoff between globalvalue's and other constants.
61 unsigned FirstConstant = Values.size();
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());
69 // Enumerate the aliasees.
70 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
72 EnumerateValue(I->getAliasee());
74 // Enumerate types used by the type symbol table.
75 EnumerateTypeSymbolTable(M->getTypeSymbolTable());
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());
82 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
84 // Enumerate types used by function bodies and argument lists.
85 for (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
87 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
89 EnumerateType(I->getType());
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();
95 if (MDNode *MD = dyn_cast<MDNode>(*OI))
96 if (MD->isFunctionLocal())
97 // These will get enumerated during function-incorporation.
99 EnumerateOperandType(*OI);
101 EnumerateType(I->getType());
102 if (const CallInst *CI = dyn_cast<CallInst>(I))
103 EnumerateAttributes(CI->getAttributes());
104 else if (const InvokeInst *II = dyn_cast<InvokeInst>(I))
105 EnumerateAttributes(II->getAttributes());
107 // Enumerate metadata attached with this instruction.
109 I->getAllMetadata(MDs);
110 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
111 EnumerateMetadata(MDs[i].second);
115 // Optimize constant ordering.
116 OptimizeConstants(FirstConstant, Values.size());
118 // Sort the type table by frequency so that most commonly used types are early
119 // in the table (have low bit-width).
120 std::stable_sort(Types.begin(), Types.end(), CompareByFrequency);
122 // Partition the Type ID's so that the single-value types occur before the
123 // aggregate types. This allows the aggregate types to be dropped from the
124 // type table after parsing the global variable initializers.
125 std::partition(Types.begin(), Types.end(), isSingleValueType);
127 // Now that we rearranged the type table, rebuild TypeMap.
128 for (unsigned i = 0, e = Types.size(); i != e; ++i)
129 TypeMap[Types[i].first] = i+1;
132 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
133 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
134 assert (I != InstructionMap.end() && "Instruction is not mapped!");
138 void ValueEnumerator::setInstructionID(const Instruction *I) {
139 InstructionMap[I] = InstructionCount++;
142 unsigned ValueEnumerator::getValueID(const Value *V) const {
143 if (isa<MetadataBase>(V)) {
144 ValueMapType::const_iterator I = MDValueMap.find(V);
145 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
149 ValueMapType::const_iterator I = ValueMap.find(V);
150 assert(I != ValueMap.end() && "Value not in slotcalculator!");
154 // Optimize constant ordering.
156 struct CstSortPredicate {
158 explicit CstSortPredicate(ValueEnumerator &ve) : VE(ve) {}
159 bool operator()(const std::pair<const Value*, unsigned> &LHS,
160 const std::pair<const Value*, unsigned> &RHS) {
162 if (LHS.first->getType() != RHS.first->getType())
163 return VE.getTypeID(LHS.first->getType()) <
164 VE.getTypeID(RHS.first->getType());
165 // Then by frequency.
166 return LHS.second > RHS.second;
171 /// OptimizeConstants - Reorder constant pool for denser encoding.
172 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
173 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
175 CstSortPredicate P(*this);
176 std::stable_sort(Values.begin()+CstStart, Values.begin()+CstEnd, P);
178 // Ensure that integer constants are at the start of the constant pool. This
179 // is important so that GEP structure indices come before gep constant exprs.
180 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
183 // Rebuild the modified portion of ValueMap.
184 for (; CstStart != CstEnd; ++CstStart)
185 ValueMap[Values[CstStart].first] = CstStart+1;
189 /// EnumerateTypeSymbolTable - Insert all of the types in the specified symbol
191 void ValueEnumerator::EnumerateTypeSymbolTable(const TypeSymbolTable &TST) {
192 for (TypeSymbolTable::const_iterator TI = TST.begin(), TE = TST.end();
194 EnumerateType(TI->second);
197 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
198 /// table into the values table.
199 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
200 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
202 EnumerateValue(VI->getValue());
205 /// EnumerateMDSymbolTable - Insert all of the values in the specified metadata
207 void ValueEnumerator::EnumerateMDSymbolTable(const MDSymbolTable &MST) {
208 for (MDSymbolTable::const_iterator MI = MST.begin(), ME = MST.end();
210 EnumerateValue(MI->getValue());
213 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
214 // Check to see if it's already in!
215 unsigned &MDValueID = MDValueMap[MD];
217 // Increment use count.
218 MDValues[MDValueID-1].second++;
222 // Enumerate the type of this value.
223 EnumerateType(MD->getType());
225 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
226 if (MDNode *E = MD->getOperand(i))
228 MDValues.push_back(std::make_pair(MD, 1U));
229 MDValueMap[MD] = Values.size();
232 void ValueEnumerator::EnumerateMetadata(const MetadataBase *MD) {
233 // Check to see if it's already in!
234 unsigned &MDValueID = MDValueMap[MD];
236 // Increment use count.
237 MDValues[MDValueID-1].second++;
241 // Enumerate the type of this value.
242 EnumerateType(MD->getType());
244 if (const MDNode *N = dyn_cast<MDNode>(MD)) {
245 MDValues.push_back(std::make_pair(MD, 1U));
246 MDValueMap[MD] = MDValues.size();
247 MDValueID = MDValues.size();
248 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
249 if (Value *V = N->getOperand(i))
252 EnumerateType(Type::getVoidTy(MD->getContext()));
258 assert(isa<MDString>(MD) && "Unknown metadata kind");
259 MDValues.push_back(std::make_pair(MD, 1U));
260 MDValueID = MDValues.size();
263 void ValueEnumerator::EnumerateValue(const Value *V) {
264 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
265 if (const MetadataBase *MB = dyn_cast<MetadataBase>(V))
266 return EnumerateMetadata(MB);
267 else if (const NamedMDNode *NMD = dyn_cast<NamedMDNode>(V))
268 return EnumerateNamedMDNode(NMD);
270 // Check to see if it's already in!
271 unsigned &ValueID = ValueMap[V];
273 // Increment use count.
274 Values[ValueID-1].second++;
278 // Enumerate the type of this value.
279 EnumerateType(V->getType());
281 if (const Constant *C = dyn_cast<Constant>(V)) {
282 if (isa<GlobalValue>(C)) {
283 // Initializers for globals are handled explicitly elsewhere.
284 } else if (isa<ConstantArray>(C) && cast<ConstantArray>(C)->isString()) {
285 // Do not enumerate the initializers for an array of simple characters.
286 // The initializers just polute the value table, and we emit the strings
288 } else if (C->getNumOperands()) {
289 // If a constant has operands, enumerate them. This makes sure that if a
290 // constant has uses (for example an array of const ints), that they are
293 // We prefer to enumerate them with values before we enumerate the user
294 // itself. This makes it more likely that we can avoid forward references
295 // in the reader. We know that there can be no cycles in the constants
296 // graph that don't go through a global variable.
297 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
299 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
302 // Finally, add the value. Doing this could make the ValueID reference be
303 // dangling, don't reuse it.
304 Values.push_back(std::make_pair(V, 1U));
305 ValueMap[V] = Values.size();
311 Values.push_back(std::make_pair(V, 1U));
312 ValueID = Values.size();
316 void ValueEnumerator::EnumerateType(const Type *Ty) {
317 unsigned &TypeID = TypeMap[Ty];
320 // If we've already seen this type, just increase its occurrence count.
321 Types[TypeID-1].second++;
325 // First time we saw this type, add it.
326 Types.push_back(std::make_pair(Ty, 1U));
327 TypeID = Types.size();
329 // Enumerate subtypes.
330 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
335 // Enumerate the types for the specified value. If the value is a constant,
336 // walk through it, enumerating the types of the constant.
337 void ValueEnumerator::EnumerateOperandType(const Value *V) {
338 EnumerateType(V->getType());
340 if (const Constant *C = dyn_cast<Constant>(V)) {
341 // If this constant is already enumerated, ignore it, we know its type must
343 if (ValueMap.count(V)) return;
345 // This constant may have operands, make sure to enumerate the types in
347 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
348 const User *Op = C->getOperand(i);
350 // Don't enumerate basic blocks here, this happens as operands to
352 if (isa<BasicBlock>(Op)) continue;
354 EnumerateOperandType(cast<Constant>(Op));
357 if (const MDNode *N = dyn_cast<MDNode>(V)) {
358 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
359 if (Value *Elem = N->getOperand(i))
360 EnumerateOperandType(Elem);
362 } else if (isa<MDString>(V) || isa<MDNode>(V))
366 void ValueEnumerator::EnumerateAttributes(const AttrListPtr &PAL) {
367 if (PAL.isEmpty()) return; // null is always 0.
369 unsigned &Entry = AttributeMap[PAL.getRawPointer()];
371 // Never saw this before, add it.
372 Attributes.push_back(PAL);
373 Entry = Attributes.size();
378 void ValueEnumerator::incorporateFunction(const Function &F) {
379 NumModuleValues = Values.size();
381 // Adding function arguments to the value table.
382 for(Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
386 FirstFuncConstantID = Values.size();
388 // Add all function-level constants to the value table.
389 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
390 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
391 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
393 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
397 BasicBlocks.push_back(BB);
398 ValueMap[BB] = BasicBlocks.size();
401 // Optimize the constant layout.
402 OptimizeConstants(FirstFuncConstantID, Values.size());
404 // Add the function's parameter attributes so they are available for use in
405 // the function's instruction.
406 EnumerateAttributes(F.getAttributes());
408 FirstInstID = Values.size();
410 // Add all of the instructions.
411 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
412 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
413 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
415 if (MDNode *MD = dyn_cast<MDNode>(*OI))
416 if (!MD->isFunctionLocal())
417 // These were already enumerated during ValueEnumerator creation.
419 EnumerateOperandType(*OI);
421 if (!I->getType()->isVoidTy())
427 void ValueEnumerator::purgeFunction() {
428 /// Remove purged values from the ValueMap.
429 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
430 ValueMap.erase(Values[i].first);
431 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
432 ValueMap.erase(BasicBlocks[i]);
434 Values.resize(NumModuleValues);
438 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
439 DenseMap<const BasicBlock*, unsigned> &IDMap) {
440 unsigned Counter = 0;
441 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
442 IDMap[BB] = ++Counter;
445 /// getGlobalBasicBlockID - This returns the function-specific ID for the
446 /// specified basic block. This is relatively expensive information, so it
447 /// should only be used by rare constructs such as address-of-label.
448 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
449 unsigned &Idx = GlobalBasicBlockIDs[BB];
453 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
454 return getGlobalBasicBlockID(BB);