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 (Module::const_iterator F = M->begin(), E = M->end(); F != E; ++F) {
78 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
80 EnumerateType(I->getType());
82 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
83 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E;++I){
84 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
86 if (MDNode *MD = dyn_cast<MDNode>(*OI))
87 if (MD->isFunctionLocal() && MD->getFunction())
88 // These will get enumerated during function-incorporation.
90 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());
98 // Enumerate metadata attached with this instruction.
100 I->getAllMetadataOtherThanDebugLoc(MDs);
101 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
102 EnumerateMetadata(MDs[i].second);
104 if (!I->getDebugLoc().isUnknown()) {
106 I->getDebugLoc().getScopeAndInlinedAt(Scope, IA, I->getContext());
107 if (Scope) EnumerateMetadata(Scope);
108 if (IA) EnumerateMetadata(IA);
113 // Optimize constant ordering.
114 OptimizeConstants(FirstConstant, Values.size());
117 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
118 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
119 assert(I != InstructionMap.end() && "Instruction is not mapped!");
123 void ValueEnumerator::setInstructionID(const Instruction *I) {
124 InstructionMap[I] = InstructionCount++;
127 unsigned ValueEnumerator::getValueID(const Value *V) const {
128 if (isa<MDNode>(V) || isa<MDString>(V)) {
129 ValueMapType::const_iterator I = MDValueMap.find(V);
130 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
134 ValueMapType::const_iterator I = ValueMap.find(V);
135 assert(I != ValueMap.end() && "Value not in slotcalculator!");
139 void ValueEnumerator::dump() const {
140 print(dbgs(), ValueMap, "Default");
142 print(dbgs(), MDValueMap, "MetaData");
146 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
147 const char *Name) const {
149 OS << "Map Name: " << Name << "\n";
150 OS << "Size: " << Map.size() << "\n";
151 for (ValueMapType::const_iterator I = Map.begin(),
152 E = Map.end(); I != E; ++I) {
154 const Value *V = I->first;
156 OS << "Value: " << V->getName();
158 OS << "Value: [null]\n";
161 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
162 for (Value::const_use_iterator UI = V->use_begin(), UE = V->use_end();
164 if (UI != V->use_begin())
167 OS << " " << (*UI)->getName();
176 /// OptimizeConstants - Reorder constant pool for denser encoding.
177 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
178 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
180 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
181 [this](const std::pair<const Value *, unsigned> &LHS,
182 const std::pair<const Value *, unsigned> &RHS) {
184 if (LHS.first->getType() != RHS.first->getType())
185 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
186 // Then by frequency.
187 return LHS.second > RHS.second;
190 // Ensure that integer and vector of integer constants are at the start of the
191 // constant pool. This is important so that GEP structure indices come before
192 // gep constant exprs.
193 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
194 isIntOrIntVectorValue);
196 // Rebuild the modified portion of ValueMap.
197 for (; CstStart != CstEnd; ++CstStart)
198 ValueMap[Values[CstStart].first] = CstStart+1;
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();
207 EnumerateValue(VI->getValue());
210 /// EnumerateNamedMetadata - Insert all of the values referenced by
211 /// named metadata in the specified module.
212 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
213 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
214 E = M->named_metadata_end(); I != E; ++I)
215 EnumerateNamedMDNode(I);
218 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
219 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
220 EnumerateMetadata(MD->getOperand(i));
223 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
224 /// and types referenced by the given MDNode.
225 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
226 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
227 if (Value *V = N->getOperand(i)) {
228 if (isa<MDNode>(V) || isa<MDString>(V))
229 EnumerateMetadata(V);
230 else if (!isa<Instruction>(V) && !isa<Argument>(V))
233 EnumerateType(Type::getVoidTy(N->getContext()));
237 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
238 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
240 // Enumerate the type of this value.
241 EnumerateType(MD->getType());
243 const MDNode *N = dyn_cast<MDNode>(MD);
245 // In the module-level pass, skip function-local nodes themselves, but
246 // do walk their operands.
247 if (N && N->isFunctionLocal() && N->getFunction()) {
248 EnumerateMDNodeOperands(N);
252 // Check to see if it's already in!
253 unsigned &MDValueID = MDValueMap[MD];
255 // Increment use count.
256 MDValues[MDValueID-1].second++;
259 MDValues.push_back(std::make_pair(MD, 1U));
260 MDValueID = MDValues.size();
262 // Enumerate all non-function-local operands.
264 EnumerateMDNodeOperands(N);
267 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
268 /// information reachable from the given MDNode.
269 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
270 assert(N->isFunctionLocal() && N->getFunction() &&
271 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
273 // Enumerate the type of this value.
274 EnumerateType(N->getType());
276 // Check to see if it's already in!
277 unsigned &MDValueID = MDValueMap[N];
279 // Increment use count.
280 MDValues[MDValueID-1].second++;
283 MDValues.push_back(std::make_pair(N, 1U));
284 MDValueID = MDValues.size();
286 // To incoroporate function-local information visit all function-local
287 // MDNodes and all function-local values they reference.
288 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
289 if (Value *V = N->getOperand(i)) {
290 if (MDNode *O = dyn_cast<MDNode>(V)) {
291 if (O->isFunctionLocal() && O->getFunction())
292 EnumerateFunctionLocalMetadata(O);
293 } else if (isa<Instruction>(V) || isa<Argument>(V))
297 // Also, collect all function-local MDNodes for easy access.
298 FunctionLocalMDs.push_back(N);
301 void ValueEnumerator::EnumerateValue(const Value *V) {
302 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
303 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
304 "EnumerateValue doesn't handle Metadata!");
306 // Check to see if it's already in!
307 unsigned &ValueID = ValueMap[V];
309 // Increment use count.
310 Values[ValueID-1].second++;
314 // Enumerate the type of this value.
315 EnumerateType(V->getType());
317 if (const Constant *C = dyn_cast<Constant>(V)) {
318 if (isa<GlobalValue>(C)) {
319 // Initializers for globals are handled explicitly elsewhere.
320 } else if (C->getNumOperands()) {
321 // If a constant has operands, enumerate them. This makes sure that if a
322 // constant has uses (for example an array of const ints), that they are
325 // We prefer to enumerate them with values before we enumerate the user
326 // itself. This makes it more likely that we can avoid forward references
327 // in the reader. We know that there can be no cycles in the constants
328 // graph that don't go through a global variable.
329 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
331 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
334 // Finally, add the value. Doing this could make the ValueID reference be
335 // dangling, don't reuse it.
336 Values.push_back(std::make_pair(V, 1U));
337 ValueMap[V] = Values.size();
343 Values.push_back(std::make_pair(V, 1U));
344 ValueID = Values.size();
348 void ValueEnumerator::EnumerateType(Type *Ty) {
349 unsigned *TypeID = &TypeMap[Ty];
351 // We've already seen this type.
355 // If it is a non-anonymous struct, mark the type as being visited so that we
356 // don't recursively visit it. This is safe because we allow forward
357 // references of these in the bitcode reader.
358 if (StructType *STy = dyn_cast<StructType>(Ty))
359 if (!STy->isLiteral())
362 // Enumerate all of the subtypes before we enumerate this type. This ensures
363 // that the type will be enumerated in an order that can be directly built.
364 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
368 // Refresh the TypeID pointer in case the table rehashed.
369 TypeID = &TypeMap[Ty];
371 // Check to see if we got the pointer another way. This can happen when
372 // enumerating recursive types that hit the base case deeper than they start.
374 // If this is actually a struct that we are treating as forward ref'able,
375 // then emit the definition now that all of its contents are available.
376 if (*TypeID && *TypeID != ~0U)
379 // Add this type now that its contents are all happily enumerated.
382 *TypeID = Types.size();
385 // Enumerate the types for the specified value. If the value is a constant,
386 // walk through it, enumerating the types of the constant.
387 void ValueEnumerator::EnumerateOperandType(const Value *V) {
388 EnumerateType(V->getType());
390 if (const Constant *C = dyn_cast<Constant>(V)) {
391 // If this constant is already enumerated, ignore it, we know its type must
393 if (ValueMap.count(V)) return;
395 // This constant may have operands, make sure to enumerate the types in
397 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
398 const Value *Op = C->getOperand(i);
400 // Don't enumerate basic blocks here, this happens as operands to
402 if (isa<BasicBlock>(Op)) continue;
404 EnumerateOperandType(Op);
407 if (const MDNode *N = dyn_cast<MDNode>(V)) {
408 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
409 if (Value *Elem = N->getOperand(i))
410 EnumerateOperandType(Elem);
412 } else if (isa<MDString>(V) || isa<MDNode>(V))
413 EnumerateMetadata(V);
416 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
417 if (PAL.isEmpty()) return; // null is always 0.
420 unsigned &Entry = AttributeMap[PAL];
422 // Never saw this before, add it.
423 Attribute.push_back(PAL);
424 Entry = Attribute.size();
427 // Do lookups for all attribute groups.
428 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
429 AttributeSet AS = PAL.getSlotAttributes(i);
430 unsigned &Entry = AttributeGroupMap[AS];
432 AttributeGroups.push_back(AS);
433 Entry = AttributeGroups.size();
438 void ValueEnumerator::incorporateFunction(const Function &F) {
439 InstructionCount = 0;
440 NumModuleValues = Values.size();
441 NumModuleMDValues = MDValues.size();
443 // Adding function arguments to the value table.
444 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
448 FirstFuncConstantID = Values.size();
450 // Add all function-level constants to the value table.
451 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
452 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
453 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
455 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
459 BasicBlocks.push_back(BB);
460 ValueMap[BB] = BasicBlocks.size();
463 // Optimize the constant layout.
464 OptimizeConstants(FirstFuncConstantID, Values.size());
466 // Add the function's parameter attributes so they are available for use in
467 // the function's instruction.
468 EnumerateAttributes(F.getAttributes());
470 FirstInstID = Values.size();
472 SmallVector<MDNode *, 8> FnLocalMDVector;
473 // Add all of the instructions.
474 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
475 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
476 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
478 if (MDNode *MD = dyn_cast<MDNode>(*OI))
479 if (MD->isFunctionLocal() && MD->getFunction())
480 // Enumerate metadata after the instructions they might refer to.
481 FnLocalMDVector.push_back(MD);
484 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
485 I->getAllMetadataOtherThanDebugLoc(MDs);
486 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
487 MDNode *N = MDs[i].second;
488 if (N->isFunctionLocal() && N->getFunction())
489 FnLocalMDVector.push_back(N);
492 if (!I->getType()->isVoidTy())
497 // Add all of the function-local metadata.
498 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
499 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
502 void ValueEnumerator::purgeFunction() {
503 /// Remove purged values from the ValueMap.
504 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
505 ValueMap.erase(Values[i].first);
506 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
507 MDValueMap.erase(MDValues[i].first);
508 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
509 ValueMap.erase(BasicBlocks[i]);
511 Values.resize(NumModuleValues);
512 MDValues.resize(NumModuleMDValues);
514 FunctionLocalMDs.clear();
517 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
518 DenseMap<const BasicBlock*, unsigned> &IDMap) {
519 unsigned Counter = 0;
520 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
521 IDMap[BB] = ++Counter;
524 /// getGlobalBasicBlockID - This returns the function-specific ID for the
525 /// specified basic block. This is relatively expensive information, so it
526 /// should only be used by rare constructs such as address-of-label.
527 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
528 unsigned &Idx = GlobalBasicBlockIDs[BB];
532 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
533 return getGlobalBasicBlockID(BB);