3bbf5f8394ef8272f92e62fbe812ce743dfe2859
[oota-llvm.git] / tools / llvm-bcanalyzer / llvm-bcanalyzer.cpp
1 //===-- llvm-bcanalyzer.cpp - Byte Code Analyzer --------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
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.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This tool may be invoked in the following manner:
11 //  llvm-bcanalyzer [options]      - Read LLVM bytecode from stdin
12 //  llvm-bcanalyzer [options] x.bc - Read LLVM bytecode from the x.bc file
13 //
14 //  Options:
15 //      --help      - Output information about command line switches
16 //      --nodetails - Don't print out detailed informaton about individual
17 //                    blocks and functions
18 //      --dump      - Dump low-level bytecode structure in readable format
19 //
20 // This tool provides analytical information about a bytecode file. It is
21 // intended as an aid to developers of bytecode reading and writing software. It
22 // produces on std::out a summary of the bytecode file that shows various
23 // statistics about the contents of the file. By default this information is
24 // detailed and contains information about individual bytecode blocks and the
25 // functions in the module. To avoid this more detailed output, use the
26 // -nodetails option to limit the output to just module level information.
27 // The tool is also able to print a bytecode file in a straight forward text
28 // format that shows the containment and relationships of the information in
29 // the bytecode file (-dump option).
30 //
31 //===----------------------------------------------------------------------===//
32
33 #include "llvm/Analysis/Verifier.h"
34 #include "llvm/Bitcode/BitstreamReader.h"
35 #include "llvm/Bitcode/LLVMBitCodes.h"
36 #include "llvm/Bytecode/Analyzer.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compressor.h"
39 #include "llvm/Support/ManagedStatic.h"
40 #include "llvm/Support/MemoryBuffer.h"
41 #include "llvm/System/Signals.h"
42 #include <fstream>
43 #include <iostream>
44 #include <algorithm>
45 using namespace llvm;
46
47 static cl::opt<std::string>
48   InputFilename(cl::Positional, cl::desc("<input bytecode>"), cl::init("-"));
49
50 static cl::opt<std::string>
51   OutputFilename("-o", cl::init("-"), cl::desc("<output file>"));
52
53 static cl::opt<bool> NoDetails("nodetails", cl::desc("Skip detailed output"));
54 static cl::opt<bool> Dump("dump", cl::desc("Dump low level bytecode trace"));
55 static cl::opt<bool> Verify("verify", cl::desc("Progressively verify module"));
56
57 //===----------------------------------------------------------------------===//
58 // Bitcode specific analysis.
59 //===----------------------------------------------------------------------===//
60
61 static cl::opt<bool> Bitcode("bitcode", cl::desc("Read a bitcode file"));
62 static cl::opt<bool> NoHistogram("disable-histogram",
63                                  cl::desc("Do not print per-code histogram"));
64
65 static cl::opt<bool>
66 NonSymbolic("non-symbolic",
67             cl::desc("Emit numberic info in dump even if"
68                      " symbolic info is available"));
69
70 /// CurStreamType - If we can sniff the flavor of this stream, we can produce 
71 /// better dump info.
72 static enum {
73   UnknownBitstream,
74   LLVMIRBitstream
75 } CurStreamType;
76
77
78 /// GetBlockName - Return a symbolic block name if known, otherwise return
79 /// null.
80 static const char *GetBlockName(unsigned BlockID) {
81   // Standard blocks for all bitcode files.
82   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
83     if (BlockID == bitc::BLOCKINFO_BLOCK_ID)
84       return "BLOCKINFO_BLOCK";
85     return 0;
86   }
87   
88   if (CurStreamType != LLVMIRBitstream) return 0;
89   
90   switch (BlockID) {
91   default:                          return 0;
92   case bitc::MODULE_BLOCK_ID:       return "MODULE_BLOCK";
93   case bitc::PARAMATTR_BLOCK_ID:    return "PARAMATTR_BLOCK";
94   case bitc::TYPE_BLOCK_ID:         return "TYPE_BLOCK";
95   case bitc::CONSTANTS_BLOCK_ID:    return "CONSTANTS_BLOCK";
96   case bitc::FUNCTION_BLOCK_ID:     return "FUNCTION_BLOCK";
97   case bitc::TYPE_SYMTAB_BLOCK_ID:  return "TYPE_SYMTAB";
98   case bitc::VALUE_SYMTAB_BLOCK_ID: return "VALUE_SYMTAB";
99   }
100 }
101
102 /// GetCodeName - Return a symbolic code name if known, otherwise return
103 /// null.
104 static const char *GetCodeName(unsigned CodeID, unsigned BlockID) {
105   // Standard blocks for all bitcode files.
106   if (BlockID < bitc::FIRST_APPLICATION_BLOCKID) {
107     if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
108       switch (CodeID) {
109       default: return 0;
110       case bitc::MODULE_CODE_VERSION:     return "VERSION";
111       }
112     }
113     return 0;
114   }
115   
116   if (CurStreamType != LLVMIRBitstream) return 0;
117   
118   switch (BlockID) {
119   default: return 0;
120   case bitc::MODULE_BLOCK_ID:
121     switch (CodeID) {
122     default: return 0;
123     case bitc::MODULE_CODE_VERSION:     return "VERSION";
124     case bitc::MODULE_CODE_TRIPLE:      return "TRIPLE";
125     case bitc::MODULE_CODE_DATALAYOUT:  return "DATALAYOUT";
126     case bitc::MODULE_CODE_ASM:         return "ASM";
127     case bitc::MODULE_CODE_SECTIONNAME: return "SECTIONNAME";
128     case bitc::MODULE_CODE_DEPLIB:      return "DEPLIB";
129     case bitc::MODULE_CODE_GLOBALVAR:   return "GLOBALVAR";
130     case bitc::MODULE_CODE_FUNCTION:    return "FUNCTION";
131     case bitc::MODULE_CODE_ALIAS:       return "ALIAS";
132     case bitc::MODULE_CODE_PURGEVALS:   return "PURGEVALS";
133     }
134   case bitc::PARAMATTR_BLOCK_ID:
135     switch (CodeID) {
136     default: return 0;
137     case bitc::PARAMATTR_CODE_ENTRY: return "ENTRY";
138     }
139   case bitc::TYPE_BLOCK_ID:
140     switch (CodeID) {
141     default: return 0;
142     case bitc::TYPE_CODE_NUMENTRY: return "NUMENTRY";
143     case bitc::TYPE_CODE_VOID:     return "VOID";
144     case bitc::TYPE_CODE_FLOAT:    return "FLOAT";
145     case bitc::TYPE_CODE_DOUBLE:   return "DOUBLE";
146     case bitc::TYPE_CODE_LABEL:    return "LABEL";
147     case bitc::TYPE_CODE_OPAQUE:   return "OPAQUE";
148     case bitc::TYPE_CODE_INTEGER:  return "INTEGER";
149     case bitc::TYPE_CODE_POINTER:  return "POINTER";
150     case bitc::TYPE_CODE_FUNCTION: return "FUNCTION";
151     case bitc::TYPE_CODE_STRUCT:   return "STRUCT";
152     case bitc::TYPE_CODE_ARRAY:    return "ARRAY";
153     case bitc::TYPE_CODE_VECTOR:   return "VECTOR";
154     }
155     
156   case bitc::CONSTANTS_BLOCK_ID:
157     switch (CodeID) {
158     default: return 0;
159     case bitc::CST_CODE_SETTYPE:       return "SETTYPE";
160     case bitc::CST_CODE_NULL:          return "NULL";
161     case bitc::CST_CODE_UNDEF:         return "UNDEF";
162     case bitc::CST_CODE_INTEGER:       return "INTEGER";
163     case bitc::CST_CODE_WIDE_INTEGER:  return "WIDE_INTEGER";
164     case bitc::CST_CODE_FLOAT:         return "FLOAT";
165     case bitc::CST_CODE_AGGREGATE:     return "AGGREGATE";
166     case bitc::CST_CODE_CE_BINOP:      return "CE_BINOP";
167     case bitc::CST_CODE_CE_CAST:       return "CE_CAST";
168     case bitc::CST_CODE_CE_GEP:        return "CE_GEP";
169     case bitc::CST_CODE_CE_SELECT:     return "CE_SELECT";
170     case bitc::CST_CODE_CE_EXTRACTELT: return "CE_EXTRACTELT";
171     case bitc::CST_CODE_CE_INSERTELT:  return "CE_INSERTELT";
172     case bitc::CST_CODE_CE_SHUFFLEVEC: return "CE_SHUFFLEVEC";
173     case bitc::CST_CODE_CE_CMP:        return "CE_CMP";
174     }        
175   case bitc::FUNCTION_BLOCK_ID:
176     switch (CodeID) {
177     default: return 0;
178     case bitc::FUNC_CODE_DECLAREBLOCKS: return "DECLAREBLOCKS";
179     
180     case bitc::FUNC_CODE_INST_BINOP:       return "INST_BINOP";
181     case bitc::FUNC_CODE_INST_CAST:        return "INST_CAST";
182     case bitc::FUNC_CODE_INST_GEP:         return "INST_GEP";
183     case bitc::FUNC_CODE_INST_SELECT:      return "INST_SELECT";
184     case bitc::FUNC_CODE_INST_EXTRACTELT:  return "INST_EXTRACTELT";
185     case bitc::FUNC_CODE_INST_INSERTELT:   return "INST_INSERTELT";
186     case bitc::FUNC_CODE_INST_SHUFFLEVEC:  return "INST_SHUFFLEVEC";
187     case bitc::FUNC_CODE_INST_CMP:         return "INST_CMP";
188     
189     case bitc::FUNC_CODE_INST_RET:         return "INST_RET";
190     case bitc::FUNC_CODE_INST_BR:          return "INST_BR";
191     case bitc::FUNC_CODE_INST_SWITCH:      return "INST_SWITCH";
192     case bitc::FUNC_CODE_INST_INVOKE:      return "INST_INVOKE";
193     case bitc::FUNC_CODE_INST_UNWIND:      return "INST_UNWIND";
194     case bitc::FUNC_CODE_INST_UNREACHABLE: return "INST_UNREACHABLE";
195     
196     case bitc::FUNC_CODE_INST_PHI:         return "INST_PHI";
197     case bitc::FUNC_CODE_INST_MALLOC:      return "INST_MALLOC";
198     case bitc::FUNC_CODE_INST_FREE:        return "INST_FREE";
199     case bitc::FUNC_CODE_INST_ALLOCA:      return "INST_ALLOCA";
200     case bitc::FUNC_CODE_INST_LOAD:        return "INST_LOAD";
201     case bitc::FUNC_CODE_INST_STORE:       return "INST_STORE";
202     case bitc::FUNC_CODE_INST_CALL:        return "INST_CALL";
203     case bitc::FUNC_CODE_INST_VAARG:       return "INST_VAARG";
204     }
205   case bitc::TYPE_SYMTAB_BLOCK_ID:
206     switch (CodeID) {
207     default: return 0;
208     case bitc::TST_CODE_ENTRY: return "ENTRY";
209     }
210   case bitc::VALUE_SYMTAB_BLOCK_ID:
211     switch (CodeID) {
212     default: return 0;
213     case bitc::VST_CODE_ENTRY: return "ENTRY";
214     case bitc::VST_CODE_BBENTRY: return "BBENTRY";
215     }
216   }
217 }
218
219
220 struct PerBlockIDStats {
221   /// NumInstances - This the number of times this block ID has been seen.
222   unsigned NumInstances;
223   
224   /// NumBits - The total size in bits of all of these blocks.
225   uint64_t NumBits;
226   
227   /// NumSubBlocks - The total number of blocks these blocks contain.
228   unsigned NumSubBlocks;
229   
230   /// NumAbbrevs - The total number of abbreviations.
231   unsigned NumAbbrevs;
232   
233   /// NumRecords - The total number of records these blocks contain, and the 
234   /// number that are abbreviated.
235   unsigned NumRecords, NumAbbreviatedRecords;
236   
237   /// CodeFreq - Keep track of the number of times we see each code.
238   std::vector<unsigned> CodeFreq;
239   
240   PerBlockIDStats()
241     : NumInstances(0), NumBits(0),
242       NumSubBlocks(0), NumAbbrevs(0), NumRecords(0), NumAbbreviatedRecords(0) {}
243 };
244
245 static std::map<unsigned, PerBlockIDStats> BlockIDStats;
246
247
248
249 /// Error - All bitcode analysis errors go through this function, making this a
250 /// good place to breakpoint if debugging.
251 static bool Error(const std::string &Err) {
252   std::cerr << Err << "\n";
253   return true;
254 }
255
256 /// ParseBlock - Read a block, updating statistics, etc.
257 static bool ParseBlock(BitstreamReader &Stream, unsigned IndentLevel) {
258   std::string Indent(IndentLevel*2, ' ');
259   uint64_t BlockBitStart = Stream.GetCurrentBitNo();
260   unsigned BlockID = Stream.ReadSubBlockID();
261
262   // Get the statistics for this BlockID.
263   PerBlockIDStats &BlockStats = BlockIDStats[BlockID];
264   
265   BlockStats.NumInstances++;
266   
267   // BLOCKINFO is a special part of the stream.
268   if (BlockID == bitc::BLOCKINFO_BLOCK_ID) {
269     if (Dump) std::cerr << Indent << "<BLOCKINFO_BLOCK/>\n";
270     if (Stream.ReadBlockInfoBlock())
271       return Error("Malformed BlockInfoBlock");
272     uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
273     BlockStats.NumBits += BlockBitEnd-BlockBitStart;
274     return false;
275   }
276   
277   unsigned NumWords = 0;
278   if (Stream.EnterSubBlock(BlockID, &NumWords))
279     return Error("Malformed block record");
280
281   const char *BlockName = 0;
282   if (Dump) {
283     std::cerr << Indent << "<";
284     if ((BlockName = GetBlockName(BlockID)))
285       std::cerr << BlockName;
286     else
287       std::cerr << "UnknownBlock" << BlockID;
288     
289     if (NonSymbolic && BlockName)
290       std::cerr << " BlockID=" << BlockID;
291     
292     std::cerr << " NumWords=" << NumWords
293               << " BlockCodeSize=" << Stream.GetAbbrevIDWidth() << ">\n";
294   }
295   
296   SmallVector<uint64_t, 64> Record;
297
298   // Read all the records for this block.
299   while (1) {
300     if (Stream.AtEndOfStream())
301       return Error("Premature end of bitstream");
302
303     // Read the code for this record.
304     unsigned AbbrevID = Stream.ReadCode();
305     switch (AbbrevID) {
306     case bitc::END_BLOCK: {
307       if (Stream.ReadBlockEnd())
308         return Error("Error at end of block");
309       uint64_t BlockBitEnd = Stream.GetCurrentBitNo();
310       BlockStats.NumBits += BlockBitEnd-BlockBitStart;
311       if (Dump) {
312         std::cerr << Indent << "</";
313         if (BlockName)
314           std::cerr << BlockName << ">\n";
315         else
316           std::cerr << "UnknownBlock" << BlockID << ">\n";
317       }
318       return false;
319     } 
320     case bitc::ENTER_SUBBLOCK: {
321       uint64_t SubBlockBitStart = Stream.GetCurrentBitNo();
322       if (ParseBlock(Stream, IndentLevel+1))
323         return true;
324       ++BlockStats.NumSubBlocks;
325       uint64_t SubBlockBitEnd = Stream.GetCurrentBitNo();
326       
327       // Don't include subblock sizes in the size of this block.
328       BlockBitStart += SubBlockBitEnd-SubBlockBitStart;
329       break;
330     }
331     case bitc::DEFINE_ABBREV:
332       Stream.ReadAbbrevRecord();
333       ++BlockStats.NumAbbrevs;
334       break;
335     default:
336       ++BlockStats.NumRecords;
337       if (AbbrevID != bitc::UNABBREV_RECORD)
338         ++BlockStats.NumAbbreviatedRecords;
339       
340       Record.clear();
341       unsigned Code = Stream.ReadRecord(AbbrevID, Record);
342
343       // Increment the # occurrences of this code.
344       if (BlockStats.CodeFreq.size() <= Code)
345         BlockStats.CodeFreq.resize(Code+1);
346       BlockStats.CodeFreq[Code]++;
347       
348       if (Dump) {
349         std::cerr << Indent << "  <";
350         if (const char *CodeName = GetCodeName(Code, BlockID))
351           std::cerr << CodeName;
352         else
353           std::cerr << "UnknownCode" << Code;
354         if (NonSymbolic && GetCodeName(Code, BlockID))
355           std::cerr << " codeid=" << Code;
356         if (AbbrevID != bitc::UNABBREV_RECORD)
357           std::cerr << " abbrevid=" << AbbrevID;
358
359         for (unsigned i = 0, e = Record.size(); i != e; ++i)
360           std::cerr << " op" << i << "=" << (int64_t)Record[i];
361         
362         std::cerr << "/>\n";
363       }
364       
365       break;
366     }
367   }
368 }
369
370 static void PrintSize(double Bits) {
371   std::cerr << Bits << "b/" << Bits/8 << "B/" << Bits/32 << "W";
372 }
373
374
375 /// AnalyzeBitcode - Analyze the bitcode file specified by InputFilename.
376 static int AnalyzeBitcode() {
377   // Read the input file.
378   MemoryBuffer *Buffer;
379   if (InputFilename == "-")
380     Buffer = MemoryBuffer::getSTDIN();
381   else
382     Buffer = MemoryBuffer::getFile(&InputFilename[0], InputFilename.size());
383
384   if (Buffer == 0)
385     return Error("Error reading '" + InputFilename + "'.");
386   
387   if (Buffer->getBufferSize() & 3)
388     return Error("Bitcode stream should be a multiple of 4 bytes in length");
389   
390   unsigned char *BufPtr = (unsigned char *)Buffer->getBufferStart();
391   BitstreamReader Stream(BufPtr, BufPtr+Buffer->getBufferSize());
392
393   
394   // Read the stream signature.
395   char Signature[6];
396   Signature[0] = Stream.Read(8);
397   Signature[1] = Stream.Read(8);
398   Signature[2] = Stream.Read(4);
399   Signature[3] = Stream.Read(4);
400   Signature[4] = Stream.Read(4);
401   Signature[5] = Stream.Read(4);
402   
403   // Autodetect the file contents, if it is one we know.
404   CurStreamType = UnknownBitstream;
405   if (Signature[0] == 'B' && Signature[1] == 'C' &&
406       Signature[2] == 0x0 && Signature[3] == 0xC &&
407       Signature[4] == 0xE && Signature[5] == 0xD)
408     CurStreamType = LLVMIRBitstream;
409
410   unsigned NumTopBlocks = 0;
411   
412   // Parse the top-level structure.  We only allow blocks at the top-level.
413   while (!Stream.AtEndOfStream()) {
414     unsigned Code = Stream.ReadCode();
415     if (Code != bitc::ENTER_SUBBLOCK)
416       return Error("Invalid record at top-level");
417     
418     if (ParseBlock(Stream, 0))
419       return true;
420     ++NumTopBlocks;
421   }
422   
423   if (Dump) std::cerr << "\n\n";
424   
425   uint64_t BufferSizeBits = Buffer->getBufferSize()*8;
426   // Print a summary of the read file.
427   std::cerr << "Summary of " << InputFilename << ":\n";
428   std::cerr << "         Total size: ";
429   PrintSize(BufferSizeBits);
430   std::cerr << "\n";
431   std::cerr << "        Stream type: ";
432   switch (CurStreamType) {
433   default: assert(0 && "Unknown bitstream type");
434   case UnknownBitstream: std::cerr << "unknown\n"; break;
435   case LLVMIRBitstream:  std::cerr << "LLVM IR\n"; break;
436   }
437   std::cerr << "  # Toplevel Blocks: " << NumTopBlocks << "\n";
438   std::cerr << "\n";
439
440   // Emit per-block stats.
441   std::cerr << "Per-block Summary:\n";
442   for (std::map<unsigned, PerBlockIDStats>::iterator I = BlockIDStats.begin(),
443        E = BlockIDStats.end(); I != E; ++I) {
444     std::cerr << "  Block ID #" << I->first;
445     if (const char *BlockName = GetBlockName(I->first))
446       std::cerr << " (" << BlockName << ")";
447     std::cerr << ":\n";
448     
449     const PerBlockIDStats &Stats = I->second;
450     std::cerr << "      Num Instances: " << Stats.NumInstances << "\n";
451     std::cerr << "         Total Size: ";
452     PrintSize(Stats.NumBits);
453     std::cerr << "\n";
454     std::cerr << "          % of file: "
455               << Stats.NumBits/(double)BufferSizeBits*100 << "\n";
456     if (Stats.NumInstances > 1) {
457       std::cerr << "       Average Size: ";
458       PrintSize(Stats.NumBits/(double)Stats.NumInstances);
459       std::cerr << "\n";
460       std::cerr << "  Tot/Avg SubBlocks: " << Stats.NumSubBlocks << "/"
461                 << Stats.NumSubBlocks/(double)Stats.NumInstances << "\n";
462       std::cerr << "    Tot/Avg Abbrevs: " << Stats.NumAbbrevs << "/"
463                 << Stats.NumAbbrevs/(double)Stats.NumInstances << "\n";
464       std::cerr << "    Tot/Avg Records: " << Stats.NumRecords << "/"
465                 << Stats.NumRecords/(double)Stats.NumInstances << "\n";
466     } else {
467       std::cerr << "      Num SubBlocks: " << Stats.NumSubBlocks << "\n";
468       std::cerr << "        Num Abbrevs: " << Stats.NumAbbrevs << "\n";
469       std::cerr << "        Num Records: " << Stats.NumRecords << "\n";
470     }
471     if (Stats.NumRecords)
472       std::cerr << "      % Abbrev Recs: " << (Stats.NumAbbreviatedRecords/
473                    (double)Stats.NumRecords)*100 << "\n";
474     std::cerr << "\n";
475     
476     // Print a histogram of the codes we see.
477     if (!NoHistogram && !Stats.CodeFreq.empty()) {
478       std::vector<std::pair<unsigned, unsigned> > FreqPairs;  // <freq,code>
479       for (unsigned i = 0, e = Stats.CodeFreq.size(); i != e; ++i)
480         if (unsigned Freq = Stats.CodeFreq[i])
481           FreqPairs.push_back(std::make_pair(Freq, i));
482       std::stable_sort(FreqPairs.begin(), FreqPairs.end());
483       std::reverse(FreqPairs.begin(), FreqPairs.end());
484       
485       std::cerr << "\tCode Histogram:\n";
486       for (unsigned i = 0, e = FreqPairs.size(); i != e; ++i) {
487         std::cerr << "\t\t" << FreqPairs[i].first << "\t";
488         if (const char *CodeName = GetCodeName(FreqPairs[i].second, I->first))
489           std::cerr << CodeName << "\n";
490         else
491           std::cerr << "UnknownCode" << FreqPairs[i].second << "\n";
492       }
493       std::cerr << "\n";
494       
495     }
496   }
497   return 0;
498 }
499
500
501 //===----------------------------------------------------------------------===//
502 // Bytecode specific analysis.
503 //===----------------------------------------------------------------------===//
504
505 int main(int argc, char **argv) {
506   llvm_shutdown_obj X;  // Call llvm_shutdown() on exit.
507   cl::ParseCommandLineOptions(argc, argv, " llvm-bcanalyzer file analyzer\n");
508   
509   sys::PrintStackTraceOnErrorSignal();
510   
511   if (Bitcode)
512     return AnalyzeBitcode();
513     
514   try {
515     std::ostream *Out = &std::cout;  // Default to printing to stdout...
516     std::string ErrorMessage;
517     BytecodeAnalysis bca;
518
519     /// Determine what to generate
520     bca.detailedResults = !NoDetails;
521     bca.progressiveVerify = Verify;
522
523     /// Analyze the bytecode file
524     Module* M = AnalyzeBytecodeFile(InputFilename, bca, 
525                                     Compressor::decompressToNewBuffer,
526                                     &ErrorMessage, (Dump?Out:0));
527
528     // All that bcanalyzer does is write the gathered statistics to the output
529     PrintBytecodeAnalysis(bca,*Out);
530
531     if (M && Verify) {
532       std::string verificationMsg;
533       if (verifyModule(*M, ReturnStatusAction, &verificationMsg))
534         std::cerr << "Final Verification Message: " << verificationMsg << "\n";
535     }
536
537     if (Out != &std::cout) {
538       ((std::ofstream*)Out)->close();
539       delete Out;
540     }
541     return 0;
542   } catch (const std::string& msg) {
543     std::cerr << argv[0] << ": " << msg << "\n";
544   } catch (...) {
545     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
546   }
547   return 1;
548 }