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