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"
30 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
31 unsigned LastGlobalConstantID;
32 unsigned LastGlobalValueID;
34 OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
36 bool isGlobalConstant(unsigned ID) const {
37 return ID <= LastGlobalConstantID;
39 bool isGlobalValue(unsigned ID) const {
40 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
43 unsigned size() const { return IDs.size(); }
44 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
45 std::pair<unsigned, bool> lookup(const Value *V) const {
48 void index(const Value *V) {
49 // Explicitly sequence get-size and insert-value operations to avoid UB.
50 unsigned ID = IDs.size() + 1;
56 static void orderValue(const Value *V, OrderMap &OM) {
57 if (OM.lookup(V).first)
60 if (const Constant *C = dyn_cast<Constant>(V))
61 if (C->getNumOperands() && !isa<GlobalValue>(C))
62 for (const Value *Op : C->operands())
63 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
66 // Note: we cannot cache this lookup above, since inserting into the map
67 // changes the map's size, and thus affects the other IDs.
71 static OrderMap orderModule(const Module &M) {
72 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
73 // and ValueEnumerator::incorporateFunction().
76 // In the reader, initializers of GlobalValues are set *after* all the
77 // globals have been read. Rather than awkwardly modeling this behaviour
78 // directly in predictValueUseListOrderImpl(), just assign IDs to
79 // initializers of GlobalValues before GlobalValues themselves to model this
81 for (const GlobalVariable &G : M.globals())
82 if (G.hasInitializer())
83 if (!isa<GlobalValue>(G.getInitializer()))
84 orderValue(G.getInitializer(), OM);
85 for (const GlobalAlias &A : M.aliases())
86 if (!isa<GlobalValue>(A.getAliasee()))
87 orderValue(A.getAliasee(), OM);
88 for (const Function &F : M) {
89 if (F.hasPrefixData())
90 if (!isa<GlobalValue>(F.getPrefixData()))
91 orderValue(F.getPrefixData(), OM);
92 if (F.hasPrologueData())
93 if (!isa<GlobalValue>(F.getPrologueData()))
94 orderValue(F.getPrologueData(), OM);
96 OM.LastGlobalConstantID = OM.size();
98 // Initializers of GlobalValues are processed in
99 // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
100 // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
101 // by giving IDs in reverse order.
103 // Since GlobalValues never reference each other directly (just through
104 // initializers), their relative IDs only matter for determining order of
105 // uses in their initializers.
106 for (const Function &F : M)
108 for (const GlobalAlias &A : M.aliases())
110 for (const GlobalVariable &G : M.globals())
112 OM.LastGlobalValueID = OM.size();
114 for (const Function &F : M) {
115 if (F.isDeclaration())
117 // Here we need to match the union of ValueEnumerator::incorporateFunction()
118 // and WriteFunction(). Basic blocks are implicitly declared before
119 // anything else (by declaring their size).
120 for (const BasicBlock &BB : F)
122 for (const Argument &A : F.args())
124 for (const BasicBlock &BB : F)
125 for (const Instruction &I : BB)
126 for (const Value *Op : I.operands())
127 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
130 for (const BasicBlock &BB : F)
131 for (const Instruction &I : BB)
137 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
138 unsigned ID, const OrderMap &OM,
139 UseListOrderStack &Stack) {
140 // Predict use-list order for this one.
141 typedef std::pair<const Use *, unsigned> Entry;
142 SmallVector<Entry, 64> List;
143 for (const Use &U : V->uses())
144 // Check if this user will be serialized.
145 if (OM.lookup(U.getUser()).first)
146 List.push_back(std::make_pair(&U, List.size()));
149 // We may have lost some users.
152 bool IsGlobalValue = OM.isGlobalValue(ID);
153 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
154 const Use *LU = L.first;
155 const Use *RU = R.first;
159 auto LID = OM.lookup(LU->getUser()).first;
160 auto RID = OM.lookup(RU->getUser()).first;
162 // Global values are processed in reverse order.
164 // Moreover, initializers of GlobalValues are set *after* all the globals
165 // have been read (despite having earlier IDs). Rather than awkwardly
166 // modeling this behaviour here, orderModule() has assigned IDs to
167 // initializers of GlobalValues before GlobalValues themselves.
168 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
171 // If ID is 4, then expect: 7 6 5 1 2 3.
174 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
180 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
185 // LID and RID are equal, so we have different operands of the same user.
186 // Assume operands are added in order for all instructions.
188 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
189 return LU->getOperandNo() < RU->getOperandNo();
190 return LU->getOperandNo() > RU->getOperandNo();
194 List.begin(), List.end(),
195 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
196 // Order is already correct.
199 // Store the shuffle.
200 Stack.emplace_back(V, F, List.size());
201 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
202 for (size_t I = 0, E = List.size(); I != E; ++I)
203 Stack.back().Shuffle[I] = List[I].second;
206 static void predictValueUseListOrder(const Value *V, const Function *F,
207 OrderMap &OM, UseListOrderStack &Stack) {
208 auto &IDPair = OM[V];
209 assert(IDPair.first && "Unmapped value");
211 // Already predicted.
214 // Do the actual prediction.
215 IDPair.second = true;
216 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
217 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
219 // Recursive descent into constants.
220 if (const Constant *C = dyn_cast<Constant>(V))
221 if (C->getNumOperands()) // Visit GlobalValues.
222 for (const Value *Op : C->operands())
223 if (isa<Constant>(Op)) // Visit GlobalValues.
224 predictValueUseListOrder(Op, F, OM, Stack);
227 static UseListOrderStack predictUseListOrder(const Module &M) {
228 OrderMap OM = orderModule(M);
230 // Use-list orders need to be serialized after all the users have been added
231 // to a value, or else the shuffles will be incomplete. Store them per
232 // function in a stack.
234 // Aside from function order, the order of values doesn't matter much here.
235 UseListOrderStack Stack;
237 // We want to visit the functions backward now so we can list function-local
238 // constants in the last Function they're used in. Module-level constants
239 // have already been visited above.
240 for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
241 const Function &F = *I;
242 if (F.isDeclaration())
244 for (const BasicBlock &BB : F)
245 predictValueUseListOrder(&BB, &F, OM, Stack);
246 for (const Argument &A : F.args())
247 predictValueUseListOrder(&A, &F, OM, Stack);
248 for (const BasicBlock &BB : F)
249 for (const Instruction &I : BB)
250 for (const Value *Op : I.operands())
251 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
252 predictValueUseListOrder(Op, &F, OM, Stack);
253 for (const BasicBlock &BB : F)
254 for (const Instruction &I : BB)
255 predictValueUseListOrder(&I, &F, OM, Stack);
258 // Visit globals last, since the module-level use-list block will be seen
259 // before the function bodies are processed.
260 for (const GlobalVariable &G : M.globals())
261 predictValueUseListOrder(&G, nullptr, OM, Stack);
262 for (const Function &F : M)
263 predictValueUseListOrder(&F, nullptr, OM, Stack);
264 for (const GlobalAlias &A : M.aliases())
265 predictValueUseListOrder(&A, nullptr, OM, Stack);
266 for (const GlobalVariable &G : M.globals())
267 if (G.hasInitializer())
268 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
269 for (const GlobalAlias &A : M.aliases())
270 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
271 for (const Function &F : M) {
272 if (F.hasPrefixData())
273 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
274 if (F.hasPrologueData())
275 predictValueUseListOrder(F.getPrologueData(), nullptr, OM, Stack);
281 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
282 return V.first->getType()->isIntOrIntVectorTy();
285 ValueEnumerator::ValueEnumerator(const Module &M) {
286 if (shouldPreserveBitcodeUseListOrder())
287 UseListOrders = predictUseListOrder(M);
289 // Enumerate the global variables.
290 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
294 // Enumerate the functions.
295 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
297 EnumerateAttributes(cast<Function>(I)->getAttributes());
300 // Enumerate the aliases.
301 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
305 // Remember what is the cutoff between globalvalue's and other constants.
306 unsigned FirstConstant = Values.size();
308 // Enumerate the global variable initializers.
309 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
311 if (I->hasInitializer())
312 EnumerateValue(I->getInitializer());
314 // Enumerate the aliasees.
315 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
317 EnumerateValue(I->getAliasee());
319 // Enumerate the prefix data constants.
320 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
321 if (I->hasPrefixData())
322 EnumerateValue(I->getPrefixData());
324 // Enumerate the prologue data constants.
325 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
326 if (I->hasPrologueData())
327 EnumerateValue(I->getPrologueData());
329 // Enumerate the metadata type.
331 // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
332 // only encodes the metadata type when it's used as a value.
333 EnumerateType(Type::getMetadataTy(M.getContext()));
335 // Insert constants and metadata that are named at module level into the slot
336 // pool so that the module symbol table can refer to them...
337 EnumerateValueSymbolTable(M.getValueSymbolTable());
338 EnumerateNamedMetadata(M);
340 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
342 // Enumerate types used by function bodies and argument lists.
343 for (const Function &F : M) {
344 for (const Argument &A : F.args())
345 EnumerateType(A.getType());
347 for (const BasicBlock &BB : F)
348 for (const Instruction &I : BB) {
349 for (const Use &Op : I.operands()) {
350 auto *MD = dyn_cast<MetadataAsValue>(&Op);
352 EnumerateOperandType(Op);
356 // Local metadata is enumerated during function-incorporation.
357 if (isa<LocalAsMetadata>(MD->getMetadata()))
360 EnumerateMetadata(MD->getMetadata());
362 EnumerateType(I.getType());
363 if (const CallInst *CI = dyn_cast<CallInst>(&I))
364 EnumerateAttributes(CI->getAttributes());
365 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
366 EnumerateAttributes(II->getAttributes());
368 // Enumerate metadata attached with this instruction.
370 I.getAllMetadataOtherThanDebugLoc(MDs);
371 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
372 EnumerateMetadata(MDs[i].second);
374 if (!I.getDebugLoc().isUnknown()) {
376 I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
377 if (Scope) EnumerateMetadata(Scope);
378 if (IA) EnumerateMetadata(IA);
383 // Optimize constant ordering.
384 OptimizeConstants(FirstConstant, Values.size());
387 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
388 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
389 assert(I != InstructionMap.end() && "Instruction is not mapped!");
393 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
394 unsigned ComdatID = Comdats.idFor(C);
395 assert(ComdatID && "Comdat not found!");
399 void ValueEnumerator::setInstructionID(const Instruction *I) {
400 InstructionMap[I] = InstructionCount++;
403 unsigned ValueEnumerator::getValueID(const Value *V) const {
404 if (auto *MD = dyn_cast<MetadataAsValue>(V))
405 return getMetadataID(MD->getMetadata());
407 ValueMapType::const_iterator I = ValueMap.find(V);
408 assert(I != ValueMap.end() && "Value not in slotcalculator!");
412 unsigned ValueEnumerator::getMetadataID(const Metadata *MD) const {
413 auto I = MDValueMap.find(MD);
414 assert(I != MDValueMap.end() && "Metadata not in slotcalculator!");
415 return I->second - 1;
418 void ValueEnumerator::dump() const {
419 print(dbgs(), ValueMap, "Default");
421 print(dbgs(), MDValueMap, "MetaData");
425 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
426 const char *Name) const {
428 OS << "Map Name: " << Name << "\n";
429 OS << "Size: " << Map.size() << "\n";
430 for (ValueMapType::const_iterator I = Map.begin(),
431 E = Map.end(); I != E; ++I) {
433 const Value *V = I->first;
435 OS << "Value: " << V->getName();
437 OS << "Value: [null]\n";
440 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
441 for (const Use &U : V->uses()) {
442 if (&U != &*V->use_begin())
445 OS << " " << U->getName();
454 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
455 const char *Name) const {
457 OS << "Map Name: " << Name << "\n";
458 OS << "Size: " << Map.size() << "\n";
459 for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
460 const Metadata *MD = I->first;
461 OS << "Metadata: slot = " << I->second << "\n";
466 /// OptimizeConstants - Reorder constant pool for denser encoding.
467 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
468 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
470 if (shouldPreserveBitcodeUseListOrder())
471 // Optimizing constants makes the use-list order difficult to predict.
472 // Disable it for now when trying to preserve the order.
475 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
476 [this](const std::pair<const Value *, unsigned> &LHS,
477 const std::pair<const Value *, unsigned> &RHS) {
479 if (LHS.first->getType() != RHS.first->getType())
480 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
481 // Then by frequency.
482 return LHS.second > RHS.second;
485 // Ensure that integer and vector of integer constants are at the start of the
486 // constant pool. This is important so that GEP structure indices come before
487 // gep constant exprs.
488 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
489 isIntOrIntVectorValue);
491 // Rebuild the modified portion of ValueMap.
492 for (; CstStart != CstEnd; ++CstStart)
493 ValueMap[Values[CstStart].first] = CstStart+1;
497 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
498 /// table into the values table.
499 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
500 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
502 EnumerateValue(VI->getValue());
505 /// Insert all of the values referenced by named metadata in the specified
507 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
508 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
509 E = M.named_metadata_end();
511 EnumerateNamedMDNode(I);
514 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
515 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
516 EnumerateMetadata(MD->getOperand(i));
519 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
520 /// and types referenced by the given MDNode.
521 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
522 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
523 Metadata *MD = N->getOperand(i);
526 assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
527 EnumerateMetadata(MD);
531 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
533 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
534 "Invalid metadata kind");
536 // Insert a dummy ID to block the co-recursive call to
537 // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
539 // Return early if there's already an ID.
540 if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
543 // Visit operands first to minimize RAUW.
544 if (auto *N = dyn_cast<MDNode>(MD))
545 EnumerateMDNodeOperands(N);
546 else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
547 EnumerateValue(C->getValue());
549 // Replace the dummy ID inserted above with the correct one. MDValueMap may
550 // have changed by inserting operands, so we need a fresh lookup here.
552 MDValueMap[MD] = MDs.size();
555 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
556 /// information reachable from the metadata.
557 void ValueEnumerator::EnumerateFunctionLocalMetadata(
558 const LocalAsMetadata *Local) {
559 // Check to see if it's already in!
560 unsigned &MDValueID = MDValueMap[Local];
564 MDs.push_back(Local);
565 MDValueID = MDs.size();
567 EnumerateValue(Local->getValue());
569 // Also, collect all function-local metadata for easy access.
570 FunctionLocalMDs.push_back(Local);
573 void ValueEnumerator::EnumerateValue(const Value *V) {
574 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
575 assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
577 // Check to see if it's already in!
578 unsigned &ValueID = ValueMap[V];
580 // Increment use count.
581 Values[ValueID-1].second++;
585 if (auto *GO = dyn_cast<GlobalObject>(V))
586 if (const Comdat *C = GO->getComdat())
589 // Enumerate the type of this value.
590 EnumerateType(V->getType());
592 if (const Constant *C = dyn_cast<Constant>(V)) {
593 if (isa<GlobalValue>(C)) {
594 // Initializers for globals are handled explicitly elsewhere.
595 } else if (C->getNumOperands()) {
596 // If a constant has operands, enumerate them. This makes sure that if a
597 // constant has uses (for example an array of const ints), that they are
600 // We prefer to enumerate them with values before we enumerate the user
601 // itself. This makes it more likely that we can avoid forward references
602 // in the reader. We know that there can be no cycles in the constants
603 // graph that don't go through a global variable.
604 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
606 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
609 // Finally, add the value. Doing this could make the ValueID reference be
610 // dangling, don't reuse it.
611 Values.push_back(std::make_pair(V, 1U));
612 ValueMap[V] = Values.size();
618 Values.push_back(std::make_pair(V, 1U));
619 ValueID = Values.size();
623 void ValueEnumerator::EnumerateType(Type *Ty) {
624 unsigned *TypeID = &TypeMap[Ty];
626 // We've already seen this type.
630 // If it is a non-anonymous struct, mark the type as being visited so that we
631 // don't recursively visit it. This is safe because we allow forward
632 // references of these in the bitcode reader.
633 if (StructType *STy = dyn_cast<StructType>(Ty))
634 if (!STy->isLiteral())
637 // Enumerate all of the subtypes before we enumerate this type. This ensures
638 // that the type will be enumerated in an order that can be directly built.
639 for (Type *SubTy : Ty->subtypes())
640 EnumerateType(SubTy);
642 // Refresh the TypeID pointer in case the table rehashed.
643 TypeID = &TypeMap[Ty];
645 // Check to see if we got the pointer another way. This can happen when
646 // enumerating recursive types that hit the base case deeper than they start.
648 // If this is actually a struct that we are treating as forward ref'able,
649 // then emit the definition now that all of its contents are available.
650 if (*TypeID && *TypeID != ~0U)
653 // Add this type now that its contents are all happily enumerated.
656 *TypeID = Types.size();
659 // Enumerate the types for the specified value. If the value is a constant,
660 // walk through it, enumerating the types of the constant.
661 void ValueEnumerator::EnumerateOperandType(const Value *V) {
662 EnumerateType(V->getType());
664 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
665 assert(!isa<LocalAsMetadata>(MD->getMetadata()) &&
666 "Function-local metadata should be left for later");
668 EnumerateMetadata(MD->getMetadata());
672 const Constant *C = dyn_cast<Constant>(V);
676 // If this constant is already enumerated, ignore it, we know its type must
678 if (ValueMap.count(C))
681 // This constant may have operands, make sure to enumerate the types in
683 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
684 const Value *Op = C->getOperand(i);
686 // Don't enumerate basic blocks here, this happens as operands to
688 if (isa<BasicBlock>(Op))
691 EnumerateOperandType(Op);
695 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
696 if (PAL.isEmpty()) return; // null is always 0.
699 unsigned &Entry = AttributeMap[PAL];
701 // Never saw this before, add it.
702 Attribute.push_back(PAL);
703 Entry = Attribute.size();
706 // Do lookups for all attribute groups.
707 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
708 AttributeSet AS = PAL.getSlotAttributes(i);
709 unsigned &Entry = AttributeGroupMap[AS];
711 AttributeGroups.push_back(AS);
712 Entry = AttributeGroups.size();
717 void ValueEnumerator::incorporateFunction(const Function &F) {
718 InstructionCount = 0;
719 NumModuleValues = Values.size();
720 NumModuleMDs = MDs.size();
722 // Adding function arguments to the value table.
723 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
727 FirstFuncConstantID = Values.size();
729 // Add all function-level constants to the value table.
730 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
731 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
732 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
734 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
738 BasicBlocks.push_back(BB);
739 ValueMap[BB] = BasicBlocks.size();
742 // Optimize the constant layout.
743 OptimizeConstants(FirstFuncConstantID, Values.size());
745 // Add the function's parameter attributes so they are available for use in
746 // the function's instruction.
747 EnumerateAttributes(F.getAttributes());
749 FirstInstID = Values.size();
751 SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
752 // Add all of the instructions.
753 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
754 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
755 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
757 if (auto *MD = dyn_cast<MetadataAsValue>(&*OI))
758 if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
759 // Enumerate metadata after the instructions they might refer to.
760 FnLocalMDVector.push_back(Local);
763 if (!I->getType()->isVoidTy())
768 // Add all of the function-local metadata.
769 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
770 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
773 void ValueEnumerator::purgeFunction() {
774 /// Remove purged values from the ValueMap.
775 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
776 ValueMap.erase(Values[i].first);
777 for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
778 MDValueMap.erase(MDs[i]);
779 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
780 ValueMap.erase(BasicBlocks[i]);
782 Values.resize(NumModuleValues);
783 MDs.resize(NumModuleMDs);
785 FunctionLocalMDs.clear();
788 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
789 DenseMap<const BasicBlock*, unsigned> &IDMap) {
790 unsigned Counter = 0;
791 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
792 IDMap[BB] = ++Counter;
795 /// getGlobalBasicBlockID - This returns the function-specific ID for the
796 /// specified basic block. This is relatively expensive information, so it
797 /// should only be used by rare constructs such as address-of-label.
798 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
799 unsigned &Idx = GlobalBasicBlockIDs[BB];
803 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
804 return getGlobalBasicBlockID(BB);