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 handleTypeList(unsigned numEntries) {
183 bca.maxTypeSlot = numEntries - 1;
186 virtual void handleType( const Type* Ty ) {
190 WriteTypeSymbolic(*os,Ty,M);
195 virtual void handleFunctionDeclaration(
196 Function* Func ///< The function
201 *os << " Function Decl: ";
202 WriteTypeSymbolic(*os,Func->getType(),M);
203 *os <<", Linkage=" << Func->getLinkage();
204 *os <<", Visibility=" << Func->getVisibility();
209 virtual void handleGlobalInitializer(GlobalVariable* GV, Constant* CV) {
211 *os << " Initializer: GV=";
219 virtual void handleDependentLibrary(const std::string& libName) {
221 bca.libSize += libName.size() + (libName.size() < 128 ? 1 : 2);
223 *os << " Library: '" << libName << "'\n";
226 virtual void handleModuleGlobalsEnd() {
228 *os << " } END BLOCK: ModuleGlobalInfo\n";
229 if (bca.progressiveVerify) {
231 if (verifyModule(*M, ReturnStatusAction, &msg))
232 bca.VerifyInfo += "Verify@EndModuleGlobalInfo: " + msg + "\n";
236 virtual void handleTypeSymbolTableBegin(TypeSymbolTable* ST) {
239 *os << " BLOCK: TypeSymbolTable {\n";
241 virtual void handleValueSymbolTableBegin(Function* CF, ValueSymbolTable* ST) {
244 *os << " BLOCK: ValueSymbolTable {\n";
247 virtual void handleSymbolTableType(unsigned i, unsigned TypSlot,
248 const std::string& name ) {
250 *os << " Type " << i << " Slot=" << TypSlot
251 << " Name: " << name << "\n";
254 virtual void handleSymbolTableValue(unsigned TySlot, unsigned ValSlot,
255 const char *Name, unsigned NameLen) {
257 *os << " Value " << TySlot << " Slot=" << ValSlot
258 << " Name: " << std::string(Name, Name+NameLen) << "\n";
259 if (ValSlot > bca.maxValueSlot)
260 bca.maxValueSlot = ValSlot;
263 virtual void handleValueSymbolTableEnd() {
265 *os << " } END BLOCK: ValueSymbolTable\n";
268 virtual void handleTypeSymbolTableEnd() {
270 *os << " } END BLOCK: TypeSymbolTable\n";
273 virtual void handleFunctionBegin(Function* Func, unsigned Size) {
275 *os << " BLOCK: Function {\n"
276 << " Linkage: " << Func->getLinkage() << "\n"
277 << " Visibility: " << Func->getVisibility() << "\n"
279 WriteTypeSymbolic(*os,Func->getType(),M);
283 currFunc = &bca.FunctionInfo[Func];
284 std::ostringstream tmp;
285 WriteTypeSymbolic(tmp,Func->getType(),M);
286 currFunc->description = tmp.str();
287 currFunc->name = Func->getName();
288 currFunc->byteSize = Size;
289 currFunc->numInstructions = 0;
290 currFunc->numBasicBlocks = 0;
291 currFunc->numPhis = 0;
292 currFunc->numOperands = 0;
293 currFunc->density = 0.0;
294 currFunc->instructionSize = 0;
295 currFunc->longInstructions = 0;
299 virtual void handleFunctionEnd( Function* Func) {
301 *os << " } END BLOCK: Function\n";
302 currFunc->density = double(currFunc->byteSize) /
303 double(currFunc->numInstructions);
305 if (bca.progressiveVerify) {
307 if (verifyModule(*M, ReturnStatusAction, &msg))
308 bca.VerifyInfo += "Verify@EndFunction: " + msg + "\n";
312 virtual void handleBasicBlockBegin( unsigned blocknum) {
314 *os << " BLOCK: BasicBlock #" << blocknum << "{\n";
315 bca.numBasicBlocks++;
317 if ( currFunc ) currFunc->numBasicBlocks++;
320 virtual bool handleInstruction( unsigned Opcode, const Type* iType,
321 unsigned *Operands, unsigned NumOps,
325 *os << " INST: OpCode="
326 << Instruction::getOpcodeName(Opcode);
327 for (unsigned i = 0; i != NumOps; ++i)
328 *os << " Op(" << Operands[i] << ")";
332 bca.numInstructions++;
334 bca.instructionSize += Size;
335 if (Size > 4 ) bca.longInstructions++;
336 bca.numOperands += NumOps;
337 for (unsigned i = 0; i != NumOps; ++i)
338 if (Operands[i] > bca.maxValueSlot)
339 bca.maxValueSlot = Operands[i];
341 currFunc->numInstructions++;
342 currFunc->instructionSize += Size;
343 if (Size > 4 ) currFunc->longInstructions++;
344 if (Opcode == Instruction::PHI) currFunc->numPhis++;
346 return Instruction::isTerminator(Opcode);
349 virtual void handleBasicBlockEnd(unsigned blocknum) {
351 *os << " } END BLOCK: BasicBlock #" << blocknum << "\n";
354 virtual void handleGlobalConstantsBegin() {
356 *os << " BLOCK: GlobalConstants {\n";
359 virtual void handleConstantExpression(unsigned Opcode,
360 Constant**ArgVec, unsigned NumArgs, Constant* C) {
362 *os << " EXPR: " << Instruction::getOpcodeName(Opcode) << "\n";
363 for ( unsigned i = 0; i != NumArgs; ++i ) {
364 *os << " Arg#" << i << " "; ArgVec[i]->print(*os);
375 virtual void handleConstantValue( Constant * c ) {
385 virtual void handleConstantArray( const ArrayType* AT,
386 Constant**Elements, unsigned NumElts,
388 Constant* ArrayVal ) {
391 WriteTypeSymbolic(*os,AT,M);
392 *os << " TypeSlot=" << TypeSlot << "\n";
393 for (unsigned i = 0; i != NumElts; ++i) {
395 Elements[i]->print(*os);
399 ArrayVal->print(*os);
407 virtual void handleConstantStruct(
408 const StructType* ST,
409 Constant**Elements, unsigned NumElts,
414 WriteTypeSymbolic(*os,ST,M);
416 for ( unsigned i = 0; i != NumElts; ++i) {
417 *os << " #" << i << " "; Elements[i]->print(*os);
421 StructVal->print(*os);
428 virtual void handleConstantVector(
429 const VectorType* PT,
430 Constant**Elements, unsigned NumElts,
436 WriteTypeSymbolic(*os,PT,M);
437 *os << " TypeSlot=" << TypeSlot << "\n";
438 for ( unsigned i = 0; i != NumElts; ++i ) {
440 Elements[i]->print(*os);
444 VectorVal->print(*os);
452 virtual void handleConstantPointer( const PointerType* PT,
453 unsigned Slot, GlobalValue* GV ) {
456 WriteTypeSymbolic(*os,PT,M);
457 *os << " Slot=" << Slot << " GlobalValue=";
465 virtual void handleConstantString( const ConstantArray* CA ) {
475 virtual void handleGlobalConstantsEnd() {
477 *os << " } END BLOCK: GlobalConstants\n";
479 if (bca.progressiveVerify) {
481 if (verifyModule(*M, ReturnStatusAction, &msg))
482 bca.VerifyInfo += "Verify@EndGlobalConstants: " + msg + "\n";
486 virtual void handleAlignment(unsigned numBytes) {
487 bca.numAlignment += numBytes;
490 virtual void handleBlock(
491 unsigned BType, const unsigned char* StartPtr, unsigned Size) {
493 assert(BType >= BytecodeFormat::ModuleBlockID);
494 assert(BType < BytecodeFormat::NumberOfBlockIDs);
496 llvm::BytecodeFormat::BytecodeBlockIdentifiers(BType)] += Size;
498 if (bca.version < 3) // Check for long block headers versions
499 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 8;
501 bca.BlockSizes[llvm::BytecodeFormat::Reserved_DoNotUse] += 4;
505 } // end anonymous namespace
507 /// @brief Utility for printing a titled unsigned value with
508 /// an aligned colon.
509 inline static void print(std::ostream& Out, const char*title,
510 unsigned val, bool nl = true ) {
511 Out << std::setw(30) << std::right << title
512 << std::setw(0) << ": "
513 << std::setw(9) << val << "\n";
516 /// @brief Utility for printing a titled double value with an
518 inline static void print(std::ostream&Out, const char*title,
520 Out << std::setw(30) << std::right << title
521 << std::setw(0) << ": "
522 << std::setw(9) << std::setprecision(6) << val << "\n" ;
525 /// @brief Utility for printing a titled double value with a
526 /// percentage and aligned colon.
527 inline static void print(std::ostream&Out, const char*title,
528 double top, double bot ) {
529 Out << std::setw(30) << std::right << title
530 << std::setw(0) << ": "
531 << std::setw(9) << std::setprecision(6) << top
532 << " (" << std::left << std::setw(0) << std::setprecision(4)
533 << (top/bot)*100.0 << "%)\n";
536 /// @brief Utility for printing a titled string value with
537 /// an aligned colon.
538 inline static void print(std::ostream&Out, const char*title,
539 std::string val, bool nl = true) {
540 Out << std::setw(30) << std::right << title
541 << std::setw(0) << ": "
542 << std::left << val << (nl ? "\n" : "");
545 /// This function prints the contents of rhe BytecodeAnalysis structure in
546 /// a human legible form.
547 /// @brief Print BytecodeAnalysis structure to an ostream
548 void llvm::PrintBytecodeAnalysis(BytecodeAnalysis& bca, std::ostream& Out )
550 Out << "\nSummary Analysis Of " << bca.ModuleId << ": \n\n";
551 print(Out, "Bytecode Analysis Of Module", bca.ModuleId);
552 print(Out, "Bytecode Version Number", bca.version);
553 print(Out, "File Size", bca.byteSize);
554 print(Out, "Module Bytes",
555 double(bca.BlockSizes[BytecodeFormat::ModuleBlockID]),
556 double(bca.byteSize));
557 print(Out, "Function Bytes",
558 double(bca.BlockSizes[BytecodeFormat::FunctionBlockID]),
559 double(bca.byteSize));
560 print(Out, "Global Types Bytes",
561 double(bca.BlockSizes[BytecodeFormat::GlobalTypePlaneBlockID]),
562 double(bca.byteSize));
563 print(Out, "Constant Pool Bytes",
564 double(bca.BlockSizes[BytecodeFormat::ConstantPoolBlockID]),
565 double(bca.byteSize));
566 print(Out, "Module Globals Bytes",
567 double(bca.BlockSizes[BytecodeFormat::ModuleGlobalInfoBlockID]),
568 double(bca.byteSize));
569 print(Out, "Instruction List Bytes",
570 double(bca.BlockSizes[BytecodeFormat::InstructionListBlockID]),
571 double(bca.byteSize));
572 print(Out, "Value Symbol Table Bytes",
573 double(bca.BlockSizes[BytecodeFormat::ValueSymbolTableBlockID]),
574 double(bca.byteSize));
575 print(Out, "Type Symbol Table Bytes",
576 double(bca.BlockSizes[BytecodeFormat::TypeSymbolTableBlockID]),
577 double(bca.byteSize));
578 print(Out, "Alignment Bytes",
579 double(bca.numAlignment), double(bca.byteSize));
580 print(Out, "Block Header Bytes",
581 double(bca.BlockSizes[BytecodeFormat::Reserved_DoNotUse]),
582 double(bca.byteSize));
583 print(Out, "Dependent Libraries Bytes", double(bca.libSize),
584 double(bca.byteSize));
585 print(Out, "Number Of Bytecode Blocks", bca.numBlocks);
586 print(Out, "Number Of Functions", bca.numFunctions);
587 print(Out, "Number Of Types", bca.numTypes);
588 print(Out, "Number Of Constants", bca.numConstants);
589 print(Out, "Number Of Global Variables", bca.numGlobalVars);
590 print(Out, "Number Of Values", bca.numValues);
591 print(Out, "Number Of Basic Blocks", bca.numBasicBlocks);
592 print(Out, "Number Of Instructions", bca.numInstructions);
593 print(Out, "Number Of Long Instructions", bca.longInstructions);
594 print(Out, "Number Of Operands", bca.numOperands);
595 print(Out, "Number Of Symbol Tables", bca.numSymTab);
596 print(Out, "Number Of Dependent Libs", bca.numLibraries);
597 print(Out, "Total Instruction Size", bca.instructionSize);
598 print(Out, "Average Instruction Size",
599 double(bca.instructionSize)/double(bca.numInstructions));
601 print(Out, "Maximum Type Slot Number", bca.maxTypeSlot);
602 print(Out, "Maximum Value Slot Number", bca.maxValueSlot);
603 print(Out, "Bytes Per Value ", bca.fileDensity);
604 print(Out, "Bytes Per Global", bca.globalsDensity);
605 print(Out, "Bytes Per Function", bca.functionDensity);
607 if (bca.detailedResults) {
608 Out << "\nDetailed Analysis Of " << bca.ModuleId << " Functions:\n";
610 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator I =
611 bca.FunctionInfo.begin();
612 std::map<const Function*,BytecodeAnalysis::BytecodeFunctionInfo>::iterator E =
613 bca.FunctionInfo.end();
616 Out << std::left << std::setw(0) << "\n";
617 if (I->second.numBasicBlocks == 0) Out << "External ";
618 Out << "Function: " << I->second.name << "\n";
619 print(Out, "Type:", I->second.description);
620 print(Out, "Byte Size", I->second.byteSize);
621 if (I->second.numBasicBlocks) {
622 print(Out, "Basic Blocks", I->second.numBasicBlocks);
623 print(Out, "Instructions", I->second.numInstructions);
624 print(Out, "Long Instructions", I->second.longInstructions);
625 print(Out, "Operands", I->second.numOperands);
626 print(Out, "Instruction Size", I->second.instructionSize);
627 print(Out, "Average Instruction Size",
628 double(I->second.instructionSize) / I->second.numInstructions);
629 print(Out, "Bytes Per Instruction", I->second.density);
635 if ( bca.progressiveVerify )
636 Out << bca.VerifyInfo;
639 // AnalyzeBytecodeFile - analyze one file
640 Module* llvm::AnalyzeBytecodeFile(const std::string &Filename, ///< File to analyze
641 BytecodeAnalysis& bca, ///< Statistical output
642 BCDecompressor_t *BCDC,
643 std::string *ErrMsg, ///< Error output
644 std::ostream* output ///< Dump output
646 BytecodeHandler* AH = new AnalyzerHandler(bca, output);
647 ModuleProvider* MP = getBytecodeModuleProvider(Filename, BCDC, ErrMsg, AH);
649 Module *M = MP->releaseModule(ErrMsg);