1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // 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/ModuleProvider.h"
17 #include "llvm/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/Verifier.h"
22 #include "llvm/Analysis/LoopPass.h"
23 #include "llvm/Analysis/CallGraph.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetMachine.h"
26 #include "llvm/Support/PassNameParser.h"
27 #include "llvm/System/Signals.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/PluginLoader.h"
31 #include "llvm/Support/Streams.h"
32 #include "llvm/Support/SystemUtils.h"
33 #include "llvm/LinkAllPasses.h"
34 #include "llvm/LinkAllVMCore.h"
41 // The OptimizationList is automatically populated with registered Passes by the
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("-"));
58 Force("f", cl::desc("Overwrite output files"));
61 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 NoOutput("disable-output",
65 cl::desc("Do not write result bitcode file"), cl::Hidden);
68 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
71 VerifyEach("verify-each", cl::desc("Verify after each transform"));
74 StripDebug("strip-debug",
75 cl::desc("Strip debugger symbol info from translation unit"));
78 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
81 DisableOptimizations("disable-opt",
82 cl::desc("Do not run any optimization passes"));
85 StandardCompileOpts("std-compile-opts",
86 cl::desc("Include the standard compile time optimizations"));
90 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
94 cl::desc("Optimization level 1. Similar to llvm-gcc -O2"));
98 cl::desc("Optimization level 1. Similar to llvm-gcc -O3"));
101 UnitAtATime("funit-at-a-time",
102 cl::desc("Enable IPO. This is same is llvm-gcc's -funit-at-a-time"));
105 DisableSimplifyLibCalls("disable-simplify-libcalls",
106 cl::desc("Disable simplify libcalls"));
109 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
112 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
115 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
117 // ---------- Define Printers for module and function passes ------------
120 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
122 const PassInfo *PassToPrint;
123 CallGraphSCCPassPrinter(const PassInfo *PI) :
124 CallGraphSCCPass((intptr_t)&ID), PassToPrint(PI) {}
126 virtual bool runOnSCC(const std::vector<CallGraphNode *>&SCC) {
128 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
130 for (unsigned i = 0, e = SCC.size(); i != e; ++i) {
131 Function *F = SCC[i]->getFunction();
133 getAnalysisID<Pass>(PassToPrint).print(cout, F->getParent());
136 // Get and print pass...
140 virtual const char *getPassName() const { return "'Pass' Printer"; }
142 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
143 AU.addRequiredID(PassToPrint);
144 AU.setPreservesAll();
148 char CallGraphSCCPassPrinter::ID = 0;
150 struct ModulePassPrinter : public ModulePass {
152 const PassInfo *PassToPrint;
153 ModulePassPrinter(const PassInfo *PI) : ModulePass((intptr_t)&ID),
156 virtual bool runOnModule(Module &M) {
158 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
159 getAnalysisID<Pass>(PassToPrint).print(cout, &M);
162 // Get and print pass...
166 virtual const char *getPassName() const { return "'Pass' Printer"; }
168 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
169 AU.addRequiredID(PassToPrint);
170 AU.setPreservesAll();
174 char ModulePassPrinter::ID = 0;
175 struct FunctionPassPrinter : public FunctionPass {
176 const PassInfo *PassToPrint;
178 FunctionPassPrinter(const PassInfo *PI) : FunctionPass((intptr_t)&ID),
181 virtual bool runOnFunction(Function &F) {
183 cout << "Printing analysis '" << PassToPrint->getPassName()
184 << "' for function '" << F.getName() << "':\n";
186 // Get and print pass...
187 getAnalysisID<Pass>(PassToPrint).print(cout, F.getParent());
191 virtual const char *getPassName() const { return "FunctionPass Printer"; }
193 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
194 AU.addRequiredID(PassToPrint);
195 AU.setPreservesAll();
199 char FunctionPassPrinter::ID = 0;
201 struct LoopPassPrinter : public LoopPass {
203 const PassInfo *PassToPrint;
204 LoopPassPrinter(const PassInfo *PI) :
205 LoopPass((intptr_t)&ID), PassToPrint(PI) {}
207 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
209 cout << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
210 getAnalysisID<Pass>(PassToPrint).print(cout,
211 L->getHeader()->getParent()->getParent());
213 // Get and print pass...
217 virtual const char *getPassName() const { return "'Pass' Printer"; }
219 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
220 AU.addRequiredID(PassToPrint);
221 AU.setPreservesAll();
225 char LoopPassPrinter::ID = 0;
227 struct BasicBlockPassPrinter : public BasicBlockPass {
228 const PassInfo *PassToPrint;
230 BasicBlockPassPrinter(const PassInfo *PI)
231 : BasicBlockPass((intptr_t)&ID), PassToPrint(PI) {}
233 virtual bool runOnBasicBlock(BasicBlock &BB) {
235 cout << "Printing Analysis info for BasicBlock '" << BB.getName()
236 << "': Pass " << PassToPrint->getPassName() << ":\n";
239 // Get and print pass...
240 getAnalysisID<Pass>(PassToPrint).print(cout, BB.getParent()->getParent());
244 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
246 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
247 AU.addRequiredID(PassToPrint);
248 AU.setPreservesAll();
252 char BasicBlockPassPrinter::ID = 0;
253 inline void addPass(PassManager &PM, Pass *P) {
254 // Add the pass to the pass manager...
257 // If we are verifying all of the intermediate steps, add the verifier...
258 if (VerifyEach) PM.add(createVerifierPass());
261 /// AddOptimizationPasses - This routine adds optimization passes
262 /// based on selected optimization level, OptLevel. This routine
263 /// duplicates llvm-gcc behaviour.
265 /// OptLevel - Optimization Level
266 /// PruneEH - Add PruneEHPass, if set.
267 /// UnrollLoop - Unroll loops, if set.
268 void AddOptimizationPasses(PassManager &MPM, FunctionPassManager &FPM,
274 FPM.add(createCFGSimplificationPass());
276 FPM.add(createPromoteMemoryToRegisterPass());
278 FPM.add(createScalarReplAggregatesPass());
279 FPM.add(createInstructionCombiningPass());
282 MPM.add(createRaiseAllocationsPass()); // call %malloc -> malloc inst
283 MPM.add(createCFGSimplificationPass()); // Clean up disgusting code
284 MPM.add(createPromoteMemoryToRegisterPass()); // Kill useless allocas
286 MPM.add(createGlobalOptimizerPass()); // OptLevel out global vars
287 MPM.add(createGlobalDCEPass()); // Remove unused fns and globs
288 MPM.add(createIPConstantPropagationPass()); // IP Constant Propagation
289 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination
291 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE
292 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE
294 MPM.add(createPruneEHPass()); // Remove dead EH info
296 MPM.add(createFunctionInliningPass()); // Inline small functions
298 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args
299 if (!DisableSimplifyLibCalls)
300 MPM.add(createSimplifyLibCallsPass()); // Library Call Optimizations
301 MPM.add(createInstructionCombiningPass()); // Cleanup for scalarrepl.
302 MPM.add(createJumpThreadingPass()); // Thread jumps.
303 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
304 MPM.add(createScalarReplAggregatesPass()); // Break up aggregate allocas
305 MPM.add(createInstructionCombiningPass()); // Combine silly seq's
306 MPM.add(createCondPropagationPass()); // Propagate conditionals
307 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls
308 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
309 MPM.add(createReassociatePass()); // Reassociate expressions
310 MPM.add(createLoopRotatePass()); // Rotate Loop
311 MPM.add(createLICMPass()); // Hoist loop invariants
312 MPM.add(createLoopUnswitchPass());
313 MPM.add(createLoopIndexSplitPass()); // Split loop index
314 MPM.add(createInstructionCombiningPass());
315 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars
316 MPM.add(createLoopDeletionPass()); // Delete dead loops
318 MPM.add(createLoopUnrollPass()); // Unroll small loops
319 MPM.add(createInstructionCombiningPass()); // Clean up after the unroller
320 MPM.add(createGVNPass()); // Remove redundancies
321 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset
322 MPM.add(createSCCPPass()); // Constant prop with SCCP
324 // Run instcombine after redundancy elimination to exploit opportunities
325 // opened up by them.
326 MPM.add(createInstructionCombiningPass());
327 MPM.add(createCondPropagationPass()); // Propagate conditionals
328 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores
329 MPM.add(createAggressiveDCEPass()); // Delete dead instructions
330 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs
333 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes
334 MPM.add(createDeadTypeEliminationPass()); // Eliminate dead types
337 if (OptLevel > 1 && UnitAtATime)
338 MPM.add(createConstantMergePass()); // Merge dup global constants
343 void AddStandardCompilePasses(PassManager &PM) {
344 PM.add(createVerifierPass()); // Verify that input is correct
346 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
348 // If the -strip-debug command line option was specified, do it.
350 addPass(PM, createStripSymbolsPass(true));
352 if (DisableOptimizations) return;
354 addPass(PM, createRaiseAllocationsPass()); // call %malloc -> malloc inst
355 addPass(PM, createCFGSimplificationPass()); // Clean up disgusting code
356 addPass(PM, createPromoteMemoryToRegisterPass());// Kill useless allocas
357 addPass(PM, createGlobalOptimizerPass()); // Optimize out global vars
358 addPass(PM, createGlobalDCEPass()); // Remove unused fns and globs
359 addPass(PM, createIPConstantPropagationPass());// IP Constant Propagation
360 addPass(PM, createDeadArgEliminationPass()); // Dead argument elimination
361 addPass(PM, createInstructionCombiningPass()); // Clean up after IPCP & DAE
362 addPass(PM, createCFGSimplificationPass()); // Clean up after IPCP & DAE
364 addPass(PM, createPruneEHPass()); // Remove dead EH info
367 addPass(PM, createFunctionInliningPass()); // Inline small functions
368 addPass(PM, createArgumentPromotionPass()); // Scalarize uninlined fn args
370 addPass(PM, createSimplifyLibCallsPass()); // Library Call Optimizations
371 addPass(PM, createInstructionCombiningPass()); // Cleanup for scalarrepl.
372 addPass(PM, createJumpThreadingPass()); // Thread jumps.
373 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
374 addPass(PM, createScalarReplAggregatesPass()); // Break up aggregate allocas
375 addPass(PM, createInstructionCombiningPass()); // Combine silly seq's
376 addPass(PM, createCondPropagationPass()); // Propagate conditionals
378 addPass(PM, createTailCallEliminationPass()); // Eliminate tail calls
379 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
380 addPass(PM, createReassociatePass()); // Reassociate expressions
381 addPass(PM, createLoopRotatePass());
382 addPass(PM, createLICMPass()); // Hoist loop invariants
383 addPass(PM, createLoopUnswitchPass()); // Unswitch loops.
384 addPass(PM, createLoopIndexSplitPass()); // Index split loops.
385 // FIXME : Removing instcombine causes nestedloop regression.
386 addPass(PM, createInstructionCombiningPass());
387 addPass(PM, createIndVarSimplifyPass()); // Canonicalize indvars
388 addPass(PM, createLoopDeletionPass()); // Delete dead loops
389 addPass(PM, createLoopUnrollPass()); // Unroll small loops
390 addPass(PM, createInstructionCombiningPass()); // Clean up after the unroller
391 addPass(PM, createGVNPass()); // Remove redundancies
392 addPass(PM, createMemCpyOptPass()); // Remove memcpy / form memset
393 addPass(PM, createSCCPPass()); // Constant prop with SCCP
395 // Run instcombine after redundancy elimination to exploit opportunities
396 // opened up by them.
397 addPass(PM, createInstructionCombiningPass());
398 addPass(PM, createCondPropagationPass()); // Propagate conditionals
400 addPass(PM, createDeadStoreEliminationPass()); // Delete dead stores
401 addPass(PM, createAggressiveDCEPass()); // Delete dead instructions
402 addPass(PM, createCFGSimplificationPass()); // Merge & remove BBs
403 addPass(PM, createStripDeadPrototypesPass()); // Get rid of dead prototypes
404 addPass(PM, createDeadTypeEliminationPass()); // Eliminate dead types
405 addPass(PM, createConstantMergePass()); // Merge dup global constants
408 } // anonymous namespace
411 //===----------------------------------------------------------------------===//
414 int main(int argc, char **argv) {
415 llvm_shutdown_obj X; // Call llvm_shutdown() on exit.
417 cl::ParseCommandLineOptions(argc, argv,
418 "llvm .bc -> .bc modular optimizer and analysis printer\n");
419 sys::PrintStackTraceOnErrorSignal();
421 // Allocate a full target machine description only if necessary.
422 // FIXME: The choice of target should be controllable on the command line.
423 std::auto_ptr<TargetMachine> target;
425 std::string ErrorMessage;
427 // Load the input module...
428 std::auto_ptr<Module> M;
429 if (MemoryBuffer *Buffer
430 = MemoryBuffer::getFileOrSTDIN(InputFilename, &ErrorMessage)) {
431 M.reset(ParseBitcodeFile(Buffer, &ErrorMessage));
436 cerr << argv[0] << ": ";
437 if (ErrorMessage.size())
438 cerr << ErrorMessage << "\n";
440 cerr << "bitcode didn't read correctly.\n";
444 // Figure out what stream we are supposed to write to...
445 // FIXME: cout is not binary!
446 std::ostream *Out = &std::cout; // Default to printing to stdout...
447 if (OutputFilename != "-") {
448 if (!Force && std::ifstream(OutputFilename.c_str())) {
449 // If force is not specified, make sure not to overwrite a file!
450 cerr << argv[0] << ": error opening '" << OutputFilename
451 << "': file exists!\n"
452 << "Use -f command line argument to force output\n";
455 std::ios::openmode io_mode = std::ios::out | std::ios::trunc |
457 Out = new std::ofstream(OutputFilename.c_str(), io_mode);
460 cerr << argv[0] << ": error opening " << OutputFilename << "!\n";
464 // Make sure that the Output file gets unlinked from the disk if we get a
466 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
469 // If the output is set to be emitted to standard out, and standard out is a
470 // console, print out a warning message and refuse to do it. We don't
471 // impress anyone by spewing tons of binary goo to a terminal.
472 if (!Force && !NoOutput && CheckBitcodeOutputToConsole(Out,!Quiet)) {
476 // Create a PassManager to hold and optimize the collection of passes we are
481 // Add an appropriate TargetData instance for this module...
482 Passes.add(new TargetData(M.get()));
484 FunctionPassManager *FPasses = NULL;
485 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
486 FPasses = new FunctionPassManager(new ExistingModuleProvider(M.get()));
487 FPasses->add(new TargetData(M.get()));
490 // If the -strip-debug command line option was specified, add it. If
491 // -std-compile-opts was also specified, it will handle StripDebug.
492 if (StripDebug && !StandardCompileOpts)
493 addPass(Passes, createStripSymbolsPass(true));
495 // Create a new optimization pass for each one specified on the command line
496 for (unsigned i = 0; i < PassList.size(); ++i) {
497 // Check to see if -std-compile-opts was specified before this option. If
499 if (StandardCompileOpts &&
500 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
501 AddStandardCompilePasses(Passes);
502 StandardCompileOpts = false;
505 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
506 AddOptimizationPasses(Passes, *FPasses, 1);
510 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
511 AddOptimizationPasses(Passes, *FPasses, 2);
515 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
516 AddOptimizationPasses(Passes, *FPasses, 3);
520 const PassInfo *PassInf = PassList[i];
522 if (PassInf->getNormalCtor())
523 P = PassInf->getNormalCtor()();
525 cerr << argv[0] << ": cannot create pass: "
526 << PassInf->getPassName() << "\n";
531 if (dynamic_cast<BasicBlockPass*>(P))
532 Passes.add(new BasicBlockPassPrinter(PassInf));
533 else if (dynamic_cast<LoopPass*>(P))
534 Passes.add(new LoopPassPrinter(PassInf));
535 else if (dynamic_cast<FunctionPass*>(P))
536 Passes.add(new FunctionPassPrinter(PassInf));
537 else if (dynamic_cast<CallGraphSCCPass*>(P))
538 Passes.add(new CallGraphSCCPassPrinter(PassInf));
540 Passes.add(new ModulePassPrinter(PassInf));
545 Passes.add(new PrintModulePass(&cerr));
548 // If -std-compile-opts was specified at the end of the pass list, add them.
549 if (StandardCompileOpts) {
550 AddStandardCompilePasses(Passes);
551 StandardCompileOpts = false;
555 AddOptimizationPasses(Passes, *FPasses, 1);
559 AddOptimizationPasses(Passes, *FPasses, 2);
563 AddOptimizationPasses(Passes, *FPasses, 3);
566 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
567 for (Module::iterator I = M.get()->begin(), E = M.get()->end();
572 // Check that the module is well formed on completion of optimization
573 if (!NoVerify && !VerifyEach)
574 Passes.add(createVerifierPass());
576 // Write bitcode out to disk or cout as the last step...
577 if (!NoOutput && !AnalyzeOnly)
578 Passes.add(CreateBitcodeWriterPass(*Out));
580 // Now that we have all of the passes ready, run them.
581 Passes.run(*M.get());
583 // Delete the ofstream.
584 if (Out != &std::cout)
588 } catch (const std::string& msg) {
589 cerr << argv[0] << ": " << msg << "\n";
591 cerr << argv[0] << ": Unexpected unknown exception occurred.\n";