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/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallPtrSet.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DerivedTypes.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/ValueSymbolTable.h"
22 #include "llvm/Support/Debug.h"
23 #include "llvm/Support/raw_ostream.h"
27 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
28 return V.first->getType()->isIntOrIntVectorTy();
31 /// ValueEnumerator - Enumerate module-level information.
32 ValueEnumerator::ValueEnumerator(const Module *M) {
33 // Enumerate the global variables.
34 for (Module::const_global_iterator I = M->global_begin(),
35 E = M->global_end(); I != E; ++I)
38 // Enumerate the functions.
39 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
41 EnumerateAttributes(cast<Function>(I)->getAttributes());
44 // Enumerate the aliases.
45 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
49 // Remember what is the cutoff between globalvalue's and other constants.
50 unsigned FirstConstant = Values.size();
52 // Enumerate the global variable initializers.
53 for (Module::const_global_iterator I = M->global_begin(),
54 E = M->global_end(); I != E; ++I)
55 if (I->hasInitializer())
56 EnumerateValue(I->getInitializer());
58 // Enumerate the aliasees.
59 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
61 EnumerateValue(I->getAliasee());
63 // Enumerate the prefix data constants.
64 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
65 if (I->hasPrefixData())
66 EnumerateValue(I->getPrefixData());
68 // Insert constants and metadata that are named at module level into the slot
69 // pool so that the module symbol table can refer to them...
70 EnumerateValueSymbolTable(M->getValueSymbolTable());
71 EnumerateNamedMetadata(M);
73 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
75 // Enumerate types used by function bodies and argument lists.
76 for (const Function &F : *M) {
77 for (const Argument &A : F.args())
78 EnumerateType(A.getType());
80 for (const BasicBlock &BB : F)
81 for (const Instruction &I : BB) {
82 for (const Use &Op : I.operands()) {
83 if (MDNode *MD = dyn_cast<MDNode>(&Op))
84 if (MD->isFunctionLocal() && MD->getFunction())
85 // These will get enumerated during function-incorporation.
87 EnumerateOperandType(Op);
89 EnumerateType(I.getType());
90 if (const CallInst *CI = dyn_cast<CallInst>(&I))
91 EnumerateAttributes(CI->getAttributes());
92 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
93 EnumerateAttributes(II->getAttributes());
95 // Enumerate metadata attached with this instruction.
97 I.getAllMetadataOtherThanDebugLoc(MDs);
98 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
99 EnumerateMetadata(MDs[i].second);
101 if (!I.getDebugLoc().isUnknown()) {
103 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
104 if (Scope) EnumerateMetadata(Scope);
105 if (IA) EnumerateMetadata(IA);
110 // Optimize constant ordering.
111 OptimizeConstants(FirstConstant, Values.size());
114 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
115 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
116 assert(I != InstructionMap.end() && "Instruction is not mapped!");
120 void ValueEnumerator::setInstructionID(const Instruction *I) {
121 InstructionMap[I] = InstructionCount++;
124 unsigned ValueEnumerator::getValueID(const Value *V) const {
125 if (isa<MDNode>(V) || isa<MDString>(V)) {
126 ValueMapType::const_iterator I = MDValueMap.find(V);
127 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
131 ValueMapType::const_iterator I = ValueMap.find(V);
132 assert(I != ValueMap.end() && "Value not in slotcalculator!");
136 void ValueEnumerator::dump() const {
137 print(dbgs(), ValueMap, "Default");
139 print(dbgs(), MDValueMap, "MetaData");
143 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
144 const char *Name) const {
146 OS << "Map Name: " << Name << "\n";
147 OS << "Size: " << Map.size() << "\n";
148 for (ValueMapType::const_iterator I = Map.begin(),
149 E = Map.end(); I != E; ++I) {
151 const Value *V = I->first;
153 OS << "Value: " << V->getName();
155 OS << "Value: [null]\n";
158 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
159 for (const Use &U : V->uses()) {
160 if (&U != &*V->use_begin())
163 OS << " " << U->getName();
172 /// OptimizeConstants - Reorder constant pool for denser encoding.
173 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
174 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
176 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
177 [this](const std::pair<const Value *, unsigned> &LHS,
178 const std::pair<const Value *, unsigned> &RHS) {
180 if (LHS.first->getType() != RHS.first->getType())
181 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
182 // Then by frequency.
183 return LHS.second > RHS.second;
186 // Ensure that integer and vector of integer constants are at the start of the
187 // constant pool. This is important so that GEP structure indices come before
188 // gep constant exprs.
189 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
190 isIntOrIntVectorValue);
192 // Rebuild the modified portion of ValueMap.
193 for (; CstStart != CstEnd; ++CstStart)
194 ValueMap[Values[CstStart].first] = CstStart+1;
198 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
199 /// table into the values table.
200 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
201 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
203 EnumerateValue(VI->getValue());
206 /// EnumerateNamedMetadata - Insert all of the values referenced by
207 /// named metadata in the specified module.
208 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
209 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
210 E = M->named_metadata_end(); I != E; ++I)
211 EnumerateNamedMDNode(I);
214 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
215 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
216 EnumerateMetadata(MD->getOperand(i));
219 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
220 /// and types referenced by the given MDNode.
221 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
222 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
223 if (Value *V = N->getOperand(i)) {
224 if (isa<MDNode>(V) || isa<MDString>(V))
225 EnumerateMetadata(V);
226 else if (!isa<Instruction>(V) && !isa<Argument>(V))
229 EnumerateType(Type::getVoidTy(N->getContext()));
233 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
234 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
236 // Enumerate the type of this value.
237 EnumerateType(MD->getType());
239 const MDNode *N = dyn_cast<MDNode>(MD);
241 // In the module-level pass, skip function-local nodes themselves, but
242 // do walk their operands.
243 if (N && N->isFunctionLocal() && N->getFunction()) {
244 EnumerateMDNodeOperands(N);
248 // Check to see if it's already in!
249 unsigned &MDValueID = MDValueMap[MD];
251 // Increment use count.
252 MDValues[MDValueID-1].second++;
255 MDValues.push_back(std::make_pair(MD, 1U));
256 MDValueID = MDValues.size();
258 // Enumerate all non-function-local operands.
260 EnumerateMDNodeOperands(N);
263 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
264 /// information reachable from the given MDNode.
265 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
266 assert(N->isFunctionLocal() && N->getFunction() &&
267 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
269 // Enumerate the type of this value.
270 EnumerateType(N->getType());
272 // Check to see if it's already in!
273 unsigned &MDValueID = MDValueMap[N];
275 // Increment use count.
276 MDValues[MDValueID-1].second++;
279 MDValues.push_back(std::make_pair(N, 1U));
280 MDValueID = MDValues.size();
282 // To incoroporate function-local information visit all function-local
283 // MDNodes and all function-local values they reference.
284 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
285 if (Value *V = N->getOperand(i)) {
286 if (MDNode *O = dyn_cast<MDNode>(V)) {
287 if (O->isFunctionLocal() && O->getFunction())
288 EnumerateFunctionLocalMetadata(O);
289 } else if (isa<Instruction>(V) || isa<Argument>(V))
293 // Also, collect all function-local MDNodes for easy access.
294 FunctionLocalMDs.push_back(N);
297 void ValueEnumerator::EnumerateValue(const Value *V) {
298 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
299 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
300 "EnumerateValue doesn't handle Metadata!");
302 // Check to see if it's already in!
303 unsigned &ValueID = ValueMap[V];
305 // Increment use count.
306 Values[ValueID-1].second++;
310 // Enumerate the type of this value.
311 EnumerateType(V->getType());
313 if (const Constant *C = dyn_cast<Constant>(V)) {
314 if (isa<GlobalValue>(C)) {
315 // Initializers for globals are handled explicitly elsewhere.
316 } else if (C->getNumOperands()) {
317 // If a constant has operands, enumerate them. This makes sure that if a
318 // constant has uses (for example an array of const ints), that they are
321 // We prefer to enumerate them with values before we enumerate the user
322 // itself. This makes it more likely that we can avoid forward references
323 // in the reader. We know that there can be no cycles in the constants
324 // graph that don't go through a global variable.
325 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
327 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
330 // Finally, add the value. Doing this could make the ValueID reference be
331 // dangling, don't reuse it.
332 Values.push_back(std::make_pair(V, 1U));
333 ValueMap[V] = Values.size();
339 Values.push_back(std::make_pair(V, 1U));
340 ValueID = Values.size();
344 void ValueEnumerator::EnumerateType(Type *Ty) {
345 unsigned *TypeID = &TypeMap[Ty];
347 // We've already seen this type.
351 // If it is a non-anonymous struct, mark the type as being visited so that we
352 // don't recursively visit it. This is safe because we allow forward
353 // references of these in the bitcode reader.
354 if (StructType *STy = dyn_cast<StructType>(Ty))
355 if (!STy->isLiteral())
358 // Enumerate all of the subtypes before we enumerate this type. This ensures
359 // that the type will be enumerated in an order that can be directly built.
360 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
364 // Refresh the TypeID pointer in case the table rehashed.
365 TypeID = &TypeMap[Ty];
367 // Check to see if we got the pointer another way. This can happen when
368 // enumerating recursive types that hit the base case deeper than they start.
370 // If this is actually a struct that we are treating as forward ref'able,
371 // then emit the definition now that all of its contents are available.
372 if (*TypeID && *TypeID != ~0U)
375 // Add this type now that its contents are all happily enumerated.
378 *TypeID = Types.size();
381 // Enumerate the types for the specified value. If the value is a constant,
382 // walk through it, enumerating the types of the constant.
383 void ValueEnumerator::EnumerateOperandType(const Value *V) {
384 EnumerateType(V->getType());
386 if (const Constant *C = dyn_cast<Constant>(V)) {
387 // If this constant is already enumerated, ignore it, we know its type must
389 if (ValueMap.count(V)) return;
391 // This constant may have operands, make sure to enumerate the types in
393 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
394 const Value *Op = C->getOperand(i);
396 // Don't enumerate basic blocks here, this happens as operands to
398 if (isa<BasicBlock>(Op)) continue;
400 EnumerateOperandType(Op);
403 if (const MDNode *N = dyn_cast<MDNode>(V)) {
404 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
405 if (Value *Elem = N->getOperand(i))
406 EnumerateOperandType(Elem);
408 } else if (isa<MDString>(V) || isa<MDNode>(V))
409 EnumerateMetadata(V);
412 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
413 if (PAL.isEmpty()) return; // null is always 0.
416 unsigned &Entry = AttributeMap[PAL];
418 // Never saw this before, add it.
419 Attribute.push_back(PAL);
420 Entry = Attribute.size();
423 // Do lookups for all attribute groups.
424 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
425 AttributeSet AS = PAL.getSlotAttributes(i);
426 unsigned &Entry = AttributeGroupMap[AS];
428 AttributeGroups.push_back(AS);
429 Entry = AttributeGroups.size();
434 void ValueEnumerator::incorporateFunction(const Function &F) {
435 InstructionCount = 0;
436 NumModuleValues = Values.size();
437 NumModuleMDValues = MDValues.size();
439 // Adding function arguments to the value table.
440 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
444 FirstFuncConstantID = Values.size();
446 // Add all function-level constants to the value table.
447 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
448 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
449 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
451 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
455 BasicBlocks.push_back(BB);
456 ValueMap[BB] = BasicBlocks.size();
459 // Optimize the constant layout.
460 OptimizeConstants(FirstFuncConstantID, Values.size());
462 // Add the function's parameter attributes so they are available for use in
463 // the function's instruction.
464 EnumerateAttributes(F.getAttributes());
466 FirstInstID = Values.size();
468 SmallVector<MDNode *, 8> FnLocalMDVector;
469 // Add all of the instructions.
470 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
471 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
472 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
474 if (MDNode *MD = dyn_cast<MDNode>(*OI))
475 if (MD->isFunctionLocal() && MD->getFunction())
476 // Enumerate metadata after the instructions they might refer to.
477 FnLocalMDVector.push_back(MD);
480 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
481 I->getAllMetadataOtherThanDebugLoc(MDs);
482 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
483 MDNode *N = MDs[i].second;
484 if (N->isFunctionLocal() && N->getFunction())
485 FnLocalMDVector.push_back(N);
488 if (!I->getType()->isVoidTy())
493 // Add all of the function-local metadata.
494 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
495 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
498 void ValueEnumerator::purgeFunction() {
499 /// Remove purged values from the ValueMap.
500 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
501 ValueMap.erase(Values[i].first);
502 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
503 MDValueMap.erase(MDValues[i].first);
504 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
505 ValueMap.erase(BasicBlocks[i]);
507 Values.resize(NumModuleValues);
508 MDValues.resize(NumModuleMDValues);
510 FunctionLocalMDs.clear();
513 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
514 DenseMap<const BasicBlock*, unsigned> &IDMap) {
515 unsigned Counter = 0;
516 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
517 IDMap[BB] = ++Counter;
520 /// getGlobalBasicBlockID - This returns the function-specific ID for the
521 /// specified basic block. This is relatively expensive information, so it
522 /// should only be used by rare constructs such as address-of-label.
523 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
524 unsigned &Idx = GlobalBasicBlockIDs[BB];
528 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
529 return getGlobalBasicBlockID(BB);