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