7de05c6889266f0d60cd4761a1488a6aa51696e0
[oota-llvm.git] / tools / gccas / gccas.cpp
1 //===----------------------------------------------------------------------===//
2 // LLVM 'GCCAS' UTILITY 
3 //
4 // This utility is designed to be used by the GCC frontend for creating bytecode
5 // files from its intermediate LLVM assembly.  The requirements for this utility
6 // are thus slightly different than that of the standard `as' util.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "llvm/Module.h"
11 #include "llvm/PassManager.h"
12 #include "llvm/Analysis/LoadValueNumbering.h"
13 #include "llvm/Analysis/Verifier.h"
14 #include "llvm/Assembly/Parser.h"
15 #include "llvm/Bytecode/WriteBytecodePass.h"
16 #include "llvm/Target/TargetData.h"
17 #include "llvm/Transforms/RaisePointerReferences.h"
18 #include "llvm/Transforms/IPO.h"
19 #include "llvm/Transforms/Scalar.h"
20 #include "Support/CommandLine.h"
21 #include "Support/Signals.h"
22 #include <memory>
23 #include <fstream>
24
25 namespace {
26   cl::opt<std::string>
27   InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));
28
29   cl::opt<std::string> 
30   OutputFilename("o", cl::desc("Override output filename"),
31                  cl::value_desc("filename"));
32
33   cl::opt<int>
34   RunNPasses("stopAfterNPasses",
35              cl::desc("Only run the first N passes of gccas"), cl::Hidden,
36              cl::value_desc("# passes"));
37
38   cl::opt<bool>   
39   Verify("verify", cl::desc("Verify each pass result"));
40 }
41
42
43 static inline void addPass(PassManager &PM, Pass *P) {
44   static int NumPassesCreated = 0;
45   
46   // If we haven't already created the number of passes that was requested...
47   if (RunNPasses == 0 || RunNPasses > NumPassesCreated) {
48     // Add the pass to the pass manager...
49     PM.add(P);
50
51     // If we are verifying all of the intermediate steps, add the verifier...
52     if (Verify) PM.add(createVerifierPass());
53
54     // Keep track of how many passes we made for -stopAfterNPasses
55     ++NumPassesCreated;
56   } else {
57     delete P;             // We don't want this pass to run, just delete it now
58   }
59 }
60
61
62 void AddConfiguredTransformationPasses(PassManager &PM) {
63   PM.add(createVerifierPass());                  // Verify that input is correct
64   addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions
65   addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
66   addPass(PM, createGlobalDCEPass());            // Remove unused globals
67   addPass(PM, createPruneEHPass());              // Remove dead EH info
68   addPass(PM, createFunctionInliningPass());     // Inline small functions
69
70   addPass(PM, createInstructionCombiningPass()); // Cleanup code for raise
71   addPass(PM, createRaisePointerReferencesPass());// Recover type information
72   addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
73   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
74   addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
75   addPass(PM, createPromoteMemoryToRegister());  // Promote alloca's to regs
76   addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
77
78
79   addPass(PM, createIndVarSimplifyPass());       // Simplify indvars
80   addPass(PM, createReassociatePass());          // Reassociate expressions
81   addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
82   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
83   addPass(PM, createLICMPass());                 // Hoist loop invariants
84   addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
85   addPass(PM, createGCSEPass());                 // Remove common subexprs
86   addPass(PM, createSCCPPass());                 // Constant prop with SCCP
87
88   // Run instcombine after redundancy elimination to exploit opportunities
89   // opened up by them.
90   addPass(PM, createInstructionCombiningPass());
91   addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
92   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
93   addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
94   addPass(PM, createConstantMergePass());        // Merge dup global constants
95 }
96
97
98 int main(int argc, char **argv) {
99   cl::ParseCommandLineOptions(argc, argv, " llvm .s -> .o assembler for GCC\n");
100
101   std::auto_ptr<Module> M;
102   try {
103     // Parse the file now...
104     M.reset(ParseAssemblyFile(InputFilename));
105   } catch (const ParseException &E) {
106     std::cerr << argv[0] << ": " << E.getMessage() << "\n";
107     return 1;
108   }
109
110   if (M.get() == 0) {
111     std::cerr << argv[0] << ": assembly didn't read correctly.\n";
112     return 1;
113   }
114
115   std::ostream *Out = 0;
116   if (OutputFilename == "") {   // Didn't specify an output filename?
117     if (InputFilename == "-") {
118       OutputFilename = "-";
119     } else {
120       std::string IFN = InputFilename;
121       int Len = IFN.length();
122       if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
123         OutputFilename = std::string(IFN.begin(), IFN.end()-2);
124       } else {
125         OutputFilename = IFN;   // Append a .o to it
126       }
127       OutputFilename += ".o";
128     }
129   }
130
131   if (OutputFilename == "-")
132     Out = &std::cout;
133   else {
134     Out = new std::ofstream(OutputFilename.c_str(), std::ios::out);
135
136     // Make sure that the Out file gets unlink'd from the disk if we get a
137     // signal
138     RemoveFileOnSignal(OutputFilename);
139   }
140
141   
142   if (!Out->good()) {
143     std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
144     return 1;
145   }
146
147   // In addition to just parsing the input from GCC, we also want to spiff it up
148   // a little bit.  Do this now.
149   //
150   PassManager Passes;
151
152   // Add an appropriate TargetData instance for this module...
153   Passes.add(new TargetData("gccas", M.get()));
154
155   // Add all of the transformation passes to the pass manager to do the cleanup
156   // and optimization of the GCC output.
157   //
158   AddConfiguredTransformationPasses(Passes);
159
160   // Write bytecode to file...
161   Passes.add(new WriteBytecodePass(Out));
162
163   // Run our queue of passes all at once now, efficiently.
164   Passes.run(*M.get());
165
166   if (Out != &std::cout) delete Out;
167   return 0;
168 }