LLVM  mainline
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                                  bool ShouldPreserveUseListOrder)
00288     : HasMDString(false), HasMDLocation(false), HasGenericDebugNode(false),
00289       ShouldPreserveUseListOrder(ShouldPreserveUseListOrder) {
00290   if (ShouldPreserveUseListOrder)
00291     UseListOrders = predictUseListOrder(M);
00292 
00293   // Enumerate the global variables.
00294   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00295        I != E; ++I)
00296     EnumerateValue(I);
00297 
00298   // Enumerate the functions.
00299   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) {
00300     EnumerateValue(I);
00301     EnumerateAttributes(cast<Function>(I)->getAttributes());
00302   }
00303 
00304   // Enumerate the aliases.
00305   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
00306        I != E; ++I)
00307     EnumerateValue(I);
00308 
00309   // Remember what is the cutoff between globalvalue's and other constants.
00310   unsigned FirstConstant = Values.size();
00311 
00312   // Enumerate the global variable initializers.
00313   for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
00314        I != E; ++I)
00315     if (I->hasInitializer())
00316       EnumerateValue(I->getInitializer());
00317 
00318   // Enumerate the aliasees.
00319   for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
00320        I != E; ++I)
00321     EnumerateValue(I->getAliasee());
00322 
00323   // Enumerate the prefix data constants.
00324   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
00325     if (I->hasPrefixData())
00326       EnumerateValue(I->getPrefixData());
00327 
00328   // Enumerate the prologue data constants.
00329   for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I)
00330     if (I->hasPrologueData())
00331       EnumerateValue(I->getPrologueData());
00332 
00333   // Enumerate the metadata type.
00334   //
00335   // TODO: Move this to ValueEnumerator::EnumerateOperandType() once bitcode
00336   // only encodes the metadata type when it's used as a value.
00337   EnumerateType(Type::getMetadataTy(M.getContext()));
00338 
00339   // Insert constants and metadata that are named at module level into the slot
00340   // pool so that the module symbol table can refer to them...
00341   EnumerateValueSymbolTable(M.getValueSymbolTable());
00342   EnumerateNamedMetadata(M);
00343 
00344   SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
00345 
00346   // Enumerate types used by function bodies and argument lists.
00347   for (const Function &F : M) {
00348     for (const Argument &A : F.args())
00349       EnumerateType(A.getType());
00350 
00351     // Enumerate metadata attached to this function.
00352     F.getAllMetadata(MDs);
00353     for (const auto &I : MDs)
00354       EnumerateMetadata(I.second);
00355 
00356     for (const BasicBlock &BB : F)
00357       for (const Instruction &I : BB) {
00358         for (const Use &Op : I.operands()) {
00359           auto *MD = dyn_cast<MetadataAsValue>(&Op);
00360           if (!MD) {
00361             EnumerateOperandType(Op);
00362             continue;
00363           }
00364 
00365           // Local metadata is enumerated during function-incorporation.
00366           if (isa<LocalAsMetadata>(MD->getMetadata()))
00367             continue;
00368 
00369           EnumerateMetadata(MD->getMetadata());
00370         }
00371         EnumerateType(I.getType());
00372         if (const CallInst *CI = dyn_cast<CallInst>(&I))
00373           EnumerateAttributes(CI->getAttributes());
00374         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
00375           EnumerateAttributes(II->getAttributes());
00376 
00377         // Enumerate metadata attached with this instruction.
00378         MDs.clear();
00379         I.getAllMetadataOtherThanDebugLoc(MDs);
00380         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
00381           EnumerateMetadata(MDs[i].second);
00382 
00383         // Don't enumerate the location directly -- it has a special record
00384         // type -- but enumerate its operands.
00385         if (MDLocation *L = I.getDebugLoc())
00386           EnumerateMDNodeOperands(L);
00387       }
00388   }
00389 
00390   // Optimize constant ordering.
00391   OptimizeConstants(FirstConstant, Values.size());
00392 }
00393 
00394 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
00395   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
00396   assert(I != InstructionMap.end() && "Instruction is not mapped!");
00397   return I->second;
00398 }
00399 
00400 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
00401   unsigned ComdatID = Comdats.idFor(C);
00402   assert(ComdatID && "Comdat not found!");
00403   return ComdatID;
00404 }
00405 
00406 void ValueEnumerator::setInstructionID(const Instruction *I) {
00407   InstructionMap[I] = InstructionCount++;
00408 }
00409 
00410 unsigned ValueEnumerator::getValueID(const Value *V) const {
00411   if (auto *MD = dyn_cast<MetadataAsValue>(V))
00412     return getMetadataID(MD->getMetadata());
00413 
00414   ValueMapType::const_iterator I = ValueMap.find(V);
00415   assert(I != ValueMap.end() && "Value not in slotcalculator!");
00416   return I->second-1;
00417 }
00418 
00419 void ValueEnumerator::dump() const {
00420   print(dbgs(), ValueMap, "Default");
00421   dbgs() << '\n';
00422   print(dbgs(), MDValueMap, "MetaData");
00423   dbgs() << '\n';
00424 }
00425 
00426 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
00427                             const char *Name) const {
00428 
00429   OS << "Map Name: " << Name << "\n";
00430   OS << "Size: " << Map.size() << "\n";
00431   for (ValueMapType::const_iterator I = Map.begin(),
00432          E = Map.end(); I != E; ++I) {
00433 
00434     const Value *V = I->first;
00435     if (V->hasName())
00436       OS << "Value: " << V->getName();
00437     else
00438       OS << "Value: [null]\n";
00439     V->dump();
00440 
00441     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
00442     for (const Use &U : V->uses()) {
00443       if (&U != &*V->use_begin())
00444         OS << ",";
00445       if(U->hasName())
00446         OS << " " << U->getName();
00447       else
00448         OS << " [null]";
00449 
00450     }
00451     OS <<  "\n\n";
00452   }
00453 }
00454 
00455 void ValueEnumerator::print(raw_ostream &OS, const MetadataMapType &Map,
00456                             const char *Name) const {
00457 
00458   OS << "Map Name: " << Name << "\n";
00459   OS << "Size: " << Map.size() << "\n";
00460   for (auto I = Map.begin(), E = Map.end(); I != E; ++I) {
00461     const Metadata *MD = I->first;
00462     OS << "Metadata: slot = " << I->second << "\n";
00463     MD->print(OS);
00464   }
00465 }
00466 
00467 /// OptimizeConstants - Reorder constant pool for denser encoding.
00468 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
00469   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
00470 
00471   if (ShouldPreserveUseListOrder)
00472     // Optimizing constants makes the use-list order difficult to predict.
00473     // Disable it for now when trying to preserve the order.
00474     return;
00475 
00476   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
00477                    [this](const std::pair<const Value *, unsigned> &LHS,
00478                           const std::pair<const Value *, unsigned> &RHS) {
00479     // Sort by plane.
00480     if (LHS.first->getType() != RHS.first->getType())
00481       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
00482     // Then by frequency.
00483     return LHS.second > RHS.second;
00484   });
00485 
00486   // Ensure that integer and vector of integer constants are at the start of the
00487   // constant pool.  This is important so that GEP structure indices come before
00488   // gep constant exprs.
00489   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
00490                  isIntOrIntVectorValue);
00491 
00492   // Rebuild the modified portion of ValueMap.
00493   for (; CstStart != CstEnd; ++CstStart)
00494     ValueMap[Values[CstStart].first] = CstStart+1;
00495 }
00496 
00497 
00498 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
00499 /// table into the values table.
00500 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
00501   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
00502        VI != VE; ++VI)
00503     EnumerateValue(VI->getValue());
00504 }
00505 
00506 /// Insert all of the values referenced by named metadata in the specified
00507 /// module.
00508 void ValueEnumerator::EnumerateNamedMetadata(const Module &M) {
00509   for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
00510                                              E = M.named_metadata_end();
00511        I != E; ++I)
00512     EnumerateNamedMDNode(I);
00513 }
00514 
00515 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
00516   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
00517     EnumerateMetadata(MD->getOperand(i));
00518 }
00519 
00520 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
00521 /// and types referenced by the given MDNode.
00522 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
00523   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00524     Metadata *MD = N->getOperand(i);
00525     if (!MD)
00526       continue;
00527     assert(!isa<LocalAsMetadata>(MD) && "MDNodes cannot be function-local");
00528     EnumerateMetadata(MD);
00529   }
00530 }
00531 
00532 void ValueEnumerator::EnumerateMetadata(const Metadata *MD) {
00533   assert(
00534       (isa<MDNode>(MD) || isa<MDString>(MD) || isa<ConstantAsMetadata>(MD)) &&
00535       "Invalid metadata kind");
00536 
00537   // Insert a dummy ID to block the co-recursive call to
00538   // EnumerateMDNodeOperands() from re-visiting MD in a cyclic graph.
00539   //
00540   // Return early if there's already an ID.
00541   if (!MDValueMap.insert(std::make_pair(MD, 0)).second)
00542     return;
00543 
00544   // Visit operands first to minimize RAUW.
00545   if (auto *N = dyn_cast<MDNode>(MD))
00546     EnumerateMDNodeOperands(N);
00547   else if (auto *C = dyn_cast<ConstantAsMetadata>(MD))
00548     EnumerateValue(C->getValue());
00549 
00550   HasMDString |= isa<MDString>(MD);
00551   HasMDLocation |= isa<MDLocation>(MD);
00552   HasGenericDebugNode |= isa<GenericDebugNode>(MD);
00553 
00554   // Replace the dummy ID inserted above with the correct one.  MDValueMap may
00555   // have changed by inserting operands, so we need a fresh lookup here.
00556   MDs.push_back(MD);
00557   MDValueMap[MD] = MDs.size();
00558 }
00559 
00560 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
00561 /// information reachable from the metadata.
00562 void ValueEnumerator::EnumerateFunctionLocalMetadata(
00563     const LocalAsMetadata *Local) {
00564   // Check to see if it's already in!
00565   unsigned &MDValueID = MDValueMap[Local];
00566   if (MDValueID)
00567     return;
00568 
00569   MDs.push_back(Local);
00570   MDValueID = MDs.size();
00571 
00572   EnumerateValue(Local->getValue());
00573 
00574   // Also, collect all function-local metadata for easy access.
00575   FunctionLocalMDs.push_back(Local);
00576 }
00577 
00578 void ValueEnumerator::EnumerateValue(const Value *V) {
00579   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
00580   assert(!isa<MetadataAsValue>(V) && "EnumerateValue doesn't handle Metadata!");
00581 
00582   // Check to see if it's already in!
00583   unsigned &ValueID = ValueMap[V];
00584   if (ValueID) {
00585     // Increment use count.
00586     Values[ValueID-1].second++;
00587     return;
00588   }
00589 
00590   if (auto *GO = dyn_cast<GlobalObject>(V))
00591     if (const Comdat *C = GO->getComdat())
00592       Comdats.insert(C);
00593 
00594   // Enumerate the type of this value.
00595   EnumerateType(V->getType());
00596 
00597   if (const Constant *C = dyn_cast<Constant>(V)) {
00598     if (isa<GlobalValue>(C)) {
00599       // Initializers for globals are handled explicitly elsewhere.
00600     } else if (C->getNumOperands()) {
00601       // If a constant has operands, enumerate them.  This makes sure that if a
00602       // constant has uses (for example an array of const ints), that they are
00603       // inserted also.
00604 
00605       // We prefer to enumerate them with values before we enumerate the user
00606       // itself.  This makes it more likely that we can avoid forward references
00607       // in the reader.  We know that there can be no cycles in the constants
00608       // graph that don't go through a global variable.
00609       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
00610            I != E; ++I)
00611         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
00612           EnumerateValue(*I);
00613 
00614       // Finally, add the value.  Doing this could make the ValueID reference be
00615       // dangling, don't reuse it.
00616       Values.push_back(std::make_pair(V, 1U));
00617       ValueMap[V] = Values.size();
00618       return;
00619     }
00620   }
00621 
00622   // Add the value.
00623   Values.push_back(std::make_pair(V, 1U));
00624   ValueID = Values.size();
00625 }
00626 
00627 
00628 void ValueEnumerator::EnumerateType(Type *Ty) {
00629   unsigned *TypeID = &TypeMap[Ty];
00630 
00631   // We've already seen this type.
00632   if (*TypeID)
00633     return;
00634 
00635   // If it is a non-anonymous struct, mark the type as being visited so that we
00636   // don't recursively visit it.  This is safe because we allow forward
00637   // references of these in the bitcode reader.
00638   if (StructType *STy = dyn_cast<StructType>(Ty))
00639     if (!STy->isLiteral())
00640       *TypeID = ~0U;
00641 
00642   // Enumerate all of the subtypes before we enumerate this type.  This ensures
00643   // that the type will be enumerated in an order that can be directly built.
00644   for (Type *SubTy : Ty->subtypes())
00645     EnumerateType(SubTy);
00646 
00647   // Refresh the TypeID pointer in case the table rehashed.
00648   TypeID = &TypeMap[Ty];
00649 
00650   // Check to see if we got the pointer another way.  This can happen when
00651   // enumerating recursive types that hit the base case deeper than they start.
00652   //
00653   // If this is actually a struct that we are treating as forward ref'able,
00654   // then emit the definition now that all of its contents are available.
00655   if (*TypeID && *TypeID != ~0U)
00656     return;
00657 
00658   // Add this type now that its contents are all happily enumerated.
00659   Types.push_back(Ty);
00660 
00661   *TypeID = Types.size();
00662 }
00663 
00664 // Enumerate the types for the specified value.  If the value is a constant,
00665 // walk through it, enumerating the types of the constant.
00666 void ValueEnumerator::EnumerateOperandType(const Value *V) {
00667   EnumerateType(V->getType());
00668 
00669   if (auto *MD = dyn_cast<MetadataAsValue>(V)) {
00670     assert(!isa<LocalAsMetadata>(MD->getMetadata()) &&
00671            "Function-local metadata should be left for later");
00672 
00673     EnumerateMetadata(MD->getMetadata());
00674     return;
00675   }
00676 
00677   const Constant *C = dyn_cast<Constant>(V);
00678   if (!C)
00679     return;
00680 
00681   // If this constant is already enumerated, ignore it, we know its type must
00682   // be enumerated.
00683   if (ValueMap.count(C))
00684     return;
00685 
00686   // This constant may have operands, make sure to enumerate the types in
00687   // them.
00688   for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00689     const Value *Op = C->getOperand(i);
00690 
00691     // Don't enumerate basic blocks here, this happens as operands to
00692     // blockaddress.
00693     if (isa<BasicBlock>(Op))
00694       continue;
00695 
00696     EnumerateOperandType(Op);
00697   }
00698 }
00699 
00700 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
00701   if (PAL.isEmpty()) return;  // null is always 0.
00702 
00703   // Do a lookup.
00704   unsigned &Entry = AttributeMap[PAL];
00705   if (Entry == 0) {
00706     // Never saw this before, add it.
00707     Attribute.push_back(PAL);
00708     Entry = Attribute.size();
00709   }
00710 
00711   // Do lookups for all attribute groups.
00712   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
00713     AttributeSet AS = PAL.getSlotAttributes(i);
00714     unsigned &Entry = AttributeGroupMap[AS];
00715     if (Entry == 0) {
00716       AttributeGroups.push_back(AS);
00717       Entry = AttributeGroups.size();
00718     }
00719   }
00720 }
00721 
00722 void ValueEnumerator::incorporateFunction(const Function &F) {
00723   InstructionCount = 0;
00724   NumModuleValues = Values.size();
00725   NumModuleMDs = MDs.size();
00726 
00727   // Adding function arguments to the value table.
00728   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
00729        I != E; ++I)
00730     EnumerateValue(I);
00731 
00732   FirstFuncConstantID = Values.size();
00733 
00734   // Add all function-level constants to the value table.
00735   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00736     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
00737       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00738            OI != E; ++OI) {
00739         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
00740             isa<InlineAsm>(*OI))
00741           EnumerateValue(*OI);
00742       }
00743     BasicBlocks.push_back(BB);
00744     ValueMap[BB] = BasicBlocks.size();
00745   }
00746 
00747   // Optimize the constant layout.
00748   OptimizeConstants(FirstFuncConstantID, Values.size());
00749 
00750   // Add the function's parameter attributes so they are available for use in
00751   // the function's instruction.
00752   EnumerateAttributes(F.getAttributes());
00753 
00754   FirstInstID = Values.size();
00755 
00756   SmallVector<LocalAsMetadata *, 8> FnLocalMDVector;
00757   // Add all of the instructions.
00758   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00759     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
00760       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00761            OI != E; ++OI) {
00762         if (auto *MD = dyn_cast<MetadataAsValue>(&*OI))
00763           if (auto *Local = dyn_cast<LocalAsMetadata>(MD->getMetadata()))
00764             // Enumerate metadata after the instructions they might refer to.
00765             FnLocalMDVector.push_back(Local);
00766       }
00767 
00768       if (!I->getType()->isVoidTy())
00769         EnumerateValue(I);
00770     }
00771   }
00772 
00773   // Add all of the function-local metadata.
00774   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
00775     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
00776 }
00777 
00778 void ValueEnumerator::purgeFunction() {
00779   /// Remove purged values from the ValueMap.
00780   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
00781     ValueMap.erase(Values[i].first);
00782   for (unsigned i = NumModuleMDs, e = MDs.size(); i != e; ++i)
00783     MDValueMap.erase(MDs[i]);
00784   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
00785     ValueMap.erase(BasicBlocks[i]);
00786 
00787   Values.resize(NumModuleValues);
00788   MDs.resize(NumModuleMDs);
00789   BasicBlocks.clear();
00790   FunctionLocalMDs.clear();
00791 }
00792 
00793 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
00794                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
00795   unsigned Counter = 0;
00796   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00797     IDMap[BB] = ++Counter;
00798 }
00799 
00800 /// getGlobalBasicBlockID - This returns the function-specific ID for the
00801 /// specified basic block.  This is relatively expensive information, so it
00802 /// should only be used by rare constructs such as address-of-label.
00803 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
00804   unsigned &Idx = GlobalBasicBlockIDs[BB];
00805   if (Idx != 0)
00806     return Idx-1;
00807 
00808   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
00809   return getGlobalBasicBlockID(BB);
00810 }
00811 
00812 uint64_t ValueEnumerator::computeBitsRequiredForTypeIndicies() const {
00813   return Log2_32_Ceil(getTypes().size() + 1);
00814 }