1 //===-- Analyzer.cpp - Analysis and Dumping of Bytecode ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by Reid Spencer and is distributed under the
6 // University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the AnalyzerHandler class and PrintBytecodeAnalysis
11 // function which together comprise the basic functionality of the llmv-abcd
12 // tool. The AnalyzerHandler collects information about the bytecode file into
13 // the BytecodeAnalysis structure. The PrintBytecodeAnalysis function prints
14 // out the content of that structure.
15 // @see include/llvm/Bytecode/Analysis.h
17 //===----------------------------------------------------------------------===//
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/Analysis/Verifier.h"
24 #include "llvm/Bytecode/BytecodeHandler.h"
25 #include "llvm/Assembly/Writer.h"
33 /// @brief Bytecode reading handler for analyzing bytecode.
34 class AnalyzerHandler : public BytecodeHandler {
35 BytecodeAnalysis& bca; ///< The structure in which data is recorded
36 std::ostream* os; ///< A convenience for osing data.
37 /// @brief Keeps track of current function
38 BytecodeAnalysis::BytecodeFunctionInfo* currFunc;
39 Module* M; ///< Keeps track of current module
44 /// The only way to construct an AnalyzerHandler. All that is needed is a
45 /// reference to the BytecodeAnalysis structure where the output will be
47 AnalyzerHandler(BytecodeAnalysis& TheBca, std::ostream* output)
54 /// @name BytecodeHandler Implementations
57 virtual void handleError(const std::string& str ) {
59 *os << "ERROR: " << str << "\n";
62 virtual void handleStart( Module* Mod, unsigned theSize ) {
65 *os << "Bytecode {\n";
66 bca.byteSize = theSize;
73 bca.numGlobalVars = 0;
74 bca.numInstructions = 0;
75 bca.numBasicBlocks = 0;
77 bca.numCmpctnTables = 0;
84 bca.fileDensity = 0.0;
85 bca.globalsDensity = 0.0;
86 bca.functionDensity = 0.0;
87 bca.instructionSize = 0;
88 bca.longInstructions = 0;
89 bca.FunctionInfo.clear();
90 bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse] = 0;
91 bca.BlockSizes[BytecodeFormat::ModuleBlockID] = theSize;
92 bca.BlockSizes[BytecodeFormat::FunctionBlockID] = 0;
93 bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID] = 0;
94 bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID] = 0;
95 bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID] = 0;
96 bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID] = 0;
97 bca.BlockSizes[BytecodeFormat::InstructionListBlockID] = 0;
98 bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID] = 0;
101 virtual void handleFinish() {
103 *os << "} End Bytecode\n";
105 bca.fileDensity = double(bca.byteSize) / double( bca.numTypes + bca.numValues );
106 double globalSize = 0.0;
107 globalSize += double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]);
108 globalSize += double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]);
109 globalSize += double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]);
110 bca.globalsDensity = globalSize / double( bca.numTypes + bca.numConstants +
112 bca.functionDensity = double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]) /
113 double(bca.numFunctions);
115 if (bca.progressiveVerify) {
117 if (verifyModule(*M, ReturnStatusAction, &msg))
118 bca.VerifyInfo += "Verify@Finish: " + msg + "\n";
122 virtual void handleModuleBegin(const std::string& id) {
124 *os << " Module " << id << " {\n";
128 virtual void handleModuleEnd(const std::string& id) {
130 *os << " } End Module " << id << "\n";
131 if (bca.progressiveVerify) {
133 if (verifyModule(*M, ReturnStatusAction, &msg))
134 bca.VerifyInfo += "Verify@EndModule: " + msg + "\n";
138 virtual void handleVersionInfo(
139 unsigned char RevisionNum ///< Byte code revision number
142 *os << " RevisionNum: " << int(RevisionNum) << "\n";
143 bca.version = RevisionNum;
146 virtual void handleModuleGlobalsBegin() {
148 *os << " BLOCK: ModuleGlobalInfo {\n";
151 virtual void handleGlobalVariable(
152 const Type* ElemType,
154 GlobalValue::LinkageTypes Linkage,
155 GlobalValue::VisibilityTypes Visibility,
162 << ( initSlot == 0 ? "Uni" : "I" ) << "nitialized, "
163 << ( isConstant? "Constant, " : "Variable, ")
164 << " Thread Local = " << ( isThreadLocal? "yes, " : "no, ")
165 << " Linkage=" << Linkage
166 << " Visibility="<< Visibility
168 //WriteTypeSymbolic(*os, ElemType, M);
169 *os << " Slot=" << SlotNum << " InitSlot=" << initSlot
175 if (SlotNum > bca.maxValueSlot)
176 bca.maxValueSlot = SlotNum;
177 if (initSlot > bca.maxValueSlot)
178 bca.maxValueSlot = initSlot;
182 virtual void handleGlobalAlias(
183 const Type* ElemType,
184 GlobalValue::LinkageTypes Linkage,
185 unsigned TypeSlotNum,
186 unsigned AliaseeSlot) {
189 << " Linkage=" << Linkage
191 //WriteTypeSymbolic(*os, ElemType, M);
192 *os << " Slot=" << TypeSlotNum << " AliaseeSlot=" << AliaseeSlot
197 if (TypeSlotNum > bca.maxValueSlot)
198 bca.maxValueSlot = TypeSlotNum;
199 if (AliaseeSlot > bca.maxValueSlot)
200 bca.maxValueSlot = AliaseeSlot;
203 virtual void handleTypeList(unsigned numEntries) {
204 bca.maxTypeSlot = numEntries - 1;
207 virtual void handleType( const Type* Ty ) {
211 //WriteTypeSymbolic(*os,Ty,M);
216 virtual void handleFunctionDeclaration(
217 Function* Func ///< The function
222 *os << " Function Decl: ";
223 //WriteTypeSymbolic(*os,Func->getType(),M);
224 *os <<", Linkage=" << Func->getLinkage();
225 *os <<", Visibility=" << Func->getVisibility();
230 virtual void handleGlobalInitializer(GlobalVariable* GV, Constant* CV) {
232 *os << " Initializer: GV=";
240 virtual void handleDependentLibrary(const std::string& libName) {
242 bca.libSize += libName.size() + (libName.size() < 128 ? 1 : 2);
244 *os << " Library: '" << libName << "'\n";
247 virtual void handleModuleGlobalsEnd() {
249 *os << " } END BLOCK: ModuleGlobalInfo\n";
250 if (bca.progressiveVerify) {
252 if (verifyModule(*M, ReturnStatusAction, &msg))
253 bca.VerifyInfo += "Verify@EndModuleGlobalInfo: " + msg + "\n";
257 virtual void handleTypeSymbolTableBegin(TypeSymbolTable* ST) {
260 *os << " BLOCK: TypeSymbolTable {\n";
262 virtual void handleValueSymbolTableBegin(Function* CF, ValueSymbolTable* ST) {
265 *os << " BLOCK: ValueSymbolTable {\n";
268 virtual void handleSymbolTableType(unsigned i, unsigned TypSlot,
269 const std::string& name ) {
271 *os << " Type " << i << " Slot=" << TypSlot
272 << " Name: " << name << "\n";
275 virtual void handleSymbolTableValue(unsigned TySlot, unsigned ValSlot,
276 const char *Name, unsigned NameLen) {
278 *os << " Value " << TySlot << " Slot=" << ValSlot
279 << " Name: " << std::string(Name, Name+NameLen) << "\n";
280 if (ValSlot > bca.maxValueSlot)
281 bca.maxValueSlot = ValSlot;
284 virtual void handleValueSymbolTableEnd() {
286 *os << " } END BLOCK: ValueSymbolTable\n";
289 virtual void handleTypeSymbolTableEnd() {
291 *os << " } END BLOCK: TypeSymbolTable\n";
294 virtual void handleFunctionBegin(Function* Func, unsigned Size) {
296 *os << " BLOCK: Function {\n"
297 << " Linkage: " << Func->getLinkage() << "\n"
298 << " Visibility: " << Func->getVisibility() << "\n"
300 //WriteTypeSymbolic(*os,Func->getType(),M);
304 currFunc = &bca.FunctionInfo[Func];
305 std::ostringstream tmp;
306 //WriteTypeSymbolic(tmp,Func->getType(),M);
307 currFunc->description = tmp.str();
308 currFunc->name = Func->getName();
309 currFunc->byteSize = Size;
310 currFunc->numInstructions = 0;
311 currFunc->numBasicBlocks = 0;
312 currFunc->numPhis = 0;
313 currFunc->numOperands = 0;
314 currFunc->density = 0.0;
315 currFunc->instructionSize = 0;
316 currFunc->longInstructions = 0;
320 virtual void handleFunctionEnd( Function* Func) {
322 *os << " } END BLOCK: Function\n";
323 currFunc->density = double(currFunc->byteSize) /
324 double(currFunc->numInstructions);
326 if (bca.progressiveVerify) {
328 if (verifyModule(*M, ReturnStatusAction, &msg))
329 bca.VerifyInfo += "Verify@EndFunction: " + msg + "\n";
333 virtual void handleBasicBlockBegin( unsigned blocknum) {
335 *os << " BLOCK: BasicBlock #" << blocknum << "{\n";
336 bca.numBasicBlocks++;
338 if ( currFunc ) currFunc->numBasicBlocks++;
341 virtual bool handleInstruction( unsigned Opcode, const Type* iType,
342 unsigned *Operands, unsigned NumOps,
346 *os << " INST: OpCode="
347 << Instruction::getOpcodeName(Opcode);
348 for (unsigned i = 0; i != NumOps; ++i)
349 *os << " Op(" << Operands[i] << ")";
353 bca.numInstructions++;
355 bca.instructionSize += Size;
356 if (Size > 4 ) bca.longInstructions++;
357 bca.numOperands += NumOps;
358 for (unsigned i = 0; i != NumOps; ++i)
359 if (Operands[i] > bca.maxValueSlot)
360 bca.maxValueSlot = Operands[i];
362 currFunc->numInstructions++;
363 currFunc->instructionSize += Size;
364 if (Size > 4 ) currFunc->longInstructions++;
365 if (Opcode == Instruction::PHI) currFunc->numPhis++;
367 return Instruction::isTerminator(Opcode);
370 virtual void handleBasicBlockEnd(unsigned blocknum) {
372 *os << " } END BLOCK: BasicBlock #" << blocknum << "\n";
375 virtual void handleGlobalConstantsBegin() {
377 *os << " BLOCK: GlobalConstants {\n";
380 virtual void handleConstantExpression(unsigned Opcode,
381 Constant**ArgVec, unsigned NumArgs, Constant* C) {
383 *os << " EXPR: " << Instruction::getOpcodeName(Opcode) << "\n";
384 for ( unsigned i = 0; i != NumArgs; ++i ) {
385 *os << " Arg#" << i << " "; ArgVec[i]->print(*os);
396 virtual void handleConstantValue( Constant * c ) {
406 virtual void handleConstantArray( const ArrayType* AT,
407 Constant**Elements, unsigned NumElts,
409 Constant* ArrayVal ) {
412 //WriteTypeSymbolic(*os,AT,M);
413 *os << " TypeSlot=" << TypeSlot << "\n";
414 for (unsigned i = 0; i != NumElts; ++i) {
416 Elements[i]->print(*os);
420 ArrayVal->print(*os);
428 virtual void handleConstantStruct(
429 const StructType* ST,
430 Constant**Elements, unsigned NumElts,
435 //WriteTypeSymbolic(*os,ST,M);
437 for ( unsigned i = 0; i != NumElts; ++i) {
438 *os << " #" << i << " "; Elements[i]->print(*os);
442 StructVal->print(*os);
449 virtual void handleConstantVector(
450 const VectorType* PT,
451 Constant**Elements, unsigned NumElts,
457 //WriteTypeSymbolic(*os,PT,M);
458 *os << " TypeSlot=" << TypeSlot << "\n";
459 for ( unsigned i = 0; i != NumElts; ++i ) {
461 Elements[i]->print(*os);
465 VectorVal->print(*os);
473 virtual void handleConstantPointer( const PointerType* PT,
474 unsigned Slot, GlobalValue* GV ) {
477 //WriteTypeSymbolic(*os,PT,M);
478 *os << " Slot=" << Slot << " GlobalValue=";
486 virtual void handleConstantString( const ConstantArray* CA ) {
496 virtual void handleGlobalConstantsEnd() {
498 *os << " } END BLOCK: GlobalConstants\n";
500 if (bca.progressiveVerify) {
502 if (verifyModule(*M, ReturnStatusAction, &msg))
503 bca.VerifyInfo += "Verify@EndGlobalConstants: " + msg + "\n";
507 virtual void handleAlignment(unsigned numBytes) {
508 bca.numAlignment += numBytes;
511 virtual void handleBlock(
512 unsigned BType, const unsigned char* StartPtr, unsigned Size) {
514 assert(BType >= BytecodeFormat::ModuleBlockID);
515 assert(BType < BytecodeFormat::NumberOfBlockIDs);
517 llvm::BytecodeFormat::BytecodeBlockIdentifiers(BType)] += Size;
519 if (bca.version < 3) // Check for long block headers versions
520 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 8;
522 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 4;
526 } // end anonymous namespace
528 /// @brief Utility for printing a titled unsigned value with
529 /// an aligned colon.
530 inline static void print(std::ostream& Out, const char*title,
531 unsigned val, bool nl = true ) {
532 Out << std::setw(30) << std::right << title
533 << std::setw(0) << ": "
534 << std::setw(9) << val << "\n";
537 /// @brief Utility for printing a titled double value with an
539 inline static void print(std::ostream&Out, const char*title,
541 Out << std::setw(30) << std::right << title
542 << std::setw(0) << ": "
543 << std::setw(9) << std::setprecision(6) << val << "\n" ;
546 /// @brief Utility for printing a titled double value with a
547 /// percentage and aligned colon.
548 inline static void print(std::ostream&Out, const char*title,
549 double top, double bot ) {
550 Out << std::setw(30) << std::right << title
551 << std::setw(0) << ": "
552 << std::setw(9) << std::setprecision(6) << top
553 << " (" << std::left << std::setw(0) << std::setprecision(4)
554 << (top/bot)*100.0 << "%)\n";
557 /// @brief Utility for printing a titled string value with
558 /// an aligned colon.
559 inline static void print(std::ostream&Out, const char*title,
560 std::string val, bool nl = true) {
561 Out << std::setw(30) << std::right << title
562 << std::setw(0) << ": "
563 << std::left << val << (nl ? "\n" : "");
566 /// This function prints the contents of rhe BytecodeAnalysis structure in
567 /// a human legible form.
568 /// @brief Print BytecodeAnalysis structure to an ostream
569 void llvm::PrintBytecodeAnalysis(BytecodeAnalysis& bca, std::ostream& Out )
571 Out << "\nSummary Analysis Of " << bca.ModuleId << ": \n\n";
572 print(Out, "Bytecode Analysis Of Module", bca.ModuleId);
573 print(Out, "Bytecode Version Number", bca.version);
574 print(Out, "File Size", bca.byteSize);
575 print(Out, "Module Bytes",
576 double(bca.BlockSizes[BytecodeFormat::ModuleBlockID]),
577 double(bca.byteSize));
578 print(Out, "Function Bytes",
579 double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]),
580 double(bca.byteSize));
581 print(Out, "Global Types Bytes",
582 double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]),
583 double(bca.byteSize));
584 print(Out, "Constant Pool Bytes",
585 double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]),
586 double(bca.byteSize));
587 print(Out, "Module Globals Bytes",
588 double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]),
589 double(bca.byteSize));
590 print(Out, "Instruction List Bytes",
591 double(bca.BlockSizes[BytecodeFormat::InstructionListBlockID]),
592 double(bca.byteSize));
593 print(Out, "Value Symbol Table Bytes",
594 double(bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID]),
595 double(bca.byteSize));
596 print(Out, "Type Symbol Table Bytes",
597 double(bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID]),
598 double(bca.byteSize));
599 print(Out, "Alignment Bytes",
600 double(bca.numAlignment), double(bca.byteSize));
601 print(Out, "Block Header Bytes",
602 double(bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse]),
603 double(bca.byteSize));
604 print(Out, "Dependent Libraries Bytes", double(bca.libSize),
605 double(bca.byteSize));
606 print(Out, "Number Of Bytecode Blocks", bca.numBlocks);
607 print(Out, "Number Of Functions", bca.numFunctions);
608 print(Out, "Number Of Types", bca.numTypes);
609 print(Out, "Number Of Constants", bca.numConstants);
610 print(Out, "Number Of Global Variables", bca.numGlobalVars);
611 print(Out, "Number Of Values", bca.numValues);
612 print(Out, "Number Of Basic Blocks", bca.numBasicBlocks);
613 print(Out, "Number Of Instructions", bca.numInstructions);
614 print(Out, "Number Of Long Instructions", bca.longInstructions);
615 print(Out, "Number Of Operands", bca.numOperands);
616 print(Out, "Number Of Symbol Tables", bca.numSymTab);
617 print(Out, "Number Of Dependent Libs", bca.numLibraries);
618 print(Out, "Total Instruction Size", bca.instructionSize);
619 print(Out, "Average Instruction Size",
620 double(bca.instructionSize)/double(bca.numInstructions));
622 print(Out, "Maximum Type Slot Number", bca.maxTypeSlot);
623 print(Out, "Maximum Value Slot Number", bca.maxValueSlot);
624 print(Out, "Bytes Per Value ", bca.fileDensity);
625 print(Out, "Bytes Per Global", bca.globalsDensity);
626 print(Out, "Bytes Per Function", bca.functionDensity);
628 if (bca.detailedResults) {
629 Out << "\nDetailed Analysis Of " << bca.ModuleId << " Functions:\n";
631 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator I =
632 bca.FunctionInfo.begin();
633 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator E =
634 bca.FunctionInfo.end();
637 Out << std::left << std::setw(0) << "\n";
638 if (I->second.numBasicBlocks == 0) Out << "External ";
639 Out << "Function: " << I->second.name << "\n";
640 print(Out, "Type:", I->second.description);
641 print(Out, "Byte Size", I->second.byteSize);
642 if (I->second.numBasicBlocks) {
643 print(Out, "Basic Blocks", I->second.numBasicBlocks);
644 print(Out, "Instructions", I->second.numInstructions);
645 print(Out, "Long Instructions", I->second.longInstructions);
646 print(Out, "Operands", I->second.numOperands);
647 print(Out, "Instruction Size", I->second.instructionSize);
648 print(Out, "Average Instruction Size",
649 double(I->second.instructionSize) / I->second.numInstructions);
650 print(Out, "Bytes Per Instruction", I->second.density);
656 if ( bca.progressiveVerify )
657 Out << bca.VerifyInfo;
660 // AnalyzeBytecodeFile - analyze one file
661 Module* llvm::AnalyzeBytecodeFile(const std::string &Filename, ///< File to analyze
662 BytecodeAnalysis& bca, ///< Statistical output
663 BCDecompressor_t *BCDC,
664 std::string *ErrMsg, ///< Error output
665 std::ostream* output ///< Dump output
667 BytecodeHandler* AH = new AnalyzerHandler(bca, output);
668 ModuleProvider* MP = getBytecodeModuleProvider(Filename, BCDC, ErrMsg, AH);
670 Module *M = MP->releaseModule(ErrMsg);