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/ValueSymbolTable.h"
00022 #include "llvm/Support/Debug.h"
00023 #include "llvm/Support/raw_ostream.h"
00024 #include <algorithm>
00025 using namespace llvm;
00026 
00027 static bool isIntOrIntVectorValue(const std::pair<const Value*, unsigned> &V) {
00028   return V.first->getType()->isIntOrIntVectorTy();
00029 }
00030 
00031 /// ValueEnumerator - Enumerate module-level information.
00032 ValueEnumerator::ValueEnumerator(const Module *M) {
00033   // Enumerate the global variables.
00034   for (Module::const_global_iterator I = M->global_begin(),
00035          E = M->global_end(); I != E; ++I)
00036     EnumerateValue(I);
00037 
00038   // Enumerate the functions.
00039   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
00040     EnumerateValue(I);
00041     EnumerateAttributes(cast<Function>(I)->getAttributes());
00042   }
00043 
00044   // Enumerate the aliases.
00045   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00046        I != E; ++I)
00047     EnumerateValue(I);
00048 
00049   // Remember what is the cutoff between globalvalue's and other constants.
00050   unsigned FirstConstant = Values.size();
00051 
00052   // Enumerate the global variable initializers.
00053   for (Module::const_global_iterator I = M->global_begin(),
00054          E = M->global_end(); I != E; ++I)
00055     if (I->hasInitializer())
00056       EnumerateValue(I->getInitializer());
00057 
00058   // Enumerate the aliasees.
00059   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
00060        I != E; ++I)
00061     EnumerateValue(I->getAliasee());
00062 
00063   // Enumerate the prefix data constants.
00064   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)
00065     if (I->hasPrefixData())
00066       EnumerateValue(I->getPrefixData());
00067 
00068   // Insert constants and metadata that are named at module level into the slot
00069   // pool so that the module symbol table can refer to them...
00070   EnumerateValueSymbolTable(M->getValueSymbolTable());
00071   EnumerateNamedMetadata(M);
00072 
00073   SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
00074 
00075   // Enumerate types used by function bodies and argument lists.
00076   for (const Function &F : *M) {
00077     for (const Argument &A : F.args())
00078       EnumerateType(A.getType());
00079 
00080     for (const BasicBlock &BB : F)
00081       for (const Instruction &I : BB) {
00082         for (const Use &Op : I.operands()) {
00083           if (MDNode *MD = dyn_cast<MDNode>(&Op))
00084             if (MD->isFunctionLocal() && MD->getFunction())
00085               // These will get enumerated during function-incorporation.
00086               continue;
00087           EnumerateOperandType(Op);
00088         }
00089         EnumerateType(I.getType());
00090         if (const CallInst *CI = dyn_cast<CallInst>(&I))
00091           EnumerateAttributes(CI->getAttributes());
00092         else if (const InvokeInst *II = dyn_cast<InvokeInst>(&I))
00093           EnumerateAttributes(II->getAttributes());
00094 
00095         // Enumerate metadata attached with this instruction.
00096         MDs.clear();
00097         I.getAllMetadataOtherThanDebugLoc(MDs);
00098         for (unsigned i = 0, e = MDs.size(); i != e; ++i)
00099           EnumerateMetadata(MDs[i].second);
00100 
00101         if (!I.getDebugLoc().isUnknown()) {
00102           MDNode *Scope, *IA;
00103           I.getDebugLoc().getScopeAndInlinedAt(Scope, IA, I.getContext());
00104           if (Scope) EnumerateMetadata(Scope);
00105           if (IA) EnumerateMetadata(IA);
00106         }
00107       }
00108   }
00109 
00110   // Optimize constant ordering.
00111   OptimizeConstants(FirstConstant, Values.size());
00112 }
00113 
00114 unsigned ValueEnumerator::getInstructionID(const Instruction *Inst) const {
00115   InstructionMapType::const_iterator I = InstructionMap.find(Inst);
00116   assert(I != InstructionMap.end() && "Instruction is not mapped!");
00117   return I->second;
00118 }
00119 
00120 unsigned ValueEnumerator::getComdatID(const Comdat *C) const {
00121   unsigned ComdatID = Comdats.idFor(C);
00122   assert(ComdatID && "Comdat not found!");
00123   return ComdatID;
00124 }
00125 
00126 void ValueEnumerator::setInstructionID(const Instruction *I) {
00127   InstructionMap[I] = InstructionCount++;
00128 }
00129 
00130 unsigned ValueEnumerator::getValueID(const Value *V) const {
00131   if (isa<MDNode>(V) || isa<MDString>(V)) {
00132     ValueMapType::const_iterator I = MDValueMap.find(V);
00133     assert(I != MDValueMap.end() && "Value not in slotcalculator!");
00134     return I->second-1;
00135   }
00136 
00137   ValueMapType::const_iterator I = ValueMap.find(V);
00138   assert(I != ValueMap.end() && "Value not in slotcalculator!");
00139   return I->second-1;
00140 }
00141 
00142 void ValueEnumerator::dump() const {
00143   print(dbgs(), ValueMap, "Default");
00144   dbgs() << '\n';
00145   print(dbgs(), MDValueMap, "MetaData");
00146   dbgs() << '\n';
00147 }
00148 
00149 void ValueEnumerator::print(raw_ostream &OS, const ValueMapType &Map,
00150                             const char *Name) const {
00151 
00152   OS << "Map Name: " << Name << "\n";
00153   OS << "Size: " << Map.size() << "\n";
00154   for (ValueMapType::const_iterator I = Map.begin(),
00155          E = Map.end(); I != E; ++I) {
00156 
00157     const Value *V = I->first;
00158     if (V->hasName())
00159       OS << "Value: " << V->getName();
00160     else
00161       OS << "Value: [null]\n";
00162     V->dump();
00163 
00164     OS << " Uses(" << std::distance(V->use_begin(),V->use_end()) << "):";
00165     for (const Use &U : V->uses()) {
00166       if (&U != &*V->use_begin())
00167         OS << ",";
00168       if(U->hasName())
00169         OS << " " << U->getName();
00170       else
00171         OS << " [null]";
00172 
00173     }
00174     OS <<  "\n\n";
00175   }
00176 }
00177 
00178 /// OptimizeConstants - Reorder constant pool for denser encoding.
00179 void ValueEnumerator::OptimizeConstants(unsigned CstStart, unsigned CstEnd) {
00180   if (CstStart == CstEnd || CstStart+1 == CstEnd) return;
00181 
00182   std::stable_sort(Values.begin() + CstStart, Values.begin() + CstEnd,
00183                    [this](const std::pair<const Value *, unsigned> &LHS,
00184                           const std::pair<const Value *, unsigned> &RHS) {
00185     // Sort by plane.
00186     if (LHS.first->getType() != RHS.first->getType())
00187       return getTypeID(LHS.first->getType()) < getTypeID(RHS.first->getType());
00188     // Then by frequency.
00189     return LHS.second > RHS.second;
00190   });
00191 
00192   // Ensure that integer and vector of integer constants are at the start of the
00193   // constant pool.  This is important so that GEP structure indices come before
00194   // gep constant exprs.
00195   std::partition(Values.begin()+CstStart, Values.begin()+CstEnd,
00196                  isIntOrIntVectorValue);
00197 
00198   // Rebuild the modified portion of ValueMap.
00199   for (; CstStart != CstEnd; ++CstStart)
00200     ValueMap[Values[CstStart].first] = CstStart+1;
00201 }
00202 
00203 
00204 /// EnumerateValueSymbolTable - Insert all of the values in the specified symbol
00205 /// table into the values table.
00206 void ValueEnumerator::EnumerateValueSymbolTable(const ValueSymbolTable &VST) {
00207   for (ValueSymbolTable::const_iterator VI = VST.begin(), VE = VST.end();
00208        VI != VE; ++VI)
00209     EnumerateValue(VI->getValue());
00210 }
00211 
00212 /// EnumerateNamedMetadata - Insert all of the values referenced by
00213 /// named metadata in the specified module.
00214 void ValueEnumerator::EnumerateNamedMetadata(const Module *M) {
00215   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
00216        E = M->named_metadata_end(); I != E; ++I)
00217     EnumerateNamedMDNode(I);
00218 }
00219 
00220 void ValueEnumerator::EnumerateNamedMDNode(const NamedMDNode *MD) {
00221   for (unsigned i = 0, e = MD->getNumOperands(); i != e; ++i)
00222     EnumerateMetadata(MD->getOperand(i));
00223 }
00224 
00225 /// EnumerateMDNodeOperands - Enumerate all non-function-local values
00226 /// and types referenced by the given MDNode.
00227 void ValueEnumerator::EnumerateMDNodeOperands(const MDNode *N) {
00228   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
00229     if (Value *V = N->getOperand(i)) {
00230       if (isa<MDNode>(V) || isa<MDString>(V))
00231         EnumerateMetadata(V);
00232       else if (!isa<Instruction>(V) && !isa<Argument>(V))
00233         EnumerateValue(V);
00234     } else
00235       EnumerateType(Type::getVoidTy(N->getContext()));
00236   }
00237 }
00238 
00239 void ValueEnumerator::EnumerateMetadata(const Value *MD) {
00240   assert((isa<MDNode>(MD) || isa<MDString>(MD)) && "Invalid metadata kind");
00241 
00242   // Enumerate the type of this value.
00243   EnumerateType(MD->getType());
00244 
00245   const MDNode *N = dyn_cast<MDNode>(MD);
00246 
00247   // In the module-level pass, skip function-local nodes themselves, but
00248   // do walk their operands.
00249   if (N && N->isFunctionLocal() && N->getFunction()) {
00250     EnumerateMDNodeOperands(N);
00251     return;
00252   }
00253 
00254   // Check to see if it's already in!
00255   unsigned &MDValueID = MDValueMap[MD];
00256   if (MDValueID) {
00257     // Increment use count.
00258     MDValues[MDValueID-1].second++;
00259     return;
00260   }
00261   MDValues.push_back(std::make_pair(MD, 1U));
00262   MDValueID = MDValues.size();
00263 
00264   // Enumerate all non-function-local operands.
00265   if (N)
00266     EnumerateMDNodeOperands(N);
00267 }
00268 
00269 /// EnumerateFunctionLocalMetadataa - Incorporate function-local metadata
00270 /// information reachable from the given MDNode.
00271 void ValueEnumerator::EnumerateFunctionLocalMetadata(const MDNode *N) {
00272   assert(N->isFunctionLocal() && N->getFunction() &&
00273          "EnumerateFunctionLocalMetadata called on non-function-local mdnode!");
00274 
00275   // Enumerate the type of this value.
00276   EnumerateType(N->getType());
00277 
00278   // Check to see if it's already in!
00279   unsigned &MDValueID = MDValueMap[N];
00280   if (MDValueID) {
00281     // Increment use count.
00282     MDValues[MDValueID-1].second++;
00283     return;
00284   }
00285   MDValues.push_back(std::make_pair(N, 1U));
00286   MDValueID = MDValues.size();
00287 
00288   // To incoroporate function-local information visit all function-local
00289   // MDNodes and all function-local values they reference.
00290   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00291     if (Value *V = N->getOperand(i)) {
00292       if (MDNode *O = dyn_cast<MDNode>(V)) {
00293         if (O->isFunctionLocal() && O->getFunction())
00294           EnumerateFunctionLocalMetadata(O);
00295       } else if (isa<Instruction>(V) || isa<Argument>(V))
00296         EnumerateValue(V);
00297     }
00298 
00299   // Also, collect all function-local MDNodes for easy access.
00300   FunctionLocalMDs.push_back(N);
00301 }
00302 
00303 void ValueEnumerator::EnumerateValue(const Value *V) {
00304   assert(!V->getType()->isVoidTy() && "Can't insert void values!");
00305   assert(!isa<MDNode>(V) && !isa<MDString>(V) &&
00306          "EnumerateValue doesn't handle Metadata!");
00307 
00308   // Check to see if it's already in!
00309   unsigned &ValueID = ValueMap[V];
00310   if (ValueID) {
00311     // Increment use count.
00312     Values[ValueID-1].second++;
00313     return;
00314   }
00315 
00316   if (auto *GO = dyn_cast<GlobalObject>(V))
00317     if (const Comdat *C = GO->getComdat())
00318       Comdats.insert(C);
00319 
00320   // Enumerate the type of this value.
00321   EnumerateType(V->getType());
00322 
00323   if (const Constant *C = dyn_cast<Constant>(V)) {
00324     if (isa<GlobalValue>(C)) {
00325       // Initializers for globals are handled explicitly elsewhere.
00326     } else if (C->getNumOperands()) {
00327       // If a constant has operands, enumerate them.  This makes sure that if a
00328       // constant has uses (for example an array of const ints), that they are
00329       // inserted also.
00330 
00331       // We prefer to enumerate them with values before we enumerate the user
00332       // itself.  This makes it more likely that we can avoid forward references
00333       // in the reader.  We know that there can be no cycles in the constants
00334       // graph that don't go through a global variable.
00335       for (User::const_op_iterator I = C->op_begin(), E = C->op_end();
00336            I != E; ++I)
00337         if (!isa<BasicBlock>(*I)) // Don't enumerate BB operand to BlockAddress.
00338           EnumerateValue(*I);
00339 
00340       // Finally, add the value.  Doing this could make the ValueID reference be
00341       // dangling, don't reuse it.
00342       Values.push_back(std::make_pair(V, 1U));
00343       ValueMap[V] = Values.size();
00344       return;
00345     }
00346   }
00347 
00348   // Add the value.
00349   Values.push_back(std::make_pair(V, 1U));
00350   ValueID = Values.size();
00351 }
00352 
00353 
00354 void ValueEnumerator::EnumerateType(Type *Ty) {
00355   unsigned *TypeID = &TypeMap[Ty];
00356 
00357   // We've already seen this type.
00358   if (*TypeID)
00359     return;
00360 
00361   // If it is a non-anonymous struct, mark the type as being visited so that we
00362   // don't recursively visit it.  This is safe because we allow forward
00363   // references of these in the bitcode reader.
00364   if (StructType *STy = dyn_cast<StructType>(Ty))
00365     if (!STy->isLiteral())
00366       *TypeID = ~0U;
00367 
00368   // Enumerate all of the subtypes before we enumerate this type.  This ensures
00369   // that the type will be enumerated in an order that can be directly built.
00370   for (Type::subtype_iterator I = Ty->subtype_begin(), E = Ty->subtype_end();
00371        I != E; ++I)
00372     EnumerateType(*I);
00373 
00374   // Refresh the TypeID pointer in case the table rehashed.
00375   TypeID = &TypeMap[Ty];
00376 
00377   // Check to see if we got the pointer another way.  This can happen when
00378   // enumerating recursive types that hit the base case deeper than they start.
00379   //
00380   // If this is actually a struct that we are treating as forward ref'able,
00381   // then emit the definition now that all of its contents are available.
00382   if (*TypeID && *TypeID != ~0U)
00383     return;
00384 
00385   // Add this type now that its contents are all happily enumerated.
00386   Types.push_back(Ty);
00387 
00388   *TypeID = Types.size();
00389 }
00390 
00391 // Enumerate the types for the specified value.  If the value is a constant,
00392 // walk through it, enumerating the types of the constant.
00393 void ValueEnumerator::EnumerateOperandType(const Value *V) {
00394   EnumerateType(V->getType());
00395 
00396   if (const Constant *C = dyn_cast<Constant>(V)) {
00397     // If this constant is already enumerated, ignore it, we know its type must
00398     // be enumerated.
00399     if (ValueMap.count(V)) return;
00400 
00401     // This constant may have operands, make sure to enumerate the types in
00402     // them.
00403     for (unsigned i = 0, e = C->getNumOperands(); i != e; ++i) {
00404       const Value *Op = C->getOperand(i);
00405 
00406       // Don't enumerate basic blocks here, this happens as operands to
00407       // blockaddress.
00408       if (isa<BasicBlock>(Op)) continue;
00409 
00410       EnumerateOperandType(Op);
00411     }
00412 
00413     if (const MDNode *N = dyn_cast<MDNode>(V)) {
00414       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00415         if (Value *Elem = N->getOperand(i))
00416           EnumerateOperandType(Elem);
00417     }
00418   } else if (isa<MDString>(V) || isa<MDNode>(V))
00419     EnumerateMetadata(V);
00420 }
00421 
00422 void ValueEnumerator::EnumerateAttributes(AttributeSet PAL) {
00423   if (PAL.isEmpty()) return;  // null is always 0.
00424 
00425   // Do a lookup.
00426   unsigned &Entry = AttributeMap[PAL];
00427   if (Entry == 0) {
00428     // Never saw this before, add it.
00429     Attribute.push_back(PAL);
00430     Entry = Attribute.size();
00431   }
00432 
00433   // Do lookups for all attribute groups.
00434   for (unsigned i = 0, e = PAL.getNumSlots(); i != e; ++i) {
00435     AttributeSet AS = PAL.getSlotAttributes(i);
00436     unsigned &Entry = AttributeGroupMap[AS];
00437     if (Entry == 0) {
00438       AttributeGroups.push_back(AS);
00439       Entry = AttributeGroups.size();
00440     }
00441   }
00442 }
00443 
00444 void ValueEnumerator::incorporateFunction(const Function &F) {
00445   InstructionCount = 0;
00446   NumModuleValues = Values.size();
00447   NumModuleMDValues = MDValues.size();
00448 
00449   // Adding function arguments to the value table.
00450   for (Function::const_arg_iterator I = F.arg_begin(), E = F.arg_end();
00451        I != E; ++I)
00452     EnumerateValue(I);
00453 
00454   FirstFuncConstantID = Values.size();
00455 
00456   // Add all function-level constants to the value table.
00457   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00458     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)
00459       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00460            OI != E; ++OI) {
00461         if ((isa<Constant>(*OI) && !isa<GlobalValue>(*OI)) ||
00462             isa<InlineAsm>(*OI))
00463           EnumerateValue(*OI);
00464       }
00465     BasicBlocks.push_back(BB);
00466     ValueMap[BB] = BasicBlocks.size();
00467   }
00468 
00469   // Optimize the constant layout.
00470   OptimizeConstants(FirstFuncConstantID, Values.size());
00471 
00472   // Add the function's parameter attributes so they are available for use in
00473   // the function's instruction.
00474   EnumerateAttributes(F.getAttributes());
00475 
00476   FirstInstID = Values.size();
00477 
00478   SmallVector<MDNode *, 8> FnLocalMDVector;
00479   // Add all of the instructions.
00480   for (Function::const_iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {
00481     for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I) {
00482       for (User::const_op_iterator OI = I->op_begin(), E = I->op_end();
00483            OI != E; ++OI) {
00484         if (MDNode *MD = dyn_cast<MDNode>(*OI))
00485           if (MD->isFunctionLocal() && MD->getFunction())
00486             // Enumerate metadata after the instructions they might refer to.
00487             FnLocalMDVector.push_back(MD);
00488       }
00489 
00490       SmallVector<std::pair<unsigned, MDNode*>, 8> MDs;
00491       I->getAllMetadataOtherThanDebugLoc(MDs);
00492       for (unsigned i = 0, e = MDs.size(); i != e; ++i) {
00493         MDNode *N = MDs[i].second;
00494         if (N->isFunctionLocal() && N->getFunction())
00495           FnLocalMDVector.push_back(N);
00496       }
00497 
00498       if (!I->getType()->isVoidTy())
00499         EnumerateValue(I);
00500     }
00501   }
00502 
00503   // Add all of the function-local metadata.
00504   for (unsigned i = 0, e = FnLocalMDVector.size(); i != e; ++i)
00505     EnumerateFunctionLocalMetadata(FnLocalMDVector[i]);
00506 }
00507 
00508 void ValueEnumerator::purgeFunction() {
00509   /// Remove purged values from the ValueMap.
00510   for (unsigned i = NumModuleValues, e = Values.size(); i != e; ++i)
00511     ValueMap.erase(Values[i].first);
00512   for (unsigned i = NumModuleMDValues, e = MDValues.size(); i != e; ++i)
00513     MDValueMap.erase(MDValues[i].first);
00514   for (unsigned i = 0, e = BasicBlocks.size(); i != e; ++i)
00515     ValueMap.erase(BasicBlocks[i]);
00516 
00517   Values.resize(NumModuleValues);
00518   MDValues.resize(NumModuleMDValues);
00519   BasicBlocks.clear();
00520   FunctionLocalMDs.clear();
00521 }
00522 
00523 static void IncorporateFunctionInfoGlobalBBIDs(const Function *F,
00524                                  DenseMap<const BasicBlock*, unsigned> &IDMap) {
00525   unsigned Counter = 0;
00526   for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)
00527     IDMap[BB] = ++Counter;
00528 }
00529 
00530 /// getGlobalBasicBlockID - This returns the function-specific ID for the
00531 /// specified basic block.  This is relatively expensive information, so it
00532 /// should only be used by rare constructs such as address-of-label.
00533 unsigned ValueEnumerator::getGlobalBasicBlockID(const BasicBlock *BB) const {
00534   unsigned &Idx = GlobalBasicBlockIDs[BB];
00535   if (Idx != 0)
00536     return Idx-1;
00537 
00538   IncorporateFunctionInfoGlobalBBIDs(BB->getParent(), GlobalBasicBlockIDs);
00539   return getGlobalBasicBlockID(BB);
00540 }
00541