Remove VISIBILITY_HIDDEN from this file.
[llvm/avr.git] / tools / opt / opt.cpp
blobd8bfd61c232779641e69bb3f37ad675ca8af22b6
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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/LLVMContext.h"
16 #include "llvm/Module.h"
17 #include "llvm/ModuleProvider.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CallGraphSCCPass.h"
20 #include "llvm/Bitcode/ReaderWriter.h"
21 #include "llvm/Assembly/PrintModulePass.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/CallGraph.h"
25 #include "llvm/Target/TargetData.h"
26 #include "llvm/Target/TargetMachine.h"
27 #include "llvm/Support/PassNameParser.h"
28 #include "llvm/System/Signals.h"
29 #include "llvm/Support/ManagedStatic.h"
30 #include "llvm/Support/MemoryBuffer.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/StandardPasses.h"
33 #include "llvm/Support/SystemUtils.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/LinkAllPasses.h"
36 #include "llvm/LinkAllVMCore.h"
37 #include <memory>
38 #include <algorithm>
39 using namespace llvm;
41 // The OptimizationList is automatically populated with registered Passes by the
42 // PassNameParser.
44 static cl::list<const PassInfo*, bool, PassNameParser>
45 PassList(cl::desc("Optimizations available:"));
47 // Other command line options...
49 static cl::opt<std::string>
50 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
51 cl::init("-"), cl::value_desc("filename"));
53 static cl::opt<std::string>
54 OutputFilename("o", cl::desc("Override output filename"),
55 cl::value_desc("filename"), cl::init("-"));
57 static cl::opt<bool>
58 Force("f", cl::desc("Enable binary output on terminals"));
60 static cl::opt<bool>
61 PrintEachXForm("p", cl::desc("Print module after each transformation"));
63 static cl::opt<bool>
64 NoOutput("disable-output",
65 cl::desc("Do not write result bitcode file"), cl::Hidden);
67 static cl::opt<bool>
68 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
70 static cl::opt<bool>
71 VerifyEach("verify-each", cl::desc("Verify after each transform"));
73 static cl::opt<bool>
74 StripDebug("strip-debug",
75 cl::desc("Strip debugger symbol info from translation unit"));
77 static cl::opt<bool>
78 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
80 static cl::opt<bool>
81 DisableOptimizations("disable-opt",
82 cl::desc("Do not run any optimization passes"));
84 static cl::opt<bool>
85 DisableInternalize("disable-internalize",
86 cl::desc("Do not mark all symbols as internal"));
88 static cl::opt<bool>
89 StandardCompileOpts("std-compile-opts",
90 cl::desc("Include the standard compile time optimizations"));
92 static cl::opt<bool>
93 StandardLinkOpts("std-link-opts",
94 cl::desc("Include the standard link time optimizations"));
96 static cl::opt<bool>
97 OptLevelO1("O1",
98 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
100 static cl::opt<bool>
101 OptLevelO2("O2",
102 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
104 static cl::opt<bool>
105 OptLevelO3("O3",
106 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
108 static cl::opt<bool>
109 UnitAtATime("funit-at-a-time",
110 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
111 cl::init(true));
113 static cl::opt<bool>
114 DisableSimplifyLibCalls("disable-simplify-libcalls",
115 cl::desc("Disable simplify-libcalls"));
117 static cl::opt<bool>
118 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
120 static cl::alias
121 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
123 static cl::opt<bool>
124 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
126 // ---------- Define Printers for module and function passes ------------
127 namespace {
129 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
130 static char ID;
131 const PassInfo *PassToPrint;
132 CallGraphSCCPassPrinter(const PassInfo *PI) :
133 CallGraphSCCPass(&ID), PassToPrint(PI) {}
135 virtual bool runOnSCC(std::vector<CallGraphNode *>&SCC) {
136 if (!Quiet) {
137 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
139 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
140 Function *F = SCC[i]->getFunction();
141 if (F) {
142 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
146 // Get and print pass...
147 return false;
150 virtual const char *getPassName() const { return "'Pass' Printer"; }
152 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
153 AU.addRequiredID(PassToPrint);
154 AU.setPreservesAll();
158 char CallGraphSCCPassPrinter::ID = 0;
160 struct ModulePassPrinter : public ModulePass {
161 static char ID;
162 const PassInfo *PassToPrint;
163 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
164 PassToPrint(PI) {}
166 virtual bool runOnModule(Module &M) {
167 if (!Quiet) {
168 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
169 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
172 // Get and print pass...
173 return false;
176 virtual const char *getPassName() const { return "'Pass' Printer"; }
178 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
179 AU.addRequiredID(PassToPrint);
180 AU.setPreservesAll();
184 char ModulePassPrinter::ID = 0;
185 struct FunctionPassPrinter : public FunctionPass {
186 const PassInfo *PassToPrint;
187 static char ID;
188 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
189 PassToPrint(PI) {}
191 virtual bool runOnFunction(Function &F) {
192 if (!Quiet) {
193 outs() << "Printing analysis '" << PassToPrint->getPassName()
194 << "' for function '" << F.getName() << "':\n";
196 // Get and print pass...
197 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
198 return false;
201 virtual const char *getPassName() const { return "FunctionPass Printer"; }
203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.addRequiredID(PassToPrint);
205 AU.setPreservesAll();
209 char FunctionPassPrinter::ID = 0;
211 struct LoopPassPrinter : public LoopPass {
212 static char ID;
213 const PassInfo *PassToPrint;
214 LoopPassPrinter(const PassInfo *PI) :
215 LoopPass(&ID), PassToPrint(PI) {}
217 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
218 if (!Quiet) {
219 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
220 getAnalysisID<Pass>(PassToPrint).print(outs(),
221 L->getHeader()->getParent()->getParent());
223 // Get and print pass...
224 return false;
227 virtual const char *getPassName() const { return "'Pass' Printer"; }
229 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230 AU.addRequiredID(PassToPrint);
231 AU.setPreservesAll();
235 char LoopPassPrinter::ID = 0;
237 struct BasicBlockPassPrinter : public BasicBlockPass {
238 const PassInfo *PassToPrint;
239 static char ID;
240 BasicBlockPassPrinter(const PassInfo *PI)
241 : BasicBlockPass(&ID), PassToPrint(PI) {}
243 virtual bool runOnBasicBlock(BasicBlock &BB) {
244 if (!Quiet) {
245 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
246 << "': Pass " << PassToPrint->getPassName() << ":\n";
249 // Get and print pass...
250 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
251 return false;
254 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
256 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
257 AU.addRequiredID(PassToPrint);
258 AU.setPreservesAll();
262 char BasicBlockPassPrinter::ID = 0;
263 inline void addPass(PassManager &PM, Pass *P) {
264 // Add the pass to the pass manager...
265 PM.add(P);
267 // If we are verifying all of the intermediate steps, add the verifier...
268 if (VerifyEach) PM.add(createVerifierPass());
271 /// AddOptimizationPasses - This routine adds optimization passes
272 /// based on selected optimization level, OptLevel. This routine
273 /// duplicates llvm-gcc behaviour.
275 /// OptLevel - Optimization Level
276 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
277 unsigned OptLevel) {
278 createStandardFunctionPasses(&FPM, OptLevel);
280 llvm::Pass *InliningPass = OptLevel > 1 ? createFunctionInliningPass() : 0;
281 createStandardModulePasses(&MPM, OptLevel,
282 /*OptimizeSize=*/ false,
283 UnitAtATime,
284 /*UnrollLoops=*/ OptLevel > 1,
285 !DisableSimplifyLibCalls,
286 /*HaveExceptions=*/ true,
287 InliningPass);
290 void AddStandardCompilePasses(PassManager &PM) {
291 PM.add(createVerifierPass()); // Verify that input is correct
293 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
295 // If the -strip-debug command line option was specified, do it.
296 if (StripDebug)
297 addPass(PM, createStripSymbolsPass(true));
299 if (DisableOptimizations) return;
301 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
303 // -std-compile-opts adds the same module passes as -O3.
304 createStandardModulePasses(&PM, 3,
305 /*OptimizeSize=*/ false,
306 /*UnitAtATime=*/ true,
307 /*UnrollLoops=*/ true,
308 /*SimplifyLibCalls=*/ true,
309 /*HaveExceptions=*/ true,
310 InliningPass);
313 void AddStandardLinkPasses(PassManager &PM) {
314 PM.add(createVerifierPass()); // Verify that input is correct
316 // If the -strip-debug command line option was specified, do it.
317 if (StripDebug)
318 addPass(PM, createStripSymbolsPass(true));
320 if (DisableOptimizations) return;
322 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
323 /*RunInliner=*/ !DisableInline,
324 /*VerifyEach=*/ VerifyEach);
327 } // anonymous namespace
330 //===----------------------------------------------------------------------===//
331 // main for opt
333 int main(int argc, char **argv) {
334 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
335 LLVMContext &Context = getGlobalContext();
336 try {
337 cl::ParseCommandLineOptions(argc, argv,
338 "llvm .bc -> .bc modular optimizer and analysis printer\n");
339 sys::PrintStackTraceOnErrorSignal();
341 // Allocate a full target machine description only if necessary.
342 // FIXME: The choice of target should be controllable on the command line.
343 std::auto_ptr<TargetMachine> target;
345 std::string ErrorMessage;
347 // Load the input module...
348 std::auto_ptr<Module> M;
349 if (MemoryBuffer *Buffer
350 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
351 M.reset(ParseBitcodeFile(Buffer, Context, &ErrorMessage));
352 delete Buffer;
355 if (M.get() == 0) {
356 errs() << argv[0] << ": ";
357 if (ErrorMessage.size())
358 errs() << ErrorMessage << "\n";
359 else
360 errs() << "bitcode didn't read correctly.\n";
361 return 1;
364 // Figure out what stream we are supposed to write to...
365 // FIXME: outs() is not binary!
366 raw_ostream *Out = &outs(); // Default to printing to stdout...
367 if (OutputFilename != "-") {
368 std::string ErrorInfo;
369 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
370 raw_fd_ostream::F_Binary);
371 if (!ErrorInfo.empty()) {
372 errs() << ErrorInfo << '\n';
373 delete Out;
374 return 1;
377 // Make sure that the Output file gets unlinked from the disk if we get a
378 // SIGINT
379 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
382 // If the output is set to be emitted to standard out, and standard out is a
383 // console, print out a warning message and refuse to do it. We don't
384 // impress anyone by spewing tons of binary goo to a terminal.
385 if (!Force && !NoOutput && CheckBitcodeOutputToConsole(*Out, !Quiet))
386 NoOutput = true;
388 // Create a PassManager to hold and optimize the collection of passes we are
389 // about to build...
391 PassManager Passes;
393 // Add an appropriate TargetData instance for this module...
394 Passes.add(new TargetData(M.get()));
396 FunctionPassManager *FPasses = NULL;
397 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
398 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
399 FPasses->add(new TargetData(M.get()));
402 // If the -strip-debug command line option was specified, add it. If
403 // -std-compile-opts was also specified, it will handle StripDebug.
404 if (StripDebug && !StandardCompileOpts)
405 addPass(Passes, createStripSymbolsPass(true));
407 // Create a new optimization pass for each one specified on the command line
408 for (unsigned i = 0; i < PassList.size(); ++i) {
409 // Check to see if -std-compile-opts was specified before this option. If
410 // so, handle it.
411 if (StandardCompileOpts &&
412 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
413 AddStandardCompilePasses(Passes);
414 StandardCompileOpts = false;
417 if (StandardLinkOpts &&
418 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
419 AddStandardLinkPasses(Passes);
420 StandardLinkOpts = false;
423 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
424 AddOptimizationPasses(Passes, *FPasses, 1);
425 OptLevelO1 = false;
428 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
429 AddOptimizationPasses(Passes, *FPasses, 2);
430 OptLevelO2 = false;
433 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
434 AddOptimizationPasses(Passes, *FPasses, 3);
435 OptLevelO3 = false;
438 const PassInfo *PassInf = PassList[i];
439 Pass *P = 0;
440 if (PassInf->getNormalCtor())
441 P = PassInf->getNormalCtor()();
442 else
443 errs() << argv[0] << ": cannot create pass: "
444 << PassInf->getPassName() << "\n";
445 if (P) {
446 bool isBBPass = dynamic_cast<BasicBlockPass*>(P) != 0;
447 bool isLPass = !isBBPass && dynamic_cast<LoopPass*>(P) != 0;
448 bool isFPass = !isLPass && dynamic_cast<FunctionPass*>(P) != 0;
449 bool isCGSCCPass = !isFPass && dynamic_cast<CallGraphSCCPass*>(P) != 0;
451 addPass(Passes, P);
453 if (AnalyzeOnly) {
454 if (isBBPass)
455 Passes.add(new BasicBlockPassPrinter(PassInf));
456 else if (isLPass)
457 Passes.add(new LoopPassPrinter(PassInf));
458 else if (isFPass)
459 Passes.add(new FunctionPassPrinter(PassInf));
460 else if (isCGSCCPass)
461 Passes.add(new CallGraphSCCPassPrinter(PassInf));
462 else
463 Passes.add(new ModulePassPrinter(PassInf));
467 if (PrintEachXForm)
468 Passes.add(createPrintModulePass(&errs()));
471 // If -std-compile-opts was specified at the end of the pass list, add them.
472 if (StandardCompileOpts) {
473 AddStandardCompilePasses(Passes);
474 StandardCompileOpts = false;
477 if (StandardLinkOpts) {
478 AddStandardLinkPasses(Passes);
479 StandardLinkOpts = false;
482 if (OptLevelO1) {
483 AddOptimizationPasses(Passes, *FPasses, 1);
486 if (OptLevelO2) {
487 AddOptimizationPasses(Passes, *FPasses, 2);
490 if (OptLevelO3) {
491 AddOptimizationPasses(Passes, *FPasses, 3);
494 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
495 FPasses->doInitialization();
496 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
497 I != E; ++I)
498 FPasses->run(*I);
501 // Check that the module is well formed on completion of optimization
502 if (!NoVerify && !VerifyEach)
503 Passes.add(createVerifierPass());
505 // Write bitcode out to disk or outs() as the last step...
506 if (!NoOutput && !AnalyzeOnly)
507 Passes.add(createBitcodeWriterPass(*Out));
509 // Now that we have all of the passes ready, run them.
510 Passes.run(*M.get());
512 // Delete the raw_fd_ostream.
513 if (Out != &outs())
514 delete Out;
515 return 0;
517 } catch (const std::string& msg) {
518 errs() << argv[0] << ": " << msg << "\n";
519 } catch (...) {
520 errs() << argv[0] << ": Unexpected unknown exception occurred.\n";
522 llvm_shutdown();
523 return 1;