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"), cl::init("-"));
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;
141 CallGraphSCCPassPrinter(const PassInfo *PI) :
142 CallGraphSCCPass(ID), PassToPrint(PI) {}
144 virtual bool runOnSCC(CallGraphSCC &SCC) {
146 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
148 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
149 Function *F = (*I)->getFunction();
151 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(outs(),
155 // Get and print pass...
159 virtual const char *getPassName() const { return "'Pass' Printer"; }
161 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
162 AU.addRequiredID(PassToPrint->getTypeInfo());
163 AU.setPreservesAll();
167 char CallGraphSCCPassPrinter::ID = 0;
169 struct ModulePassPrinter : public ModulePass {
171 const PassInfo *PassToPrint;
172 ModulePassPrinter(const PassInfo *PI) : ModulePass(ID),
175 virtual bool runOnModule(Module &M) {
177 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
178 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(outs(), &M);
181 // Get and print pass...
185 virtual const char *getPassName() const { return "'Pass' Printer"; }
187 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
188 AU.addRequiredID(PassToPrint->getTypeInfo());
189 AU.setPreservesAll();
193 char ModulePassPrinter::ID = 0;
194 struct FunctionPassPrinter : public FunctionPass {
195 const PassInfo *PassToPrint;
197 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(ID),
200 virtual bool runOnFunction(Function &F) {
202 outs() << "Printing analysis '" << PassToPrint->getPassName()
203 << "' for function '" << F.getName() << "':\n";
205 // Get and print pass...
206 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(outs(),
211 virtual const char *getPassName() const { return "FunctionPass Printer"; }
213 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
214 AU.addRequiredID(PassToPrint->getTypeInfo());
215 AU.setPreservesAll();
219 char FunctionPassPrinter::ID = 0;
221 struct LoopPassPrinter : public LoopPass {
223 const PassInfo *PassToPrint;
224 LoopPassPrinter(const PassInfo *PI) :
225 LoopPass(ID), PassToPrint(PI) {}
227 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
229 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
230 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(outs(),
231 L->getHeader()->getParent()->getParent());
233 // Get and print pass...
237 virtual const char *getPassName() const { return "'Pass' Printer"; }
239 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
240 AU.addRequiredID(PassToPrint->getTypeInfo());
241 AU.setPreservesAll();
245 char LoopPassPrinter::ID = 0;
247 struct BasicBlockPassPrinter : public BasicBlockPass {
248 const PassInfo *PassToPrint;
250 BasicBlockPassPrinter(const PassInfo *PI)
251 : BasicBlockPass(ID), PassToPrint(PI) {}
253 virtual bool runOnBasicBlock(BasicBlock &BB) {
255 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
256 << "': Pass " << PassToPrint->getPassName() << ":\n";
259 // Get and print pass...
260 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(outs(),
261 BB.getParent()->getParent());
265 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
267 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
268 AU.addRequiredID(PassToPrint->getTypeInfo());
269 AU.setPreservesAll();
273 char BasicBlockPassPrinter::ID = 0;
274 inline void addPass(PassManagerBase &PM, Pass *P) {
275 // Add the pass to the pass manager...
278 // If we are verifying all of the intermediate steps, add the verifier...
279 if (VerifyEach) PM.add(createVerifierPass());
282 /// AddOptimizationPasses - This routine adds optimization passes
283 /// based on selected optimization level, OptLevel. This routine
284 /// duplicates llvm-gcc behaviour.
286 /// OptLevel - Optimization Level
287 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
289 createStandardFunctionPasses(&FPM, OptLevel);
291 llvm::Pass *InliningPass = 0;
294 } else if (OptLevel) {
295 unsigned Threshold = 200;
298 InliningPass = createFunctionInliningPass(Threshold);
300 InliningPass = createAlwaysInlinerPass();
302 createStandardModulePasses(&MPM, OptLevel,
303 /*OptimizeSize=*/ false,
305 /*UnrollLoops=*/ OptLevel > 1,
306 !DisableSimplifyLibCalls,
307 /*HaveExceptions=*/ true,
311 void AddStandardCompilePasses(PassManagerBase &PM) {
312 PM.add(createVerifierPass()); // Verify that input is correct
314 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
316 // If the -strip-debug command line option was specified, do it.
318 addPass(PM, createStripSymbolsPass(true));
320 if (DisableOptimizations) return;
322 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
324 // -std-compile-opts adds the same module passes as -O3.
325 createStandardModulePasses(&PM, 3,
326 /*OptimizeSize=*/ false,
327 /*UnitAtATime=*/ true,
328 /*UnrollLoops=*/ true,
329 /*SimplifyLibCalls=*/ true,
330 /*HaveExceptions=*/ true,
334 void AddStandardLinkPasses(PassManagerBase &PM) {
335 PM.add(createVerifierPass()); // Verify that input is correct
337 // If the -strip-debug command line option was specified, do it.
339 addPass(PM, createStripSymbolsPass(true));
341 if (DisableOptimizations) return;
343 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
344 /*RunInliner=*/ !DisableInline,
345 /*VerifyEach=*/ VerifyEach);
348 } // anonymous namespace
351 //===----------------------------------------------------------------------===//
354 int main(int argc, char **argv) {
355 sys::PrintStackTraceOnErrorSignal();
356 llvm::PrettyStackTraceProgram X(argc, argv);
358 // Enable debug stream buffering.
359 EnableDebugBuffering = true;
361 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
362 LLVMContext &Context = getGlobalContext();
364 cl::ParseCommandLineOptions(argc, argv,
365 "llvm .bc -> .bc modular optimizer and analysis printer\n");
367 // Allocate a full target machine description only if necessary.
368 // FIXME: The choice of target should be controllable on the command line.
369 std::auto_ptr<TargetMachine> target;
373 // Load the input module...
374 std::auto_ptr<Module> M;
375 M.reset(ParseIRFile(InputFilename, Err, Context));
378 Err.Print(argv[0], errs());
382 // Figure out what stream we are supposed to write to...
383 raw_ostream *Out = 0;
384 bool DeleteStream = false;
385 if (!NoOutput && !AnalyzeOnly) {
386 if (OutputFilename == "-") {
389 // If we're printing a bitcode file, switch stdout to binary mode.
390 // FIXME: This switches outs() globally, not just for the bitcode output.
392 sys::Program::ChangeStdoutToBinary();
394 if (NoOutput || AnalyzeOnly) {
395 errs() << "WARNING: The -o (output filename) option is ignored when\n"
396 "the --disable-output or --analyze options are used.\n";
398 // Make sure that the Output file gets unlinked from the disk if we get
400 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
402 std::string ErrorInfo;
403 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
404 raw_fd_ostream::F_Binary);
405 if (!ErrorInfo.empty()) {
406 errs() << ErrorInfo << '\n';
415 // If the output is set to be emitted to standard out, and standard out is a
416 // console, print out a warning message and refuse to do it. We don't
417 // impress anyone by spewing tons of binary goo to a terminal.
418 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
419 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
422 // Create a PassManager to hold and optimize the collection of passes we are
427 // Add an appropriate TargetData instance for this module...
429 const std::string &ModuleDataLayout = M.get()->getDataLayout();
430 if (!ModuleDataLayout.empty())
431 TD = new TargetData(ModuleDataLayout);
432 else if (!DefaultDataLayout.empty())
433 TD = new TargetData(DefaultDataLayout);
438 OwningPtr<PassManager> FPasses;
439 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
440 FPasses.reset(new PassManager());
442 FPasses->add(new TargetData(*TD));
445 // If the -strip-debug command line option was specified, add it. If
446 // -std-compile-opts was also specified, it will handle StripDebug.
447 if (StripDebug && !StandardCompileOpts)
448 addPass(Passes, createStripSymbolsPass(true));
450 // Create a new optimization pass for each one specified on the command line
451 for (unsigned i = 0; i < PassList.size(); ++i) {
452 // Check to see if -std-compile-opts was specified before this option. If
454 if (StandardCompileOpts &&
455 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
456 AddStandardCompilePasses(Passes);
457 StandardCompileOpts = false;
460 if (StandardLinkOpts &&
461 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
462 AddStandardLinkPasses(Passes);
463 StandardLinkOpts = false;
466 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
467 AddOptimizationPasses(Passes, *FPasses, 1);
471 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
472 AddOptimizationPasses(Passes, *FPasses, 2);
476 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
477 AddOptimizationPasses(Passes, *FPasses, 3);
481 const PassInfo *PassInf = PassList[i];
483 if (PassInf->getNormalCtor())
484 P = PassInf->getNormalCtor()();
486 errs() << argv[0] << ": cannot create pass: "
487 << PassInf->getPassName() << "\n";
489 PassKind Kind = P->getPassKind();
495 Passes.add(new BasicBlockPassPrinter(PassInf));
498 Passes.add(new LoopPassPrinter(PassInf));
501 Passes.add(new FunctionPassPrinter(PassInf));
503 case PT_CallGraphSCC:
504 Passes.add(new CallGraphSCCPassPrinter(PassInf));
507 Passes.add(new ModulePassPrinter(PassInf));
514 Passes.add(createPrintModulePass(&errs()));
517 // If -std-compile-opts was specified at the end of the pass list, add them.
518 if (StandardCompileOpts) {
519 AddStandardCompilePasses(Passes);
520 StandardCompileOpts = false;
523 if (StandardLinkOpts) {
524 AddStandardLinkPasses(Passes);
525 StandardLinkOpts = false;
529 AddOptimizationPasses(Passes, *FPasses, 1);
532 AddOptimizationPasses(Passes, *FPasses, 2);
535 AddOptimizationPasses(Passes, *FPasses, 3);
537 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
538 FPasses->run(*M.get());
540 // Check that the module is well formed on completion of optimization
541 if (!NoVerify && !VerifyEach)
542 Passes.add(createVerifierPass());
544 // Write bitcode or assembly out to disk or outs() as the last step...
545 if (!NoOutput && !AnalyzeOnly) {
547 Passes.add(createPrintModulePass(Out));
549 Passes.add(createBitcodeWriterPass(*Out));
552 // Now that we have all of the passes ready, run them.
553 Passes.run(*M.get());
555 // Delete the raw_fd_ostream.