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/DebugInfoMetadata.h"
19 #include "llvm/IR/DerivedTypes.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Module.h"
22 #include "llvm/IR/UseListOrder.h"
23 #include "llvm/IR/ValueSymbolTable.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
31 DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
32 unsigned LastGlobalConstantID;
33 unsigned LastGlobalValueID;
35 OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
37 bool isGlobalConstant(unsigned ID) const {
38 return ID <= LastGlobalConstantID;
40 bool isGlobalValue(unsigned ID) const {
41 return ID <= LastGlobalValueID && !isGlobalConstant(ID);
44 unsigned size() const { return IDs.size(); }
45 std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
46 std::pair<unsigned, bool> lookup(const Value *V) const {
49 void index(const Value *V) {
50 // Explicitly sequence get-size and insert-value operations to avoid UB.
51 unsigned ID = IDs.size() + 1;
57 static void orderValue(const Value *V, OrderMap &OM) {
58 if (OM.lookup(V).first)
61 if (const Constant *C = dyn_cast<Constant>(V))
62 if (C->getNumOperands() && !isa<GlobalValue>(C))
63 for (const Value *Op : C->operands())
64 if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
67 // Note: we cannot cache this lookup above, since inserting into the map
68 // changes the map's size, and thus affects the other IDs.
72 static OrderMap orderModule(const Module &M) {
73 // This needs to match the order used by ValueEnumerator::ValueEnumerator()
74 // and ValueEnumerator::incorporateFunction().
77 // In the reader, initializers of GlobalValues are set *after* all the
78 // globals have been read. Rather than awkwardly modeling this behaviour
79 // directly in predictValueUseListOrderImpl(), just assign IDs to
80 // initializers of GlobalValues before GlobalValues themselves to model this
82 for (const GlobalVariable &G : M.globals())
83 if (G.hasInitializer())
84 if (!isa<GlobalValue>(G.getInitializer()))
85 orderValue(G.getInitializer(), OM);
86 for (const GlobalAlias &A : M.aliases())
87 if (!isa<GlobalValue>(A.getAliasee()))
88 orderValue(A.getAliasee(), OM);
89 for (const Function &F : M) {
90 if (F.hasPrefixData())
91 if (!isa<GlobalValue>(F.getPrefixData()))
92 orderValue(F.getPrefixData(), OM);
93 if (F.hasPrologueData())
94 if (!isa<GlobalValue>(F.getPrologueData()))
95 orderValue(F.getPrologueData(), OM);
97 OM.LastGlobalConstantID = OM.size();
99 // Initializers of GlobalValues are processed in
100 // BitcodeReader::ResolveGlobalAndAliasInits(). Match the order there rather
101 // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
102 // by giving IDs in reverse order.
104 // Since GlobalValues never reference each other directly (just through
105 // initializers), their relative IDs only matter for determining order of
106 // uses in their initializers.
107 for (const Function &F : M)
109 for (const GlobalAlias &A : M.aliases())
111 for (const GlobalVariable &G : M.globals())
113 OM.LastGlobalValueID = OM.size();
115 for (const Function &F : M) {
116 if (F.isDeclaration())
118 // Here we need to match the union of ValueEnumerator::incorporateFunction()
119 // and WriteFunction(). Basic blocks are implicitly declared before
120 // anything else (by declaring their size).
121 for (const BasicBlock &BB : F)
123 for (const Argument &A : F.args())
125 for (const BasicBlock &BB : F)
126 for (const Instruction &I : BB)
127 for (const Value *Op : I.operands())
128 if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
131 for (const BasicBlock &BB : F)
132 for (const Instruction &I : BB)
138 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
139 unsigned ID, const OrderMap &OM,
140 UseListOrderStack &Stack) {
141 // Predict use-list order for this one.
142 typedef std::pair<const Use *, unsigned> Entry;
143 SmallVector<Entry, 64> List;
144 for (const Use &U : V->uses())
145 // Check if this user will be serialized.
146 if (OM.lookup(U.getUser()).first)
147 List.push_back(std::make_pair(&U, List.size()));
150 // We may have lost some users.
153 bool IsGlobalValue = OM.isGlobalValue(ID);
154 std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
155 const Use *LU = L.first;
156 const Use *RU = R.first;
160 auto LID = OM.lookup(LU->getUser()).first;
161 auto RID = OM.lookup(RU->getUser()).first;
163 // Global values are processed in reverse order.
165 // Moreover, initializers of GlobalValues are set *after* all the globals
166 // have been read (despite having earlier IDs). Rather than awkwardly
167 // modeling this behaviour here, orderModule() has assigned IDs to
168 // initializers of GlobalValues before GlobalValues themselves.
169 if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
172 // If ID is 4, then expect: 7 6 5 1 2 3.
175 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
181 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
186 // LID and RID are equal, so we have different operands of the same user.
187 // Assume operands are added in order for all instructions.
189 if (!IsGlobalValue) // GlobalValue uses don't get reversed.
190 return LU->getOperandNo() < RU->getOperandNo();
191 return LU->getOperandNo() > RU->getOperandNo();
195 List.begin(), List.end(),
196 [](const Entry &L, const Entry &R) { return L.second < R.second; }))
197 // Order is already correct.
200 // Store the shuffle.
201 Stack.emplace_back(V, F, List.size());
202 assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
203 for (size_t I = 0, E = List.size(); I != E; ++I)
204 Stack.back().Shuffle[I] = List[I].second;
207 static void predictValueUseListOrder(const Value *V, const Function *F,
208 OrderMap &OM, UseListOrderStack &Stack) {
209 auto &IDPair = OM[V];
210 assert(IDPair.first && "Unmapped value");
212 // Already predicted.
215 // Do the actual prediction.
216 IDPair.second = true;
217 if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
218 predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
220 // Recursive descent into constants.
221 if (const Constant *C = dyn_cast<Constant>(V))
222 if (C->getNumOperands()) // Visit GlobalValues.
223 for (const Value *Op : C->operands())
224 if (isa<Constant>(Op)) // Visit GlobalValues.
225 predictValueUseListOrder(Op, F, OM, Stack);
228 static UseListOrderStack predictUseListOrder(const Module &M) {
229 OrderMap OM = orderModule(M);
231 // Use-list orders need to be serialized after all the users have been added
232 // to a value, or else the shuffles will be incomplete. Store them per
233 // function in a stack.
235 // Aside from function order, the order of values doesn't matter much here.
236 UseListOrderStack Stack;
238 // We want to visit the functions backward now so we can list function-local
239 // constants in the last Function they're used in. Module-level constants
240 // have already been visited above.
241 for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
242 const Function &F = *I;
243 if (F.isDeclaration())
245 for (const BasicBlock &BB : F)
246 predictValueUseListOrder(&BB, &F, OM, Stack);
247 for (const Argument &A : F.args())
248 predictValueUseListOrder(&A, &F, OM, Stack);
249 for (const BasicBlock &BB : F)
250 for (const Instruction &I : BB)
251 for (const Value *Op : I.operands())
252 if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
253 predictValueUseListOrder(Op, &F, OM, Stack);
254 for (const BasicBlock &BB : F)
255 for (const Instruction &I : BB)
256 predictValueUseListOrder(&I, &F, OM, Stack);
259 // Visit globals last, since the module-level use-list block will be seen
260 // before the function bodies are processed.
261 for (const GlobalVariable &G : M.globals())
262 predictValueUseListOrder(&G, nullptr, OM, Stack);
263 for (const Function &F : M)
264 predictValueUseListOrder(&F, nullptr, OM, Stack);
265 for (const GlobalAlias &A : M.aliases())
266 predictValueUseListOrder(&A, nullptr, OM, Stack);
267 for (const GlobalVariable &G : M.globals())
268 if (G.hasInitializer())
269 predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
270 for (const GlobalAlias &A : M.aliases())
271 predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
272 for (const Function &F : M) {
273 if (F.hasPrefixData())
274 predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
275 if (F.hasPrologueData())
276 predictValueUseListOrder(F.getPrologueData(), nullptr, OM, Stack);
282 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
283 return V.first->getType()->isIntOrIntVectorTy();
286 ValueEnumerator::ValueEnumerator(const Module &M,
287 bool ShouldPreserveUseListOrder)
288 : HasMDString(false), HasDILocation(false), HasGenericDINode(false),
289 ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
290 if (ShouldPreserveUseListOrder)
291 UseListOrders = predictUseListOrder(M);
293 // Enumerate the global variables.
294 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
298 // Enumerate the functions.
299 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
301 EnumerateAttributes(cast<Function>(I)->getAttributes());
304 // Enumerate the aliases.
305 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
309 // Remember what is the cutoff between globalvalue's and other constants.
310 unsigned FirstConstant = Values.size();
312 // Enumerate the global variable initializers.
313 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
315 if (I->hasInitializer())
316 EnumerateValue(I->getInitializer());
318 // Enumerate the aliasees.
319 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
321 EnumerateValue(I->getAliasee());
323 // Enumerate the prefix data constants.
324 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
325 if (I->hasPrefixData())
326 EnumerateValue(I->getPrefixData());
328 // Enumerate the prologue data constants.
329 for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
330 if (I->hasPrologueData())
331 EnumerateValue(I->getPrologueData());
333 // Enumerate the metadata type.
335 // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
336 // only encodes the metadata type when it's used as a value.
337 EnumerateType(Type::getMetadataTy(M.getContext()));
339 // Insert constants and metadata that are named at module level into the slot
340 // pool so that the module symbol table can refer to them...
341 EnumerateValueSymbolTable(M.getValueSymbolTable());
342 EnumerateNamedMetadata(M);
344 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
346 // Enumerate types used by function bodies and argument lists.
347 for (const Function &F : M) {
348 for (const Argument &A : F.args())
349 EnumerateType(A.getType());
351 // Enumerate metadata attached to this function.
352 F.getAllMetadata(MDs);
353 for (const auto &I : MDs)
354 EnumerateMetadata(I.second);
356 for (const BasicBlock &BB : F)
357 for (const Instruction &I : BB) {
358 for (const Use &Op : I.operands()) {
359 auto *MD = dyn_cast<MetadataAsValue>(&Op);
361 EnumerateOperandType(Op);
365 // Local metadata is enumerated during function-incorporation.
366 if (isa<LocalAsMetadata>(MD->getMetadata()))
369 EnumerateMetadata(MD->getMetadata());
371 EnumerateType(I.getType());
372 if (const CallInst *CI = dyn_cast<CallInst>(&I))
373 EnumerateAttributes(CI->getAttributes());
374 else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
375 EnumerateAttributes(II->getAttributes());
377 // Enumerate metadata attached with this instruction.
379 I.getAllMetadataOtherThanDebugLoc(MDs);
380 for (unsigned i = 0, e = MDs.size(); i != e; ++i)
381 EnumerateMetadata(MDs[i].second);
383 // Don't enumerate the location directly -- it has a special record
384 // type -- but enumerate its operands.
385 if (DILocation *L = I.getDebugLoc())
386 EnumerateMDNodeOperands(L);
390 // Optimize constant ordering.
391 OptimizeConstants(FirstConstant, Values.size());
394 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
395 InstructionMapType::const_iterator I = InstructionMap.find(Inst);
396 assert(I != InstructionMap.end() && "Instruction is not mapped!");
400 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
401 unsigned ComdatID = Comdats.idFor(C);
402 assert(ComdatID && "Comdat not found!");
406 void ValueEnumerator::setInstructionID(const Instruction *I) {
407 InstructionMap[I] = InstructionCount++;
410 unsigned ValueEnumerator::getValueID(const Value *V) const {
411 if (auto *MD = dyn_cast<MetadataAsValue>(V))
412 return getMetadataID(MD->getMetadata());
414 ValueMapType::const_iterator I = ValueMap.find(V);
415 assert(I != ValueMap.end() && "Value not in slotcalculator!");
419 void ValueEnumerator::dump() const {
420 print(dbgs(), ValueMap, "Default");
422 print(dbgs(), MDValueMap, "MetaData");
426 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
427 const char *Name) const {
429 OS << "Map Name: " << Name << "\n";
430 OS << "Size: " << Map.size() << "\n";
431 for (ValueMapType::const_iterator I = Map.begin(),
432 E = Map.end(); I != E; ++I) {
434 const Value *V = I->first;
436 OS << "Value: " << V->getName();
438 OS << "Value: [null]\n";
441 OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
442 for (const Use &U : V->uses()) {
443 if (&U != &*V->use_begin())
446 OS << " " << U->getName();
455 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
456 const char *Name) const {
458 OS << "Map Name: " << Name << "\n";
459 OS << "Size: " << Map.size() << "\n";
460 for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
461 const Metadata *MD = I->first;
462 OS << "Metadata: slot = " << I->second << "\n";
467 /// OptimizeConstants - Reorder constant pool for denser encoding.
468 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
469 if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
471 if (ShouldPreserveUseListOrder)
472 // Optimizing constants makes the use-list order difficult to predict.
473 // Disable it for now when trying to preserve the order.
476 std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
477 [this](const std::pair<const Value *, unsigned> &LHS,
478 const std::pair<const Value *, unsigned> &RHS) {
480 if (LHS.first->getType() != RHS.first->getType())
481 return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
482 // Then by frequency.
483 return LHS.second > RHS.second;
486 // Ensure that integer and vector of integer constants are at the start of the
487 // constant pool. This is important so that GEP structure indices come before
488 // gep constant exprs.
489 std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
490 isIntOrIntVectorValue);
492 // Rebuild the modified portion of ValueMap.
493 for (; CstStart != CstEnd; ++CstStart)
494 ValueMap[Values[CstStart].first] = CstStart+1;
498 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
499 /// table into the values table.
500 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
501 for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
503 EnumerateValue(VI->getValue());
506 /// Insert all of the values referenced by named metadata in the specified
508 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
509 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
510 E = M.named_metadata_end();
512 EnumerateNamedMDNode(I);
515 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
516 for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
517 EnumerateMetadata(MD->getOperand(i));
520 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
521 /// and types referenced by the given MDNode.
522 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
523 for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
524 Metadata *MD = N->getOperand(i);
527 assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
528 EnumerateMetadata(MD);
532 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
534 (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
535 "Invalid metadata kind");
537 // Insert a dummy ID to block the co-recursive call to
538 // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
540 // Return early if there's already an ID.
541 if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
544 // Visit operands first to minimize RAUW.
545 if (auto *N = dyn_cast<MDNode>(MD))
546 EnumerateMDNodeOperands(N);
547 else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
548 EnumerateValue(C->getValue());
550 HasMDString |= isa<MDString>(MD);
551 HasDILocation |= isa<DILocation>(MD);
552 HasGenericDINode |= isa<GenericDINode>(MD);
554 // Replace the dummy ID inserted above with the correct one. MDValueMap may
555 // have changed by inserting operands, so we need a fresh lookup here.
557 MDValueMap[MD] = MDs.size();
560 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
561 /// information reachable from the metadata.
562 void ValueEnumerator::EnumerateFunctionLocalMetadata(
563 const LocalAsMetadata *Local) {
564 // Check to see if it's already in!
565 unsigned &MDValueID = MDValueMap[Local];
569 MDs.push_back(Local);
570 MDValueID = MDs.size();
572 EnumerateValue(Local->getValue());
574 // Also, collect all function-local metadata for easy access.
575 FunctionLocalMDs.push_back(Local);
578 void ValueEnumerator::EnumerateValue(const Value *V) {
579 assert(!V->getType()->isVoidTy() && "Can't insert void values!");
580 assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
582 // Check to see if it's already in!
583 unsigned &ValueID = ValueMap[V];
585 // Increment use count.
586 Values[ValueID-1].second++;
590 if (auto *GO = dyn_cast<GlobalObject>(V))
591 if (const Comdat *C = GO->getComdat())
594 // Enumerate the type of this value.
595 EnumerateType(V->getType());
597 if (const Constant *C = dyn_cast<Constant>(V)) {
598 if (isa<GlobalValue>(C)) {
599 // Initializers for globals are handled explicitly elsewhere.
600 } else if (C->getNumOperands()) {
601 // If a constant has operands, enumerate them. This makes sure that if a
602 // constant has uses (for example an array of const ints), that they are
605 // We prefer to enumerate them with values before we enumerate the user
606 // itself. This makes it more likely that we can avoid forward references
607 // in the reader. We know that there can be no cycles in the constants
608 // graph that don't go through a global variable.
609 for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
611 if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
614 // Finally, add the value. Doing this could make the ValueID reference be
615 // dangling, don't reuse it.
616 Values.push_back(std::make_pair(V, 1U));
617 ValueMap[V] = Values.size();
623 Values.push_back(std::make_pair(V, 1U));
624 ValueID = Values.size();
628 void ValueEnumerator::EnumerateType(Type *Ty) {
629 unsigned *TypeID = &TypeMap[Ty];
631 // We've already seen this type.
635 // If it is a non-anonymous struct, mark the type as being visited so that we
636 // don't recursively visit it. This is safe because we allow forward
637 // references of these in the bitcode reader.
638 if (StructType *STy = dyn_cast<StructType>(Ty))
639 if (!STy->isLiteral())
642 // Enumerate all of the subtypes before we enumerate this type. This ensures
643 // that the type will be enumerated in an order that can be directly built.
644 for (Type *SubTy : Ty->subtypes())
645 EnumerateType(SubTy);
647 // Refresh the TypeID pointer in case the table rehashed.
648 TypeID = &TypeMap[Ty];
650 // Check to see if we got the pointer another way. This can happen when
651 // enumerating recursive types that hit the base case deeper than they start.
653 // If this is actually a struct that we are treating as forward ref'able,
654 // then emit the definition now that all of its contents are available.
655 if (*TypeID && *TypeID != ~0U)
658 // Add this type now that its contents are all happily enumerated.
661 *TypeID = Types.size();
664 // Enumerate the types for the specified value. If the value is a constant,
665 // walk through it, enumerating the types of the constant.
666 void ValueEnumerator::EnumerateOperandType(const Value *V) {
667 EnumerateType(V->getType());
669 if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
670 assert(!isa<LocalAsMetadata>(MD->getMetadata()) &&
671 "Function-local metadata should be left for later");
673 EnumerateMetadata(MD->getMetadata());
677 const Constant *C = dyn_cast<Constant>(V);
681 // If this constant is already enumerated, ignore it, we know its type must
683 if (ValueMap.count(C))
686 // This constant may have operands, make sure to enumerate the types in
688 for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
689 const Value *Op = C->getOperand(i);
691 // Don't enumerate basic blocks here, this happens as operands to
693 if (isa<BasicBlock>(Op))
696 EnumerateOperandType(Op);
700 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
701 if (PAL.isEmpty()) return; // null is always 0.
704 unsigned &Entry = AttributeMap[PAL];
706 // Never saw this before, add it.
707 Attribute.push_back(PAL);
708 Entry = Attribute.size();
711 // Do lookups for all attribute groups.
712 for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
713 AttributeSet AS = PAL.getSlotAttributes(i);
714 unsigned &Entry = AttributeGroupMap[AS];
716 AttributeGroups.push_back(AS);
717 Entry = AttributeGroups.size();
722 void ValueEnumerator::incorporateFunction(const Function &F) {
723 InstructionCount = 0;
724 NumModuleValues = Values.size();
725 NumModuleMDs = MDs.size();
727 // Adding function arguments to the value table.
728 for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
732 FirstFuncConstantID = Values.size();
734 // Add all function-level constants to the value table.
735 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
736 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
737 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
739 if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
743 BasicBlocks.push_back(BB);
744 ValueMap[BB] = BasicBlocks.size();
747 // Optimize the constant layout.
748 OptimizeConstants(FirstFuncConstantID, Values.size());
750 // Add the function's parameter attributes so they are available for use in
751 // the function's instruction.
752 EnumerateAttributes(F.getAttributes());
754 FirstInstID = Values.size();
756 SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
757 // Add all of the instructions.
758 for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
759 for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
760 for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
762 if (auto *MD = dyn_cast<MetadataAsValue>(&*OI))
763 if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
764 // Enumerate metadata after the instructions they might refer to.
765 FnLocalMDVector.push_back(Local);
768 if (!I->getType()->isVoidTy())
773 // Add all of the function-local metadata.
774 for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
775 EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
778 void ValueEnumerator::purgeFunction() {
779 /// Remove purged values from the ValueMap.
780 for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
781 ValueMap.erase(Values[i].first);
782 for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
783 MDValueMap.erase(MDs[i]);
784 for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
785 ValueMap.erase(BasicBlocks[i]);
787 Values.resize(NumModuleValues);
788 MDs.resize(NumModuleMDs);
790 FunctionLocalMDs.clear();
793 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
794 DenseMap<const BasicBlock*, unsigned> &IDMap) {
795 unsigned Counter = 0;
796 for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
797 IDMap[BB] = ++Counter;
800 /// getGlobalBasicBlockID - This returns the function-specific ID for the
801 /// specified basic block. This is relatively expensive information, so it
802 /// should only be used by rare constructs such as address-of-label.
803 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
804 unsigned &Idx = GlobalBasicBlockIDs[BB];
808 IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
809 return getGlobalBasicBlockID(BB);
812 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
813 return Log2_32_Ceil(getTypes().size() + 1);