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 // Get and print pass...
155 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
156 Function *F = (*I)->getFunction();
158 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
164 virtual const char *getPassName() const { return PassName.c_str(); }
166 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
167 AU.addRequiredID(PassToPrint->getTypeInfo());
168 AU.setPreservesAll();
172 char CallGraphSCCPassPrinter::ID = 0;
174 struct ModulePassPrinter : public ModulePass {
176 const PassInfo *PassToPrint;
178 std::string PassName;
180 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
181 : ModulePass(ID), PassToPrint(PI), Out(out) {
182 std::string PassToPrintName = PassToPrint->getPassName();
183 PassName = "ModulePass Printer: " + PassToPrintName;
186 virtual bool runOnModule(Module &M) {
188 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
190 // Get and print pass...
191 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
195 virtual const char *getPassName() const { return PassName.c_str(); }
197 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
198 AU.addRequiredID(PassToPrint->getTypeInfo());
199 AU.setPreservesAll();
203 char ModulePassPrinter::ID = 0;
204 struct FunctionPassPrinter : public FunctionPass {
205 const PassInfo *PassToPrint;
208 std::string PassName;
210 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
211 : FunctionPass(ID), PassToPrint(PI), Out(out) {
212 std::string PassToPrintName = PassToPrint->getPassName();
213 PassName = "FunctionPass Printer: " + PassToPrintName;
216 virtual bool runOnFunction(Function &F) {
218 Out << "Printing analysis '" << PassToPrint->getPassName()
219 << "' for function '" << F.getName() << "':\n";
221 // Get and print pass...
222 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
227 virtual const char *getPassName() const { return PassName.c_str(); }
229 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
230 AU.addRequiredID(PassToPrint->getTypeInfo());
231 AU.setPreservesAll();
235 char FunctionPassPrinter::ID = 0;
237 struct LoopPassPrinter : public LoopPass {
239 const PassInfo *PassToPrint;
241 std::string PassName;
243 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
244 LoopPass(ID), PassToPrint(PI), Out(out) {
245 std::string PassToPrintName = PassToPrint->getPassName();
246 PassName = "LoopPass Printer: " + PassToPrintName;
250 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
252 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
254 // Get and print pass...
255 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
256 L->getHeader()->getParent()->getParent());
260 virtual const char *getPassName() const { return PassName.c_str(); }
262 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
263 AU.addRequiredID(PassToPrint->getTypeInfo());
264 AU.setPreservesAll();
268 char LoopPassPrinter::ID = 0;
270 struct BasicBlockPassPrinter : public BasicBlockPass {
271 const PassInfo *PassToPrint;
274 std::string PassName;
276 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
277 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
278 std::string PassToPrintName = PassToPrint->getPassName();
279 PassName = "BasicBlockPass Printer: " + PassToPrintName;
282 virtual bool runOnBasicBlock(BasicBlock &BB) {
284 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
285 << "': Pass " << PassToPrint->getPassName() << ":\n";
287 // Get and print pass...
288 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
289 BB.getParent()->getParent());
293 virtual const char *getPassName() const { return PassName.c_str(); }
295 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
296 AU.addRequiredID(PassToPrint->getTypeInfo());
297 AU.setPreservesAll();
301 char BasicBlockPassPrinter::ID = 0;
302 inline void addPass(PassManagerBase &PM, Pass *P) {
303 // Add the pass to the pass manager...
306 // If we are verifying all of the intermediate steps, add the verifier...
307 if (VerifyEach) PM.add(createVerifierPass());
310 /// AddOptimizationPasses - This routine adds optimization passes
311 /// based on selected optimization level, OptLevel. This routine
312 /// duplicates llvm-gcc behaviour.
314 /// OptLevel - Optimization Level
315 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
317 createStandardFunctionPasses(&FPM, OptLevel);
319 llvm::Pass *InliningPass = 0;
322 } else if (OptLevel) {
323 unsigned Threshold = 200;
326 InliningPass = createFunctionInliningPass(Threshold);
328 InliningPass = createAlwaysInlinerPass();
330 createStandardModulePasses(&MPM, OptLevel,
331 /*OptimizeSize=*/ false,
333 /*UnrollLoops=*/ OptLevel > 1,
334 !DisableSimplifyLibCalls,
335 /*HaveExceptions=*/ true,
339 void AddStandardCompilePasses(PassManagerBase &PM) {
340 PM.add(createVerifierPass()); // Verify that input is correct
342 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
344 // If the -strip-debug command line option was specified, do it.
346 addPass(PM, createStripSymbolsPass(true));
348 if (DisableOptimizations) return;
350 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
352 // -std-compile-opts adds the same module passes as -O3.
353 createStandardModulePasses(&PM, 3,
354 /*OptimizeSize=*/ false,
355 /*UnitAtATime=*/ true,
356 /*UnrollLoops=*/ true,
357 /*SimplifyLibCalls=*/ true,
358 /*HaveExceptions=*/ true,
362 void AddStandardLinkPasses(PassManagerBase &PM) {
363 PM.add(createVerifierPass()); // Verify that input is correct
365 // If the -strip-debug command line option was specified, do it.
367 addPass(PM, createStripSymbolsPass(true));
369 if (DisableOptimizations) return;
371 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
372 /*RunInliner=*/ !DisableInline,
373 /*VerifyEach=*/ VerifyEach);
376 } // anonymous namespace
379 //===----------------------------------------------------------------------===//
382 int main(int argc, char **argv) {
383 sys::PrintStackTraceOnErrorSignal();
384 llvm::PrettyStackTraceProgram X(argc, argv);
386 if (AnalyzeOnly && NoOutput) {
387 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
391 // Enable debug stream buffering.
392 EnableDebugBuffering = true;
394 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
395 LLVMContext &Context = getGlobalContext();
397 cl::ParseCommandLineOptions(argc, argv,
398 "llvm .bc -> .bc modular optimizer and analysis printer\n");
400 // Allocate a full target machine description only if necessary.
401 // FIXME: The choice of target should be controllable on the command line.
402 std::auto_ptr<TargetMachine> target;
406 // Load the input module...
407 std::auto_ptr<Module> M;
408 M.reset(ParseIRFile(InputFilename, Err, Context));
411 Err.Print(argv[0], errs());
415 // Figure out what stream we are supposed to write to...
416 OwningPtr<tool_output_file> Out;
418 if (!OutputFilename.empty())
419 errs() << "WARNING: The -o (output filename) option is ignored when\n"
420 "the --disable-output option is used.\n";
422 // Default to standard output.
423 if (OutputFilename.empty())
424 OutputFilename = "-";
426 std::string ErrorInfo;
427 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
428 raw_fd_ostream::F_Binary));
429 if (!ErrorInfo.empty()) {
430 errs() << ErrorInfo << '\n';
435 // If the output is set to be emitted to standard out, and standard out is a
436 // console, print out a warning message and refuse to do it. We don't
437 // impress anyone by spewing tons of binary goo to a terminal.
438 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
439 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
442 // Create a PassManager to hold and optimize the collection of passes we are
447 // Add an appropriate TargetData instance for this module...
449 const std::string &ModuleDataLayout = M.get()->getDataLayout();
450 if (!ModuleDataLayout.empty())
451 TD = new TargetData(ModuleDataLayout);
452 else if (!DefaultDataLayout.empty())
453 TD = new TargetData(DefaultDataLayout);
458 OwningPtr<PassManager> FPasses;
459 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
460 FPasses.reset(new PassManager());
462 FPasses->add(new TargetData(*TD));
465 // If the -strip-debug command line option was specified, add it. If
466 // -std-compile-opts was also specified, it will handle StripDebug.
467 if (StripDebug && !StandardCompileOpts)
468 addPass(Passes, createStripSymbolsPass(true));
470 // Create a new optimization pass for each one specified on the command line
471 for (unsigned i = 0; i < PassList.size(); ++i) {
472 // Check to see if -std-compile-opts was specified before this option. If
474 if (StandardCompileOpts &&
475 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
476 AddStandardCompilePasses(Passes);
477 StandardCompileOpts = false;
480 if (StandardLinkOpts &&
481 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
482 AddStandardLinkPasses(Passes);
483 StandardLinkOpts = false;
486 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
487 AddOptimizationPasses(Passes, *FPasses, 1);
491 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
492 AddOptimizationPasses(Passes, *FPasses, 2);
496 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
497 AddOptimizationPasses(Passes, *FPasses, 3);
501 const PassInfo *PassInf = PassList[i];
503 if (PassInf->getNormalCtor())
504 P = PassInf->getNormalCtor()();
506 errs() << argv[0] << ": cannot create pass: "
507 << PassInf->getPassName() << "\n";
509 PassKind Kind = P->getPassKind();
515 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
518 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
521 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
523 case PT_CallGraphSCC:
524 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
527 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
534 Passes.add(createPrintModulePass(&errs()));
537 // If -std-compile-opts was specified at the end of the pass list, add them.
538 if (StandardCompileOpts) {
539 AddStandardCompilePasses(Passes);
540 StandardCompileOpts = false;
543 if (StandardLinkOpts) {
544 AddStandardLinkPasses(Passes);
545 StandardLinkOpts = false;
549 AddOptimizationPasses(Passes, *FPasses, 1);
552 AddOptimizationPasses(Passes, *FPasses, 2);
555 AddOptimizationPasses(Passes, *FPasses, 3);
557 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
558 FPasses->run(*M.get());
560 // Check that the module is well formed on completion of optimization
561 if (!NoVerify && !VerifyEach)
562 Passes.add(createVerifierPass());
564 // Write bitcode or assembly to the output as the last step...
565 if (!NoOutput && !AnalyzeOnly) {
567 Passes.add(createPrintModulePass(&Out->os()));
569 Passes.add(createBitcodeWriterPass(Out->os()));
572 // Now that we have all of the passes ready, run them.
573 Passes.run(*M.get());