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/UseListOrder.h"
22 #include "llvm/IR/ValueSymbolTable.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
28 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
29 return V.first->getType()->isIntOrIntVectorTy();
32 /// ValueEnumerator - Enumerate module-level information.
33 ValueEnumerator::ValueEnumerator(const Module *M) {
34 // Enumerate the global variables.
35 for (Module::const_global_iterator I = M->global_begin(),
36 E = M->global_end(); I != E; ++I)
39 // Enumerate the functions.
40 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
42 EnumerateAttributes(cast<Function>(I)->getAttributes());
45 // Enumerate the aliases.
46 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
50 // Remember what is the cutoff between globalvalue's and other constants.
51 unsigned FirstConstant = Values.size();
53 // Enumerate the global variable initializers.
54 for (Module::const_global_iterator I = M->global_begin(),
55 E = M->global_end(); I != E; ++I)
56 if (I->hasInitializer())
57 EnumerateValue(I->getInitializer());
59 // Enumerate the aliasees.
60 for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
62 EnumerateValue(I->getAliasee());
64 // Enumerate the prefix data constants.
65 for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
66 if (I->hasPrefixData())
67 EnumerateValue(I->getPrefixData());
69 // Insert constants and metadata that are named at module level into the slot
70 // pool so that the module symbol table can refer to them...
71 EnumerateValueSymbolTable(M->getValueSymbolTable());
72 EnumerateNamedMetadata(M);
74 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
76 // Enumerate types used by function bodies and argument lists.
77 for (const Function &F : *M) {
78 for (const Argument &A : F.args())
79 EnumerateType(A.getType());
81 for (const BasicBlock &BB : F)
82 for (const Instruction &I : BB) {
83 for (const Use &Op : I.operands()) {
84 if (MDNode *MD = dyn_cast<MDNode>(&Op))
85 if (MD->isFunctionLocal() && MD->getFunction())
86 // These will get enumerated during function-incorporation.
88 EnumerateOperandType(Op);
90 EnumerateType(I.getType());
91 if (const CallInst *CI = dyn_cast<CallInst>(&I))
92 EnumerateAttributes(CI->getAttributes());
93 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
94 EnumerateAttributes(II->getAttributes());
96 // Enumerate metadata attached with this instruction.
98 I.getAllMetadataOtherThanDebugLoc(MDs);
99 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
100 EnumerateMetadata(MDs[i].second);
102 if (!I.getDebugLoc().isUnknown()) {
104 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
105 if (Scope) EnumerateMetadata(Scope);
106 if (IA) EnumerateMetadata(IA);
111 // Optimize constant ordering.
112 OptimizeConstants(FirstConstant, Values.size());
115 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
116 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
117 assert(I != InstructionMap.end() && "Instruction is not mapped!");
121 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
122 unsigned ComdatID = Comdats.idFor(C);
123 assert(ComdatID && "Comdat not found!");
127 void ValueEnumerator::setInstructionID(const Instruction *I) {
128 InstructionMap[I] = InstructionCount++;
131 unsigned ValueEnumerator::getValueID(const Value *V) const {
132 if (isa<MDNode>(V) || isa<MDString>(V)) {
133 ValueMapType::const_iterator I = MDValueMap.find(V);
134 assert(I != MDValueMap.end() && "Value not in slotcalculator!");
138 ValueMapType::const_iterator I = ValueMap.find(V);
139 assert(I != ValueMap.end() && "Value not in slotcalculator!");
143 void ValueEnumerator::dump() const {
144 print(dbgs(), ValueMap, "Default");
146 print(dbgs(), MDValueMap, "MetaData");
150 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
151 const char *Name) const {
153 OS << "Map Name: " << Name << "\n";
154 OS << "Size: " << Map.size() << "\n";
155 for (ValueMapType::const_iterator I = Map.begin(),
156 E = Map.end(); I != E; ++I) {
158 const Value *V = I->first;
160 OS << "Value: " << V->getName();
162 OS << "Value: [null]\n";
165 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
166 for (const Use &U : V->uses()) {
167 if (&U != &*V->use_begin())
170 OS << " " << U->getName();
179 /// OptimizeConstants - Reorder constant pool for denser encoding.
180 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
181 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
183 if (shouldPreserveBitcodeUseListOrder())
184 // Optimizing constants makes the use-list order difficult to predict.
185 // Disable it for now when trying to preserve the order.
188 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
189 [this](const std::pair<const Value *, unsigned> &LHS,
190 const std::pair<const Value *, unsigned> &RHS) {
192 if (LHS.first->getType() != RHS.first->getType())
193 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
194 // Then by frequency.
195 return LHS.second > RHS.second;
198 // Ensure that integer and vector of integer constants are at the start of the
199 // constant pool. This is important so that GEP structure indices come before
200 // gep constant exprs.
201 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
202 isIntOrIntVectorValue);
204 // Rebuild the modified portion of ValueMap.
205 for (; CstStart != CstEnd; ++CstStart)
206 ValueMap[Values[CstStart].first] = CstStart+1;
210 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
211 /// table into the values table.
212 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
213 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
215 EnumerateValue(VI->getValue());
218 /// EnumerateNamedMetadata - Insert all of the values referenced by
219 /// named metadata in the specified module.
220 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
221 for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
222 E = M->named_metadata_end(); I != E; ++I)
223 EnumerateNamedMDNode(I);
226 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
227 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
228 EnumerateMetadata(MD->getOperand(i));
231 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
232 /// and types referenced by the given MDNode.
233 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
234 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
235 if (Value *V = N->getOperand(i)) {
236 if (isa<MDNode>(V) || isa<MDString>(V))
237 EnumerateMetadata(V);
238 else if (!isa<Instruction>(V) && !isa<Argument>(V))
241 EnumerateType(Type::getVoidTy(N->getContext()));
245 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
246 assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
248 // Enumerate the type of this value.
249 EnumerateType(MD->getType());
251 const MDNode *N = dyn_cast<MDNode>(MD);
253 // In the module-level pass, skip function-local nodes themselves, but
254 // do walk their operands.
255 if (N && N->isFunctionLocal() && N->getFunction()) {
256 EnumerateMDNodeOperands(N);
260 // Check to see if it's already in!
261 unsigned &MDValueID = MDValueMap[MD];
263 // Increment use count.
264 MDValues[MDValueID-1].second++;
267 MDValues.push_back(std::make_pair(MD, 1U));
268 MDValueID = MDValues.size();
270 // Enumerate all non-function-local operands.
272 EnumerateMDNodeOperands(N);
275 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
276 /// information reachable from the given MDNode.
277 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
278 assert(N->isFunctionLocal() && N->getFunction() &&
279 "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
281 // Enumerate the type of this value.
282 EnumerateType(N->getType());
284 // Check to see if it's already in!
285 unsigned &MDValueID = MDValueMap[N];
287 // Increment use count.
288 MDValues[MDValueID-1].second++;
291 MDValues.push_back(std::make_pair(N, 1U));
292 MDValueID = MDValues.size();
294 // To incoroporate function-local information visit all function-local
295 // MDNodes and all function-local values they reference.
296 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
297 if (Value *V = N->getOperand(i)) {
298 if (MDNode *O = dyn_cast<MDNode>(V)) {
299 if (O->isFunctionLocal() && O->getFunction())
300 EnumerateFunctionLocalMetadata(O);
301 } else if (isa<Instruction>(V) || isa<Argument>(V))
305 // Also, collect all function-local MDNodes for easy access.
306 FunctionLocalMDs.push_back(N);
309 void ValueEnumerator::EnumerateValue(const Value *V) {
310 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
311 assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
312 "EnumerateValue doesn't handle Metadata!");
314 // Check to see if it's already in!
315 unsigned &ValueID = ValueMap[V];
317 // Increment use count.
318 Values[ValueID-1].second++;
322 if (auto *GO = dyn_cast<GlobalObject>(V))
323 if (const Comdat *C = GO->getComdat())
326 // Enumerate the type of this value.
327 EnumerateType(V->getType());
329 if (const Constant *C = dyn_cast<Constant>(V)) {
330 if (isa<GlobalValue>(C)) {
331 // Initializers for globals are handled explicitly elsewhere.
332 } else if (C->getNumOperands()) {
333 // If a constant has operands, enumerate them. This makes sure that if a
334 // constant has uses (for example an array of const ints), that they are
337 // We prefer to enumerate them with values before we enumerate the user
338 // itself. This makes it more likely that we can avoid forward references
339 // in the reader. We know that there can be no cycles in the constants
340 // graph that don't go through a global variable.
341 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
343 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
346 // Finally, add the value. Doing this could make the ValueID reference be
347 // dangling, don't reuse it.
348 Values.push_back(std::make_pair(V, 1U));
349 ValueMap[V] = Values.size();
355 Values.push_back(std::make_pair(V, 1U));
356 ValueID = Values.size();
360 void ValueEnumerator::EnumerateType(Type *Ty) {
361 unsigned *TypeID = &TypeMap[Ty];
363 // We've already seen this type.
367 // If it is a non-anonymous struct, mark the type as being visited so that we
368 // don't recursively visit it. This is safe because we allow forward
369 // references of these in the bitcode reader.
370 if (StructType *STy = dyn_cast<StructType>(Ty))
371 if (!STy->isLiteral())
374 // Enumerate all of the subtypes before we enumerate this type. This ensures
375 // that the type will be enumerated in an order that can be directly built.
376 for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
380 // Refresh the TypeID pointer in case the table rehashed.
381 TypeID = &TypeMap[Ty];
383 // Check to see if we got the pointer another way. This can happen when
384 // enumerating recursive types that hit the base case deeper than they start.
386 // If this is actually a struct that we are treating as forward ref'able,
387 // then emit the definition now that all of its contents are available.
388 if (*TypeID && *TypeID != ~0U)
391 // Add this type now that its contents are all happily enumerated.
394 *TypeID = Types.size();
397 // Enumerate the types for the specified value. If the value is a constant,
398 // walk through it, enumerating the types of the constant.
399 void ValueEnumerator::EnumerateOperandType(const Value *V) {
400 EnumerateType(V->getType());
402 if (const Constant *C = dyn_cast<Constant>(V)) {
403 // If this constant is already enumerated, ignore it, we know its type must
405 if (ValueMap.count(V)) return;
407 // This constant may have operands, make sure to enumerate the types in
409 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
410 const Value *Op = C->getOperand(i);
412 // Don't enumerate basic blocks here, this happens as operands to
414 if (isa<BasicBlock>(Op)) continue;
416 EnumerateOperandType(Op);
419 if (const MDNode *N = dyn_cast<MDNode>(V)) {
420 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
421 if (Value *Elem = N->getOperand(i))
422 EnumerateOperandType(Elem);
424 } else if (isa<MDString>(V) || isa<MDNode>(V))
425 EnumerateMetadata(V);
428 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
429 if (PAL.isEmpty()) return; // null is always 0.
432 unsigned &Entry = AttributeMap[PAL];
434 // Never saw this before, add it.
435 Attribute.push_back(PAL);
436 Entry = Attribute.size();
439 // Do lookups for all attribute groups.
440 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
441 AttributeSet AS = PAL.getSlotAttributes(i);
442 unsigned &Entry = AttributeGroupMap[AS];
444 AttributeGroups.push_back(AS);
445 Entry = AttributeGroups.size();
450 void ValueEnumerator::incorporateFunction(const Function &F) {
451 InstructionCount = 0;
452 NumModuleValues = Values.size();
453 NumModuleMDValues = MDValues.size();
455 // Adding function arguments to the value table.
456 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
460 FirstFuncConstantID = Values.size();
462 // Add all function-level constants to the value table.
463 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
464 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
465 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
467 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
471 BasicBlocks.push_back(BB);
472 ValueMap[BB] = BasicBlocks.size();
475 // Optimize the constant layout.
476 OptimizeConstants(FirstFuncConstantID, Values.size());
478 // Add the function's parameter attributes so they are available for use in
479 // the function's instruction.
480 EnumerateAttributes(F.getAttributes());
482 FirstInstID = Values.size();
484 SmallVector<MDNode *, 8> FnLocalMDVector;
485 // Add all of the instructions.
486 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
487 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
488 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
490 if (MDNode *MD = dyn_cast<MDNode>(*OI))
491 if (MD->isFunctionLocal() && MD->getFunction())
492 // Enumerate metadata after the instructions they might refer to.
493 FnLocalMDVector.push_back(MD);
496 SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
497 I->getAllMetadataOtherThanDebugLoc(MDs);
498 for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
499 MDNode *N = MDs[i].second;
500 if (N->isFunctionLocal() && N->getFunction())
501 FnLocalMDVector.push_back(N);
504 if (!I->getType()->isVoidTy())
509 // Add all of the function-local metadata.
510 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
511 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
514 void ValueEnumerator::purgeFunction() {
515 /// Remove purged values from the ValueMap.
516 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
517 ValueMap.erase(Values[i].first);
518 for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
519 MDValueMap.erase(MDValues[i].first);
520 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
521 ValueMap.erase(BasicBlocks[i]);
523 Values.resize(NumModuleValues);
524 MDValues.resize(NumModuleMDValues);
526 FunctionLocalMDs.clear();
529 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
530 DenseMap<const BasicBlock*, unsigned> &IDMap) {
531 unsigned Counter = 0;
532 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
533 IDMap[BB] = ++Counter;
536 /// getGlobalBasicBlockID - This returns the function-specific ID for the
537 /// specified basic block. This is relatively expensive information, so it
538 /// should only be used by rare constructs such as address-of-label.
539 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
540 unsigned &Idx = GlobalBasicBlockIDs[BB];
544 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
545 return getGlobalBasicBlockID(BB);