1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
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.
8 //===----------------------------------------------------------------------===//
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Module.h"
16 #include "llvm/PassManager.h"
17 #include "llvm/Bytecode/Reader.h"
18 #include "llvm/Bytecode/WriteBytecodePass.h"
19 #include "llvm/Assembly/PrintModulePass.h"
20 #include "llvm/Analysis/Verifier.h"
21 #include "llvm/Target/TargetData.h"
22 #include "llvm/Target/TargetMachine.h"
23 #include "llvm/Support/PassNameParser.h"
24 #include "llvm/System/Signals.h"
25 #include "llvm/Support/PluginLoader.h"
26 #include "llvm/Support/Streams.h"
27 #include "llvm/Support/SystemUtils.h"
28 #include "llvm/Support/Timer.h"
29 #include "llvm/LinkAllPasses.h"
30 #include "llvm/LinkAllVMCore.h"
36 // The OptimizationList is automatically populated with registered Passes by the
39 static cl::list<const PassInfo*, bool, PassNameParser>
40 PassList(cl::desc("Optimizations available:"));
42 static cl::opt<bool> NoCompress("disable-compression", cl::init(false),
43 cl::desc("Don't compress the generated bytecode"));
45 // Other command line options...
47 static cl::opt<std::string>
48 InputFilename(cl::Positional, cl::desc("<input bytecode file>"),
49 cl::init("-"), cl::value_desc("filename"));
51 static cl::opt<std::string>
52 OutputFilename("o", cl::desc("Override output filename"),
53 cl::value_desc("filename"), cl::init("-"));
56 Force("f", cl::desc("Overwrite output files"));
59 PrintEachXForm("p", cl::desc("Print module after each transformation"));
62 NoOutput("disable-output",
63 cl::desc("Do not write result bytecode file"), cl::Hidden);
66 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
69 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
72 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
75 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
77 static Timer BytecodeLoadTimer("Bytecode Loader");
79 // ---------- Define Printers for module and function passes ------------
82 struct ModulePassPrinter : public ModulePass {
83 const PassInfo *PassToPrint;
84 ModulePassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
86 virtual bool runOnModule(Module &M) {
88 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
90 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, &M);
93 // Get and print pass...
97 virtual const char *getPassName() const { return "'Pass' Printer"; }
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequiredID(PassToPrint);
101 AU.setPreservesAll();
105 struct FunctionPassPrinter : public FunctionPass {
106 const PassInfo *PassToPrint;
107 FunctionPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
109 virtual bool runOnFunction(Function &F) {
111 llvm_cout << "Printing analysis '" << PassToPrint->getPassName()
112 << "' for function '" << F.getName() << "':\n";
114 // Get and print pass...
115 getAnalysisID<Pass>(PassToPrint).print(llvm_cout, F.getParent());
119 virtual const char *getPassName() const { return "FunctionPass Printer"; }
121 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
122 AU.addRequiredID(PassToPrint);
123 AU.setPreservesAll();
127 struct BasicBlockPassPrinter : public BasicBlockPass {
128 const PassInfo *PassToPrint;
129 BasicBlockPassPrinter(const PassInfo *PI) : PassToPrint(PI) {}
131 virtual bool runOnBasicBlock(BasicBlock &BB) {
133 llvm_cout << "Printing Analysis info for BasicBlock '" << BB.getName()
134 << "': Pass " << PassToPrint->getPassName() << ":\n";
137 // Get and print pass...
138 getAnalysisID<Pass>(PassToPrint).print(
139 llvm_cout, BB.getParent()->getParent());
143 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
145 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
146 AU.addRequiredID(PassToPrint);
147 AU.setPreservesAll();
151 } // anonymous namespace
154 //===----------------------------------------------------------------------===//
157 int main(int argc, char **argv) {
159 cl::ParseCommandLineOptions(argc, argv,
160 " llvm .bc -> .bc modular optimizer and analysis printer \n");
161 sys::PrintStackTraceOnErrorSignal();
163 // Allocate a full target machine description only if necessary.
164 // FIXME: The choice of target should be controllable on the command line.
165 std::auto_ptr<TargetMachine> target;
167 std::string ErrorMessage;
169 // Load the input module...
170 std::auto_ptr<Module> M(ParseBytecodeFile(InputFilename, &ErrorMessage));
172 llvm_cerr << argv[0] << ": ";
173 if (ErrorMessage.size())
174 llvm_cerr << ErrorMessage << "\n";
176 llvm_cerr << "bytecode didn't read correctly.\n";
180 // Figure out what stream we are supposed to write to...
181 // FIXME: cout is not binary!
182 std::ostream *Out = &std::cout; // Default to printing to stdout...
183 if (OutputFilename != "-") {
184 if (!Force && std::ifstream(OutputFilename.c_str())) {
185 // If force is not specified, make sure not to overwrite a file!
186 llvm_cerr << argv[0] << ": error opening '" << OutputFilename
187 << "': file exists!\n"
188 << "Use -f command line argument to force output\n";
191 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
193 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
196 llvm_cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
200 // Make sure that the Output file gets unlinked from the disk if we get a
202 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
205 // If the output is set to be emitted to standard out, and standard out is a
206 // console, print out a warning message and refuse to do it. We don't
207 // impress anyone by spewing tons of binary goo to a terminal.
208 if (!Force && !NoOutput && CheckBytecodeOutputToConsole(Out,!Quiet)) {
212 // Create a PassManager to hold and optimize the collection of passes we are
217 // Add an appropriate TargetData instance for this module...
218 Passes.add(new TargetData(M.get()));
220 // Create a new optimization pass for each one specified on the command line
221 for (unsigned i = 0; i < PassList.size(); ++i) {
222 const PassInfo *PassInf = PassList[i];
224 if (PassInf->getNormalCtor())
225 P = PassInf->getNormalCtor()();
226 else if (PassInf->getTargetCtor()) {
227 assert(target.get() && "Could not allocate target machine!");
228 P = PassInf->getTargetCtor()(*target.get());
230 llvm_cerr << argv[0] << ": cannot create pass: "
231 << PassInf->getPassName() << "\n";
236 if (dynamic_cast<BasicBlockPass*>(P))
237 Passes.add(new BasicBlockPassPrinter(PassInf));
238 else if (dynamic_cast<FunctionPass*>(P))
239 Passes.add(new FunctionPassPrinter(PassInf));
241 Passes.add(new ModulePassPrinter(PassInf));
246 Passes.add(new PrintModulePass(&llvm_cerr));
249 // Check that the module is well formed on completion of optimization
251 Passes.add(createVerifierPass());
253 // Write bytecode out to disk or cout as the last step...
254 if (!NoOutput && !AnalyzeOnly)
255 Passes.add(new WriteBytecodePass(Out, Out != &std::cout, !NoCompress));
257 // Now that we have all of the passes ready, run them.
258 Passes.run(*M.get());
262 } catch (const std::string& msg) {
263 llvm_cerr << argv[0] << ": " << msg << "\n";
265 llvm_cerr << argv[0] << ": Unexpected unknown exception occurred.\n";