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/LLVMContext.h"
16 #include "llvm/Module.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/Debug.h"
29 #include "llvm/Support/IRReader.h"
30 #include "llvm/Support/ManagedStatic.h"
31 #include "llvm/Support/PluginLoader.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/StandardPasses.h"
34 #include "llvm/Support/SystemUtils.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/LinkAllVMCore.h"
42 // The OptimizationList is automatically populated with registered Passes by the
45 static cl::list<const PassInfo*, bool, PassNameParser>
46 PassList(cl::desc("Optimizations available:"));
48 // Other command line options...
50 static cl::opt<std::string>
51 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
52 cl::init("-"), cl::value_desc("filename"));
54 static cl::opt<std::string>
55 OutputFilename("o", cl::desc("Override output filename"),
56 cl::value_desc("filename"));
59 Force("f", cl::desc("Enable binary output on terminals"));
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
128 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
130 static cl::opt<std::string>
131 DefaultDataLayout("default-data-layout",
132 cl::desc("data layout string to use if not specified by module"),
133 cl::value_desc("layout-string"), cl::init(""));
135 // ---------- Define Printers for module and function passes ------------
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
140 const PassInfo *PassToPrint;
142 std::string PassName;
144 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
145 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
146 std::string PassToPrintName = PassToPrint->getPassName();
147 PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
150 virtual bool runOnSCC(CallGraphSCC &SCC) {
152 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
154 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
155 Function *F = (*I)->getFunction();
157 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
161 // Get and print pass...
165 virtual const char *getPassName() const { return PassName.c_str(); }
167 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
168 AU.addRequiredID(PassToPrint->getTypeInfo());
169 AU.setPreservesAll();
173 char CallGraphSCCPassPrinter::ID = 0;
175 struct ModulePassPrinter : public ModulePass {
177 const PassInfo *PassToPrint;
179 std::string PassName;
181 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
182 : ModulePass(ID), PassToPrint(PI), Out(out) {
183 std::string PassToPrintName = PassToPrint->getPassName();
184 PassName = "ModulePass Printer: " + PassToPrintName;
187 virtual bool runOnModule(Module &M) {
189 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
190 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
193 // Get and print pass...
197 virtual const char *getPassName() const { return PassName.c_str(); }
199 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
200 AU.addRequiredID(PassToPrint->getTypeInfo());
201 AU.setPreservesAll();
205 char ModulePassPrinter::ID = 0;
206 struct FunctionPassPrinter : public FunctionPass {
207 const PassInfo *PassToPrint;
210 std::string PassName;
212 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
213 : FunctionPass(ID), PassToPrint(PI), Out(out) {
214 std::string PassToPrintName = PassToPrint->getPassName();
215 PassName = "FunctionPass Printer: " + PassToPrintName;
218 virtual bool runOnFunction(Function &F) {
220 Out << "Printing analysis '" << PassToPrint->getPassName()
221 << "' for function '" << F.getName() << "':\n";
223 // Get and print pass...
224 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
229 virtual const char *getPassName() const { return PassName.c_str(); }
231 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
232 AU.addRequiredID(PassToPrint->getTypeInfo());
233 AU.setPreservesAll();
237 char FunctionPassPrinter::ID = 0;
239 struct LoopPassPrinter : public LoopPass {
241 const PassInfo *PassToPrint;
243 std::string PassName;
245 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
246 LoopPass(ID), PassToPrint(PI), Out(out) {
247 std::string PassToPrintName = PassToPrint->getPassName();
248 PassName = "LoopPass Printer: " + PassToPrintName;
252 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
254 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
255 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
256 L->getHeader()->getParent()->getParent());
258 // Get and print pass...
262 virtual const char *getPassName() const { return PassName.c_str(); }
264 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
265 AU.addRequiredID(PassToPrint->getTypeInfo());
266 AU.setPreservesAll();
270 char LoopPassPrinter::ID = 0;
272 struct BasicBlockPassPrinter : public BasicBlockPass {
273 const PassInfo *PassToPrint;
276 std::string PassName;
278 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
279 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
280 std::string PassToPrintName = PassToPrint->getPassName();
281 PassName = "BasicBlockPass Printer: " + PassToPrintName;
284 virtual bool runOnBasicBlock(BasicBlock &BB) {
286 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
287 << "': Pass " << PassToPrint->getPassName() << ":\n";
290 // Get and print pass...
291 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
292 BB.getParent()->getParent());
296 virtual const char *getPassName() const { return PassName.c_str(); }
298 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
299 AU.addRequiredID(PassToPrint->getTypeInfo());
300 AU.setPreservesAll();
304 char BasicBlockPassPrinter::ID = 0;
305 inline void addPass(PassManagerBase &PM, Pass *P) {
306 // Add the pass to the pass manager...
309 // If we are verifying all of the intermediate steps, add the verifier...
310 if (VerifyEach) PM.add(createVerifierPass());
313 /// AddOptimizationPasses - This routine adds optimization passes
314 /// based on selected optimization level, OptLevel. This routine
315 /// duplicates llvm-gcc behaviour.
317 /// OptLevel - Optimization Level
318 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
320 createStandardFunctionPasses(&FPM, OptLevel);
322 llvm::Pass *InliningPass = 0;
325 } else if (OptLevel) {
326 unsigned Threshold = 200;
329 InliningPass = createFunctionInliningPass(Threshold);
331 InliningPass = createAlwaysInlinerPass();
333 createStandardModulePasses(&MPM, OptLevel,
334 /*OptimizeSize=*/ false,
336 /*UnrollLoops=*/ OptLevel > 1,
337 !DisableSimplifyLibCalls,
338 /*HaveExceptions=*/ true,
342 void AddStandardCompilePasses(PassManagerBase &PM) {
343 PM.add(createVerifierPass()); // Verify that input is correct
345 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
347 // If the -strip-debug command line option was specified, do it.
349 addPass(PM, createStripSymbolsPass(true));
351 if (DisableOptimizations) return;
353 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
355 // -std-compile-opts adds the same module passes as -O3.
356 createStandardModulePasses(&PM, 3,
357 /*OptimizeSize=*/ false,
358 /*UnitAtATime=*/ true,
359 /*UnrollLoops=*/ true,
360 /*SimplifyLibCalls=*/ true,
361 /*HaveExceptions=*/ true,
365 void AddStandardLinkPasses(PassManagerBase &PM) {
366 PM.add(createVerifierPass()); // Verify that input is correct
368 // If the -strip-debug command line option was specified, do it.
370 addPass(PM, createStripSymbolsPass(true));
372 if (DisableOptimizations) return;
374 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
375 /*RunInliner=*/ !DisableInline,
376 /*VerifyEach=*/ VerifyEach);
379 } // anonymous namespace
382 //===----------------------------------------------------------------------===//
385 int main(int argc, char **argv) {
386 sys::PrintStackTraceOnErrorSignal();
387 llvm::PrettyStackTraceProgram X(argc, argv);
389 if (AnalyzeOnly && NoOutput) {
390 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
394 // Enable debug stream buffering.
395 EnableDebugBuffering = true;
397 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
398 LLVMContext &Context = getGlobalContext();
400 cl::ParseCommandLineOptions(argc, argv,
401 "llvm .bc -> .bc modular optimizer and analysis printer\n");
403 // Allocate a full target machine description only if necessary.
404 // FIXME: The choice of target should be controllable on the command line.
405 std::auto_ptr<TargetMachine> target;
409 // Load the input module...
410 std::auto_ptr<Module> M;
411 M.reset(ParseIRFile(InputFilename, Err, Context));
414 Err.Print(argv[0], errs());
418 // Figure out what stream we are supposed to write to...
419 OwningPtr<tool_output_file> Out;
421 if (!OutputFilename.empty())
422 errs() << "WARNING: The -o (output filename) option is ignored when\n"
423 "the --disable-output option is used.\n";
425 // Default to standard output.
426 if (OutputFilename.empty())
427 OutputFilename = "-";
429 std::string ErrorInfo;
430 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
431 raw_fd_ostream::F_Binary));
432 if (!ErrorInfo.empty()) {
433 errs() << ErrorInfo << '\n';
438 // If the output is set to be emitted to standard out, and standard out is a
439 // console, print out a warning message and refuse to do it. We don't
440 // impress anyone by spewing tons of binary goo to a terminal.
441 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
442 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
445 // Create a PassManager to hold and optimize the collection of passes we are
450 // Add an appropriate TargetData instance for this module...
452 const std::string &ModuleDataLayout = M.get()->getDataLayout();
453 if (!ModuleDataLayout.empty())
454 TD = new TargetData(ModuleDataLayout);
455 else if (!DefaultDataLayout.empty())
456 TD = new TargetData(DefaultDataLayout);
461 OwningPtr<PassManager> FPasses;
462 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
463 FPasses.reset(new PassManager());
465 FPasses->add(new TargetData(*TD));
468 // If the -strip-debug command line option was specified, add it. If
469 // -std-compile-opts was also specified, it will handle StripDebug.
470 if (StripDebug && !StandardCompileOpts)
471 addPass(Passes, createStripSymbolsPass(true));
473 // Create a new optimization pass for each one specified on the command line
474 for (unsigned i = 0; i < PassList.size(); ++i) {
475 // Check to see if -std-compile-opts was specified before this option. If
477 if (StandardCompileOpts &&
478 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
479 AddStandardCompilePasses(Passes);
480 StandardCompileOpts = false;
483 if (StandardLinkOpts &&
484 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
485 AddStandardLinkPasses(Passes);
486 StandardLinkOpts = false;
489 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
490 AddOptimizationPasses(Passes, *FPasses, 1);
494 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
495 AddOptimizationPasses(Passes, *FPasses, 2);
499 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
500 AddOptimizationPasses(Passes, *FPasses, 3);
504 const PassInfo *PassInf = PassList[i];
506 if (PassInf->getNormalCtor())
507 P = PassInf->getNormalCtor()();
509 errs() << argv[0] << ": cannot create pass: "
510 << PassInf->getPassName() << "\n";
512 PassKind Kind = P->getPassKind();
518 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
521 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
524 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
526 case PT_CallGraphSCC:
527 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
530 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
537 Passes.add(createPrintModulePass(&errs()));
540 // If -std-compile-opts was specified at the end of the pass list, add them.
541 if (StandardCompileOpts) {
542 AddStandardCompilePasses(Passes);
543 StandardCompileOpts = false;
546 if (StandardLinkOpts) {
547 AddStandardLinkPasses(Passes);
548 StandardLinkOpts = false;
552 AddOptimizationPasses(Passes, *FPasses, 1);
555 AddOptimizationPasses(Passes, *FPasses, 2);
558 AddOptimizationPasses(Passes, *FPasses, 3);
560 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
561 FPasses->run(*M.get());
563 // Check that the module is well formed on completion of optimization
564 if (!NoVerify && !VerifyEach)
565 Passes.add(createVerifierPass());
567 // Write bitcode or assembly to the output as the last step...
568 if (!NoOutput && !AnalyzeOnly) {
570 Passes.add(createPrintModulePass(&Out->os()));
572 Passes.add(createBitcodeWriterPass(Out->os()));
575 // Now that we have all of the passes ready, run them.
576 Passes.run(*M.get());