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