LLVM API Documentation

ValueEnumerator.cpp
Go to the documentation of this file.
00001 //===-- ValueEnumerator.cpp - Number values and types for bitcode writer --===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file implements the ValueEnumerator class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "ValueEnumerator.h"
00015 #include "llvm/ADT/STLExtras.h"
00016 #include "llvm/ADT/SmallPtrSet.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/DebugInfoMetadata.h"
00019 #include "llvm/IR/DerivedTypes.h"
00020 #include "llvm/IR/Instructions.h"
00021 #include "llvm/IR/Module.h"
00022 #include "llvm/IR/UseListOrder.h"
00023 #include "llvm/IR/ValueSymbolTable.h"
00024 #include "llvm/Support/Debug.h"
00025 #include "llvm/Support/raw_ostream.h"
00026 #include <algorithm>
00027 using namespace llvm;
00028 
00029 namespace {
00030 struct OrderMap {
00031   DenseMap<const Value *, std::pair<unsigned, bool>> IDs;
00032   unsigned LastGlobalConstantID;
00033   unsigned LastGlobalValueID;
00034 
00035   OrderMap() : LastGlobalConstantID(0), LastGlobalValueID(0) {}
00036 
00037   bool isGlobalConstant(unsigned ID) const {
00038     return ID <= LastGlobalConstantID;
00039   }
00040   bool isGlobalValue(unsigned ID) const {
00041     return ID <= LastGlobalValueID && !isGlobalConstant(ID);
00042   }
00043 
00044   unsigned size() const { return IDs.size(); }
00045   std::pair<unsigned, bool> &operator[](const Value *V) { return IDs[V]; }
00046   std::pair<unsigned, bool> lookup(const Value *V) const {
00047     return IDs.lookup(V);
00048   }
00049   void index(const Value *V) {
00050     // Explicitly sequence get-size and insert-value operations to avoid UB.
00051     unsigned ID = IDs.size() + 1;
00052     IDs[V].first = ID;
00053   }
00054 };
00055 }
00056 
00057 static void orderValue(const Value *V, OrderMap &OM) {
00058   if (OM.lookup(V).first)
00059     return;
00060 
00061   if (const Constant *C = dyn_cast<Constant>(V))
00062     if (C->getNumOperands() && !isa<GlobalValue>(C))
00063       for (const Value *Op : C->operands())
00064         if (!isa<BasicBlock>(Op) && !isa<GlobalValue>(Op))
00065           orderValue(Op, OM);
00066 
00067   // Note: we cannot cache this lookup above, since inserting into the map
00068   // changes the map's size, and thus affects the other IDs.
00069   OM.index(V);
00070 }
00071 
00072 static OrderMap orderModule(const Module &M) {
00073   // This needs to match the order used by ValueEnumerator::ValueEnumerator()
00074   // and ValueEnumerator::incorporateFunction().
00075   OrderMap OM;
00076 
00077   // In the reader, initializers of GlobalValues are set *after* all the
00078   // globals have been read.  Rather than awkwardly modeling this behaviour
00079   // directly in predictValueUseListOrderImpl(), just assign IDs to
00080   // initializers of GlobalValues before GlobalValues themselves to model this
00081   // implicitly.
00082   for (const GlobalVariable &G : M.globals())
00083     if (G.hasInitializer())
00084       if (!isa<GlobalValue>(G.getInitializer()))
00085         orderValue(G.getInitializer(), OM);
00086   for (const GlobalAlias &A : M.aliases())
00087     if (!isa<GlobalValue>(A.getAliasee()))
00088       orderValue(A.getAliasee(), OM);
00089   for (const Function &F : M) {
00090     if (F.hasPrefixData())
00091       if (!isa<GlobalValue>(F.getPrefixData()))
00092         orderValue(F.getPrefixData(), OM);
00093     if (F.hasPrologueData())
00094       if (!isa<GlobalValue>(F.getPrologueData()))
00095         orderValue(F.getPrologueData(), OM);
00096   }
00097   OM.LastGlobalConstantID = OM.size();
00098 
00099   // Initializers of GlobalValues are processed in
00100   // BitcodeReader::ResolveGlobalAndAliasInits().  Match the order there rather
00101   // than ValueEnumerator, and match the code in predictValueUseListOrderImpl()
00102   // by giving IDs in reverse order.
00103   //
00104   // Since GlobalValues never reference each other directly (just through
00105   // initializers), their relative IDs only matter for determining order of
00106   // uses in their initializers.
00107   for (const Function &F : M)
00108     orderValue(&F, OM);
00109   for (const GlobalAlias &A : M.aliases())
00110     orderValue(&A, OM);
00111   for (const GlobalVariable &G : M.globals())
00112     orderValue(&G, OM);
00113   OM.LastGlobalValueID = OM.size();
00114 
00115   for (const Function &F : M) {
00116     if (F.isDeclaration())
00117       continue;
00118     // Here we need to match the union of ValueEnumerator::incorporateFunction()
00119     // and WriteFunction().  Basic blocks are implicitly declared before
00120     // anything else (by declaring their size).
00121     for (const BasicBlock &BB : F)
00122       orderValue(&BB, OM);
00123     for (const Argument &A : F.args())
00124       orderValue(&A, OM);
00125     for (const BasicBlock &BB : F)
00126       for (const Instruction &I : BB)
00127         for (const Value *Op : I.operands())
00128           if ((isa<Constant>(*Op) && !isa<GlobalValue>(*Op)) ||
00129               isa<InlineAsm>(*Op))
00130             orderValue(Op, OM);
00131     for (const BasicBlock &BB : F)
00132       for (const Instruction &I : BB)
00133         orderValue(&I, OM);
00134   }
00135   return OM;
00136 }
00137 
00138 static void predictValueUseListOrderImpl(const Value *V, const Function *F,
00139                                          unsigned ID, const OrderMap &OM,
00140                                          UseListOrderStack &Stack) {
00141   // Predict use-list order for this one.
00142   typedef std::pair<const Use *, unsigned> Entry;
00143   SmallVector<Entry, 64> List;
00144   for (const Use &U : V->uses())
00145     // Check if this user will be serialized.
00146     if (OM.lookup(U.getUser()).first)
00147       List.push_back(std::make_pair(&U, List.size()));
00148 
00149   if (List.size() < 2)
00150     // We may have lost some users.
00151     return;
00152 
00153   bool IsGlobalValue = OM.isGlobalValue(ID);
00154   std::sort(List.begin(), List.end(), [&](const Entry &L, const Entry &R) {
00155     const Use *LU = L.first;
00156     const Use *RU = R.first;
00157     if (LU == RU)
00158       return false;
00159 
00160     auto LID = OM.lookup(LU->getUser()).first;
00161     auto RID = OM.lookup(RU->getUser()).first;
00162 
00163     // Global values are processed in reverse order.
00164     //
00165     // Moreover, initializers of GlobalValues are set *after* all the globals
00166     // have been read (despite having earlier IDs).  Rather than awkwardly
00167     // modeling this behaviour here, orderModule() has assigned IDs to
00168     // initializers of GlobalValues before GlobalValues themselves.
00169     if (OM.isGlobalValue(LID) && OM.isGlobalValue(RID))
00170       return LID < RID;
00171 
00172     // If ID is 4, then expect: 7 6 5 1 2 3.
00173     if (LID < RID) {
00174       if (RID <= ID)
00175         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00176           return true;
00177       return false;
00178     }
00179     if (RID < LID) {
00180       if (LID <= ID)
00181         if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00182           return false;
00183       return true;
00184     }
00185 
00186     // LID and RID are equal, so we have different operands of the same user.
00187     // Assume operands are added in order for all instructions.
00188     if (LID <= ID)
00189       if (!IsGlobalValue) // GlobalValue uses don't get reversed.
00190         return LU->getOperandNo() < RU->getOperandNo();
00191     return LU->getOperandNo() > RU->getOperandNo();
00192   });
00193 
00194   if (std::is_sorted(
00195           List.begin(), List.end(),
00196           [](const Entry &L, const Entry &R) { return L.second < R.second; }))
00197     // Order is already correct.
00198     return;
00199 
00200   // Store the shuffle.
00201   Stack.emplace_back(V, F, List.size());
00202   assert(List.size() == Stack.back().Shuffle.size() && "Wrong size");
00203   for (size_t I = 0, E = List.size(); I != E; ++I)
00204     Stack.back().Shuffle[I] = List[I].second;
00205 }
00206 
00207 static void predictValueUseListOrder(const Value *V, const Function *F,
00208                                      OrderMap &OM, UseListOrderStack &Stack) {
00209   auto &IDPair = OM[V];
00210   assert(IDPair.first && "Unmapped value");
00211   if (IDPair.second)
00212     // Already predicted.
00213     return;
00214 
00215   // Do the actual prediction.
00216   IDPair.second = true;
00217   if (!V->use_empty() && std::next(V->use_begin()) != V->use_end())
00218     predictValueUseListOrderImpl(V, F, IDPair.first, OM, Stack);
00219 
00220   // Recursive descent into constants.
00221   if (const Constant *C = dyn_cast<Constant>(V))
00222     if (C->getNumOperands()) // Visit GlobalValues.
00223       for (const Value *Op : C->operands())
00224         if (isa<Constant>(Op)) // Visit GlobalValues.
00225           predictValueUseListOrder(Op, F, OM, Stack);
00226 }
00227 
00228 static UseListOrderStack predictUseListOrder(const Module &M) {
00229   OrderMap OM = orderModule(M);
00230 
00231   // Use-list orders need to be serialized after all the users have been added
00232   // to a value, or else the shuffles will be incomplete.  Store them per
00233   // function in a stack.
00234   //
00235   // Aside from function order, the order of values doesn't matter much here.
00236   UseListOrderStack Stack;
00237 
00238   // We want to visit the functions backward now so we can list function-local
00239   // constants in the last Function they're used in.  Module-level constants
00240   // have already been visited above.
00241   for (auto I = M.rbegin(), E = M.rend(); I != E; ++I) {
00242     const Function &F = *I;
00243     if (F.isDeclaration())
00244       continue;
00245     for (const BasicBlock &BB : F)
00246       predictValueUseListOrder(&BB, &F, OM, Stack);
00247     for (const Argument &A : F.args())
00248       predictValueUseListOrder(&A, &F, OM, Stack);
00249     for (const BasicBlock &BB : F)
00250       for (const Instruction &I : BB)
00251         for (const Value *Op : I.operands())
00252           if (isa<Constant>(*Op) || isa<InlineAsm>(*Op)) // Visit GlobalValues.
00253             predictValueUseListOrder(Op, &F, OM, Stack);
00254     for (const BasicBlock &BB : F)
00255       for (const Instruction &I : BB)
00256         predictValueUseListOrder(&I, &F, OM, Stack);
00257   }
00258 
00259   // Visit globals last, since the module-level use-list block will be seen
00260   // before the function bodies are processed.
00261   for (const GlobalVariable &G : M.globals())
00262     predictValueUseListOrder(&G, nullptr, OM, Stack);
00263   for (const Function &F : M)
00264     predictValueUseListOrder(&F, nullptr, OM, Stack);
00265   for (const GlobalAlias &A : M.aliases())
00266     predictValueUseListOrder(&A, nullptr, OM, Stack);
00267   for (const GlobalVariable &G : M.globals())
00268     if (G.hasInitializer())
00269       predictValueUseListOrder(G.getInitializer(), nullptr, OM, Stack);
00270   for (const GlobalAlias &A : M.aliases())
00271     predictValueUseListOrder(A.getAliasee(), nullptr, OM, Stack);
00272   for (const Function &F : M) {
00273     if (F.hasPrefixData())
00274       predictValueUseListOrder(F.getPrefixData(), nullptr, OM, Stack);
00275     if (F.hasPrologueData())
00276       predictValueUseListOrder(F.getPrologueData(), nullptr, OM, Stack);
00277   }
00278 
00279   return Stack;
00280 }
00281 
00282 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
00283   return V.first->getType()->isIntOrIntVectorTy();
00284 }
00285 
00286 ValueEnumerator::ValueEnumerator(const Module &M)
00287     : HasMDString(false), HasMDLocation(false), HasGenericDebugNode(false) {
00288   if (shouldPreserveBitcodeUseListOrder())
00289     UseListOrders = predictUseListOrder(M);
00290 
00291   // Enumerate the global variables.
00292   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00293        I != E; ++I)
00294     EnumerateValue(I);
00295 
00296   // Enumerate the functions.
00297   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
00298     EnumerateValue(I);
00299     EnumerateAttributes(cast<Function>(I)->getAttributes());
00300   }
00301 
00302   // Enumerate the aliases.
00303   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
00304        I != E; ++I)
00305     EnumerateValue(I);
00306 
00307   // Remember what is the cutoff between globalvalue's and other constants.
00308   unsigned FirstConstant = Values.size();
00309 
00310   // Enumerate the global variable initializers.
00311   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00312        I != E; ++I)
00313     if (I->hasInitializer())
00314       EnumerateValue(I->getInitializer());
00315 
00316   // Enumerate the aliasees.
00317   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
00318        I != E; ++I)
00319     EnumerateValue(I->getAliasee());
00320 
00321   // Enumerate the prefix data constants.
00322   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
00323     if (I->hasPrefixData())
00324       EnumerateValue(I->getPrefixData());
00325 
00326   // Enumerate the prologue data constants.
00327   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
00328     if (I->hasPrologueData())
00329       EnumerateValue(I->getPrologueData());
00330 
00331   // Enumerate the metadata type.
00332   //
00333   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
00334   // only encodes the metadata type when it's used as a value.
00335   EnumerateType(Type::getMetadataTy(M.getContext()));
00336 
00337   // Insert constants and metadata that are named at module level into the slot
00338   // pool so that the module symbol table can refer to them...
00339   EnumerateValueSymbolTable(M.getValueSymbolTable());
00340   EnumerateNamedMetadata(M);
00341 
00342   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
00343 
00344   // Enumerate types used by function bodies and argument lists.
00345   for (const Function &F : M) {
00346     for (const Argument &A : F.args())
00347       EnumerateType(A.getType());
00348 
00349     for (const BasicBlock &BB : F)
00350       for (const Instruction &I : BB) {
00351         for (const Use &Op : I.operands()) {
00352           auto *MD = dyn_cast<MetadataAsValue>(&Op);
00353           if (!MD) {
00354             EnumerateOperandType(Op);
00355             continue;
00356           }
00357 
00358           // Local metadata is enumerated during function-incorporation.
00359           if (isa<LocalAsMetadata>(MD->getMetadata()))
00360             continue;
00361 
00362           EnumerateMetadata(MD->getMetadata());
00363         }
00364         EnumerateType(I.getType());
00365         if (const CallInst *CI = dyn_cast<CallInst>(&I))
00366           EnumerateAttributes(CI->getAttributes());
00367         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
00368           EnumerateAttributes(II->getAttributes());
00369 
00370         // Enumerate metadata attached with this instruction.
00371         MDs.clear();
00372         I.getAllMetadataOtherThanDebugLoc(MDs);
00373         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
00374           EnumerateMetadata(MDs[i].second);
00375 
00376         if (!I.getDebugLoc().isUnknown()) {
00377           MDNode *Scope, *IA;
00378           I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
00379           if (Scope) EnumerateMetadata(Scope);
00380           if (IA) EnumerateMetadata(IA);
00381         }
00382       }
00383   }
00384 
00385   // Optimize constant ordering.
00386   OptimizeConstants(FirstConstant, Values.size());
00387 }
00388 
00389 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
00390   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
00391   assert(I != InstructionMap.end() && "Instruction is not mapped!");
00392   return I->second;
00393 }
00394 
00395 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
00396   unsigned ComdatID = Comdats.idFor(C);
00397   assert(ComdatID && "Comdat not found!");
00398   return ComdatID;
00399 }
00400 
00401 void ValueEnumerator::setInstructionID(const Instruction *I) {
00402   InstructionMap[I] = InstructionCount++;
00403 }
00404 
00405 unsigned ValueEnumerator::getValueID(const Value *V) const {
00406   if (auto *MD = dyn_cast<MetadataAsValue>(V))
00407     return getMetadataID(MD->getMetadata());
00408 
00409   ValueMapType::const_iterator I = ValueMap.find(V);
00410   assert(I != ValueMap.end() && "Value not in slotcalculator!");
00411   return I->second-1;
00412 }
00413 
00414 void ValueEnumerator::dump() const {
00415   print(dbgs(), ValueMap, "Default");
00416   dbgs() << '\n';
00417   print(dbgs(), MDValueMap, "MetaData");
00418   dbgs() << '\n';
00419 }
00420 
00421 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
00422                             const char *Name) const {
00423 
00424   OS << "Map Name: " << Name << "\n";
00425   OS << "Size: " << Map.size() << "\n";
00426   for (ValueMapType::const_iterator I = Map.begin(),
00427          E = Map.end(); I != E; ++I) {
00428 
00429     const Value *V = I->first;
00430     if (V->hasName())
00431       OS << "Value: " << V->getName();
00432     else
00433       OS << "Value: [null]\n";
00434     V->dump();
00435 
00436     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
00437     for (const Use &U : V->uses()) {
00438       if (&U != &*V->use_begin())
00439         OS << ",";
00440       if(U->hasName())
00441         OS << " " << U->getName();
00442       else
00443         OS << " [null]";
00444 
00445     }
00446     OS <<  "\n\n";
00447   }
00448 }
00449 
00450 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
00451                             const char *Name) const {
00452 
00453   OS << "Map Name: " << Name << "\n";
00454   OS << "Size: " << Map.size() << "\n";
00455   for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
00456     const Metadata *MD = I->first;
00457     OS << "Metadata: slot = " << I->second << "\n";
00458     MD->print(OS);
00459   }
00460 }
00461 
00462 /// OptimizeConstants - Reorder constant pool for denser encoding.
00463 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
00464   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
00465 
00466   if (shouldPreserveBitcodeUseListOrder())
00467     // Optimizing constants makes the use-list order difficult to predict.
00468     // Disable it for now when trying to preserve the order.
00469     return;
00470 
00471   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
00472                    [this](const std::pair<const Value *, unsigned> &LHS,
00473                           const std::pair<const Value *, unsigned> &RHS) {
00474     // Sort by plane.
00475     if (LHS.first->getType() != RHS.first->getType())
00476       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
00477     // Then by frequency.
00478     return LHS.second > RHS.second;
00479   });
00480 
00481   // Ensure that integer and vector of integer constants are at the start of the
00482   // constant pool.  This is important so that GEP structure indices come before
00483   // gep constant exprs.
00484   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
00485                  isIntOrIntVectorValue);
00486 
00487   // Rebuild the modified portion of ValueMap.
00488   for (; CstStart != CstEnd; ++CstStart)
00489     ValueMap[Values[CstStart].first] = CstStart+1;
00490 }
00491 
00492 
00493 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
00494 /// table into the values table.
00495 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
00496   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
00497        VI != VE; ++VI)
00498     EnumerateValue(VI->getValue());
00499 }
00500 
00501 /// Insert all of the values referenced by named metadata in the specified
00502 /// module.
00503 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
00504   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
00505                                              E = M.named_metadata_end();
00506        I != E; ++I)
00507     EnumerateNamedMDNode(I);
00508 }
00509 
00510 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
00511   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
00512     EnumerateMetadata(MD->getOperand(i));
00513 }
00514 
00515 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
00516 /// and types referenced by the given MDNode.
00517 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
00518   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00519     Metadata *MD = N->getOperand(i);
00520     if (!MD)
00521       continue;
00522     assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
00523     EnumerateMetadata(MD);
00524   }
00525 }
00526 
00527 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
00528   assert(
00529       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
00530       "Invalid metadata kind");
00531 
00532   // Insert a dummy ID to block the co-recursive call to
00533   // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
00534   //
00535   // Return early if there's already an ID.
00536   if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
00537     return;
00538 
00539   // Visit operands first to minimize RAUW.
00540   if (auto *N = dyn_cast<MDNode>(MD))
00541     EnumerateMDNodeOperands(N);
00542   else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
00543     EnumerateValue(C->getValue());
00544 
00545   HasMDString |= isa<MDString>(MD);
00546   HasMDLocation |= isa<MDLocation>(MD);
00547   HasGenericDebugNode |= isa<GenericDebugNode>(MD);
00548 
00549   // Replace the dummy ID inserted above with the correct one.  MDValueMap may
00550   // have changed by inserting operands, so we need a fresh lookup here.
00551   MDs.push_back(MD);
00552   MDValueMap[MD] = MDs.size();
00553 }
00554 
00555 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
00556 /// information reachable from the metadata.
00557 void ValueEnumerator::EnumerateFunctionLocalMetadata(
00558     const LocalAsMetadata *Local) {
00559   // Check to see if it's already in!
00560   unsigned &MDValueID = MDValueMap[Local];
00561   if (MDValueID)
00562     return;
00563 
00564   MDs.push_back(Local);
00565   MDValueID = MDs.size();
00566 
00567   EnumerateValue(Local->getValue());
00568 
00569   // Also, collect all function-local metadata for easy access.
00570   FunctionLocalMDs.push_back(Local);
00571 }
00572 
00573 void ValueEnumerator::EnumerateValue(const Value *V) {
00574   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
00575   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
00576 
00577   // Check to see if it's already in!
00578   unsigned &ValueID = ValueMap[V];
00579   if (ValueID) {
00580     // Increment use count.
00581     Values[ValueID-1].second++;
00582     return;
00583   }
00584 
00585   if (auto *GO = dyn_cast<GlobalObject>(V))
00586     if (const Comdat *C = GO->getComdat())
00587       Comdats.insert(C);
00588 
00589   // Enumerate the type of this value.
00590   EnumerateType(V->getType());
00591 
00592   if (const Constant *C = dyn_cast<Constant>(V)) {
00593     if (isa<GlobalValue>(C)) {
00594       // Initializers for globals are handled explicitly elsewhere.
00595     } else if (C->getNumOperands()) {
00596       // If a constant has operands, enumerate them.  This makes sure that if a
00597       // constant has uses (for example an array of const ints), that they are
00598       // inserted also.
00599 
00600       // We prefer to enumerate them with values before we enumerate the user
00601       // itself.  This makes it more likely that we can avoid forward references
00602       // in the reader.  We know that there can be no cycles in the constants
00603       // graph that don't go through a global variable.
00604       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
00605            I != E; ++I)
00606         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
00607           EnumerateValue(*I);
00608 
00609       // Finally, add the value.  Doing this could make the ValueID reference be
00610       // dangling, don't reuse it.
00611       Values.push_back(std::make_pair(V, 1U));
00612       ValueMap[V] = Values.size();
00613       return;
00614     }
00615   }
00616 
00617   // Add the value.
00618   Values.push_back(std::make_pair(V, 1U));
00619   ValueID = Values.size();
00620 }
00621 
00622 
00623 void ValueEnumerator::EnumerateType(Type *Ty) {
00624   unsigned *TypeID = &TypeMap[Ty];
00625 
00626   // We've already seen this type.
00627   if (*TypeID)
00628     return;
00629 
00630   // If it is a non-anonymous struct, mark the type as being visited so that we
00631   // don't recursively visit it.  This is safe because we allow forward
00632   // references of these in the bitcode reader.
00633   if (StructType *STy = dyn_cast<StructType>(Ty))
00634     if (!STy->isLiteral())
00635       *TypeID = ~0U;
00636 
00637   // Enumerate all of the subtypes before we enumerate this type.  This ensures
00638   // that the type will be enumerated in an order that can be directly built.
00639   for (Type *SubTy : Ty->subtypes())
00640     EnumerateType(SubTy);
00641 
00642   // Refresh the TypeID pointer in case the table rehashed.
00643   TypeID = &TypeMap[Ty];
00644 
00645   // Check to see if we got the pointer another way.  This can happen when
00646   // enumerating recursive types that hit the base case deeper than they start.
00647   //
00648   // If this is actually a struct that we are treating as forward ref'able,
00649   // then emit the definition now that all of its contents are available.
00650   if (*TypeID && *TypeID != ~0U)
00651     return;
00652 
00653   // Add this type now that its contents are all happily enumerated.
00654   Types.push_back(Ty);
00655 
00656   *TypeID = Types.size();
00657 }
00658 
00659 // Enumerate the types for the specified value.  If the value is a constant,
00660 // walk through it, enumerating the types of the constant.
00661 void ValueEnumerator::EnumerateOperandType(const Value *V) {
00662   EnumerateType(V->getType());
00663 
00664   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
00665     assert(!isa<LocalAsMetadata>(MD->getMetadata()) &&
00666            "Function-local metadata should be left for later");
00667 
00668     EnumerateMetadata(MD->getMetadata());
00669     return;
00670   }
00671 
00672   const Constant *C = dyn_cast<Constant>(V);
00673   if (!C)
00674     return;
00675 
00676   // If this constant is already enumerated, ignore it, we know its type must
00677   // be enumerated.
00678   if (ValueMap.count(C))
00679     return;
00680 
00681   // This constant may have operands, make sure to enumerate the types in
00682   // them.
00683   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00684     const Value *Op = C->getOperand(i);
00685 
00686     // Don't enumerate basic blocks here, this happens as operands to
00687     // blockaddress.
00688     if (isa<BasicBlock>(Op))
00689       continue;
00690 
00691     EnumerateOperandType(Op);
00692   }
00693 }
00694 
00695 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
00696   if (PAL.isEmpty()) return;  // null is always 0.
00697 
00698   // Do a lookup.
00699   unsigned &Entry = AttributeMap[PAL];
00700   if (Entry == 0) {
00701     // Never saw this before, add it.
00702     Attribute.push_back(PAL);
00703     Entry = Attribute.size();
00704   }
00705 
00706   // Do lookups for all attribute groups.
00707   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
00708     AttributeSet AS = PAL.getSlotAttributes(i);
00709     unsigned &Entry = AttributeGroupMap[AS];
00710     if (Entry == 0) {
00711       AttributeGroups.push_back(AS);
00712       Entry = AttributeGroups.size();
00713     }
00714   }
00715 }
00716 
00717 void ValueEnumerator::incorporateFunction(const Function &F) {
00718   InstructionCount = 0;
00719   NumModuleValues = Values.size();
00720   NumModuleMDs = MDs.size();
00721 
00722   // Adding function arguments to the value table.
00723   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
00724        I != E; ++I)
00725     EnumerateValue(I);
00726 
00727   FirstFuncConstantID = Values.size();
00728 
00729   // Add all function-level constants to the value table.
00730   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00731     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
00732       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00733            OI != E; ++OI) {
00734         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
00735             isa<InlineAsm>(*OI))
00736           EnumerateValue(*OI);
00737       }
00738     BasicBlocks.push_back(BB);
00739     ValueMap[BB] = BasicBlocks.size();
00740   }
00741 
00742   // Optimize the constant layout.
00743   OptimizeConstants(FirstFuncConstantID, Values.size());
00744 
00745   // Add the function's parameter attributes so they are available for use in
00746   // the function's instruction.
00747   EnumerateAttributes(F.getAttributes());
00748 
00749   FirstInstID = Values.size();
00750 
00751   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
00752   // Add all of the instructions.
00753   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00754     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
00755       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00756            OI != E; ++OI) {
00757         if (auto *MD = dyn_cast<MetadataAsValue>(&*OI))
00758           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
00759             // Enumerate metadata after the instructions they might refer to.
00760             FnLocalMDVector.push_back(Local);
00761       }
00762 
00763       if (!I->getType()->isVoidTy())
00764         EnumerateValue(I);
00765     }
00766   }
00767 
00768   // Add all of the function-local metadata.
00769   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
00770     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
00771 }
00772 
00773 void ValueEnumerator::purgeFunction() {
00774   /// Remove purged values from the ValueMap.
00775   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
00776     ValueMap.erase(Values[i].first);
00777   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
00778     MDValueMap.erase(MDs[i]);
00779   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
00780     ValueMap.erase(BasicBlocks[i]);
00781 
00782   Values.resize(NumModuleValues);
00783   MDs.resize(NumModuleMDs);
00784   BasicBlocks.clear();
00785   FunctionLocalMDs.clear();
00786 }
00787 
00788 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
00789                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
00790   unsigned Counter = 0;
00791   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00792     IDMap[BB] = ++Counter;
00793 }
00794 
00795 /// getGlobalBasicBlockID - This returns the function-specific ID for the
00796 /// specified basic block.  This is relatively expensive information, so it
00797 /// should only be used by rare constructs such as address-of-label.
00798 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
00799   unsigned &Idx = GlobalBasicBlockIDs[BB];
00800   if (Idx != 0)
00801     return Idx-1;
00802 
00803   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
00804   return getGlobalBasicBlockID(BB);
00805 }
00806 
00807 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
00808   return Log2_32_Ceil(getTypes().size() + 1);
00809 }