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