1192d6a366dec9698a32b7affa6c5e038b4c103b
[oota-llvm.git] / tools / gccas / gccas.cpp
1 //===-- gccas.cpp - The "optimizing assembler" used by the GCC frontend ---===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is designed to be used by the GCC frontend for creating bytecode
11 // files from its intermediate LLVM assembly.  The requirements for this utility
12 // are thus slightly different than that of the standard `as' util.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "llvm/Module.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/Analysis/LoadValueNumbering.h"
19 #include "llvm/Analysis/Verifier.h"
20 #include "llvm/Assembly/Parser.h"
21 #include "llvm/Bytecode/WriteBytecodePass.h"
22 #include "llvm/Target/TargetData.h"
23 #include "llvm/Transforms/IPO.h"
24 #include "llvm/Transforms/Scalar.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/System/Signals.h"
27 #include <memory>
28 #include <fstream>
29
30 using namespace llvm;
31
32 namespace {
33   cl::opt<std::string>
34   InputFilename(cl::Positional,cl::desc("<input llvm assembly>"),cl::init("-"));
35
36   cl::opt<std::string> 
37   OutputFilename("o", cl::desc("Override output filename"),
38                  cl::value_desc("filename"));
39
40   cl::opt<bool>   
41   Verify("verify", cl::desc("Verify each pass result"));
42
43   cl::opt<bool>
44   DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
45
46   cl::opt<bool>
47   DisableOptimizations("disable-opt",
48                        cl::desc("Do not run any optimization passes"));
49
50   cl::opt<bool>
51   StripDebug("strip-debug",
52              cl::desc("Strip debugger symbol info from translation unit"));
53
54   cl::opt<bool> 
55   NoCompress("disable-compression", cl::init(false),
56              cl::desc("Don't compress the generated bytecode"));
57
58   cl::opt<bool> TF("traditional-format", cl::Hidden,
59     cl::desc("Compatibility option: ignored"));
60 }
61
62
63 static inline void addPass(PassManager &PM, Pass *P) {
64   // Add the pass to the pass manager...
65   PM.add(P);
66   
67   // If we are verifying all of the intermediate steps, add the verifier...
68   if (Verify) PM.add(createVerifierPass());
69 }
70
71
72 void AddConfiguredTransformationPasses(PassManager &PM) {
73   PM.add(createVerifierPass());                  // Verify that input is correct
74
75   addPass(PM, createLowerSetJmpPass());          // Lower llvm.setjmp/.longjmp
76   addPass(PM, createFunctionResolvingPass());    // Resolve (...) functions
77
78   // If the -strip-debug command line option was specified, do it.
79   if (StripDebug)
80     addPass(PM, createStripSymbolsPass(true));
81
82   if (DisableOptimizations) return;
83
84   addPass(PM, createRaiseAllocationsPass());     // call %malloc -> malloc inst
85   addPass(PM, createCFGSimplificationPass());    // Clean up disgusting code
86   addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
87   addPass(PM, createGlobalOptimizerPass());      // Optimize out global vars
88   addPass(PM, createGlobalDCEPass());            // Remove unused fns and globs
89   addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
90   addPass(PM, createDeadArgEliminationPass());   // Dead argument elimination
91   addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
92   addPass(PM, createCFGSimplificationPass());    // Clean up after IPCP & DAE
93
94   addPass(PM, createPruneEHPass());              // Remove dead EH info
95
96   if (!DisableInline)
97     addPass(PM, createFunctionInliningPass());   // Inline small functions
98   addPass(PM, createArgumentPromotionPass());    // Scalarize uninlined fn args
99
100   addPass(PM, createRaisePointerReferencesPass());// Recover type information
101   addPass(PM, createTailDuplicationPass());      // Simplify cfg by copying code
102   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
103   addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
104   addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
105
106   addPass(PM, createTailCallEliminationPass());  // Eliminate tail calls
107   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
108   addPass(PM, createLICMPass());                 // Hoist loop invariants
109   addPass(PM, createReassociatePass());          // Reassociate expressions
110   addPass(PM, createInstructionCombiningPass()); // Clean up after LICM/reassoc
111   addPass(PM, createIndVarSimplifyPass());       // Canonicalize indvars
112   addPass(PM, createLoopUnrollPass());           // Unroll small loops
113   addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
114   addPass(PM, createLoadValueNumberingPass());   // GVN for load instructions
115   addPass(PM, createGCSEPass());                 // Remove common subexprs
116   addPass(PM, createSCCPPass());                 // Constant prop with SCCP
117
118   // Run instcombine after redundancy elimination to exploit opportunities
119   // opened up by them.
120   addPass(PM, createInstructionCombiningPass());
121   addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
122   addPass(PM, createAggressiveDCEPass());        // SSA based 'Aggressive DCE'
123   addPass(PM, createCFGSimplificationPass());    // Merge & remove BBs
124   addPass(PM, createDeadTypeEliminationPass());  // Eliminate dead types
125   addPass(PM, createConstantMergePass());        // Merge dup global constants
126 }
127
128
129 int main(int argc, char **argv) {
130   try {
131     cl::ParseCommandLineOptions(argc, argv, 
132                                 " llvm .s -> .o assembler for GCC\n");
133     sys::PrintStackTraceOnErrorSignal();
134
135     std::auto_ptr<Module> M;
136     try {
137       // Parse the file now...
138       M.reset(ParseAssemblyFile(InputFilename));
139     } catch (const ParseException &E) {
140       std::cerr << argv[0] << ": " << E.getMessage() << "\n";
141       return 1;
142     }
143
144     if (M.get() == 0) {
145       std::cerr << argv[0] << ": assembly didn't read correctly.\n";
146       return 1;
147     }
148
149     std::ostream *Out = 0;
150     if (OutputFilename == "") {   // Didn't specify an output filename?
151       if (InputFilename == "-") {
152         OutputFilename = "-";
153       } else {
154         std::string IFN = InputFilename;
155         int Len = IFN.length();
156         if (IFN[Len-2] == '.' && IFN[Len-1] == 's') {   // Source ends in .s?
157           OutputFilename = std::string(IFN.begin(), IFN.end()-2);
158         } else {
159           OutputFilename = IFN;   // Append a .o to it
160         }
161         OutputFilename += ".o";
162       }
163     }
164
165     if (OutputFilename == "-")
166       // FIXME: cout is not binary!
167       Out = &std::cout;
168     else {
169       std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
170                                    std::ios::binary;
171       Out = new std::ofstream(OutputFilename.c_str(), io_mode);
172
173       // Make sure that the Out file gets unlinked from the disk if we get a
174       // signal
175       sys::RemoveFileOnSignal(sys::Path(OutputFilename));
176     }
177
178     
179     if (!Out->good()) {
180       std::cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
181       return 1;
182     }
183
184     // In addition to just parsing the input from GCC, we also want to spiff it up
185     // a little bit.  Do this now.
186     //
187     PassManager Passes;
188
189     // Add an appropriate TargetData instance for this module...
190     Passes.add(new TargetData("gccas", M.get()));
191
192     // Add all of the transformation passes to the pass manager to do the cleanup
193     // and optimization of the GCC output.
194     //
195     AddConfiguredTransformationPasses(Passes);
196
197     // Make sure everything is still good.
198     Passes.add(createVerifierPass());
199
200     // Write bytecode to file...
201     Passes.add(new WriteBytecodePass(Out,false,!NoCompress));
202
203     // Run our queue of passes all at once now, efficiently.
204     Passes.run(*M.get());
205
206     if (Out != &std::cout) delete Out;
207     return 0;
208   } catch (const std::string& msg) {
209     std::cerr << argv[0] << ": " << msg << "\n";
210   } catch (...) {
211     std::cerr << argv[0] << ": Unexpected unknown exception occurred.\n";
212   }
213   return 1;
214 }