Add missing include for ptrdiff_t. Patch by Joerg Sonnenberger!
[llvm.git] / tools / opt / opt.cpp
blobff8f65cfff7738b6ff77b018c06ff03813ee3b9d
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/PassManager.h"
18 #include "llvm/CallGraphSCCPass.h"
19 #include "llvm/Bitcode/ReaderWriter.h"
20 #include "llvm/Assembly/PrintModulePass.h"
21 #include "llvm/Analysis/DebugInfo.h"
22 #include "llvm/Analysis/Verifier.h"
23 #include "llvm/Analysis/LoopPass.h"
24 #include "llvm/Analysis/RegionPass.h"
25 #include "llvm/Analysis/CallGraph.h"
26 #include "llvm/Target/TargetData.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Support/PassNameParser.h"
29 #include "llvm/Support/Signals.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/IRReader.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/PluginLoader.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/StandardPasses.h"
36 #include "llvm/Support/SystemUtils.h"
37 #include "llvm/Support/ToolOutputFile.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/LinkAllVMCore.h"
40 #include <memory>
41 #include <algorithm>
42 using namespace llvm;
44 // The OptimizationList is automatically populated with registered Passes by the
45 // PassNameParser.
47 static cl::list<const PassInfo*, bool, PassNameParser>
48 PassList(cl::desc("Optimizations available:"));
50 // Other command line options...
52 static cl::opt<std::string>
53 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
54 cl::init("-"), cl::value_desc("filename"));
56 static cl::opt<std::string>
57 OutputFilename("o", cl::desc("Override output filename"),
58 cl::value_desc("filename"));
60 static cl::opt<bool>
61 Force("f", cl::desc("Enable binary output on terminals"));
63 static cl::opt<bool>
64 PrintEachXForm("p", cl::desc("Print module after each transformation"));
66 static cl::opt<bool>
67 NoOutput("disable-output",
68 cl::desc("Do not write result bitcode file"), cl::Hidden);
70 static cl::opt<bool>
71 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
73 static cl::opt<bool>
74 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
76 static cl::opt<bool>
77 VerifyEach("verify-each", cl::desc("Verify after each transform"));
79 static cl::opt<bool>
80 StripDebug("strip-debug",
81 cl::desc("Strip debugger symbol info from translation unit"));
83 static cl::opt<bool>
84 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
86 static cl::opt<bool>
87 DisableOptimizations("disable-opt",
88 cl::desc("Do not run any optimization passes"));
90 static cl::opt<bool>
91 DisableInternalize("disable-internalize",
92 cl::desc("Do not mark all symbols as internal"));
94 static cl::opt<bool>
95 StandardCompileOpts("std-compile-opts",
96 cl::desc("Include the standard compile time optimizations"));
98 static cl::opt<bool>
99 StandardLinkOpts("std-link-opts",
100 cl::desc("Include the standard link time optimizations"));
102 static cl::opt<bool>
103 OptLevelO1("O1",
104 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
106 static cl::opt<bool>
107 OptLevelO2("O2",
108 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
110 static cl::opt<bool>
111 OptLevelO3("O3",
112 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
114 static cl::opt<bool>
115 UnitAtATime("funit-at-a-time",
116 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
117 cl::init(true));
119 static cl::opt<bool>
120 DisableSimplifyLibCalls("disable-simplify-libcalls",
121 cl::desc("Disable simplify-libcalls"));
123 static cl::opt<bool>
124 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
126 static cl::alias
127 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
129 static cl::opt<bool>
130 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
132 static cl::opt<bool>
133 PrintBreakpoints("print-breakpoints-for-testing",
134 cl::desc("Print select breakpoints location for testing"));
136 static cl::opt<std::string>
137 DefaultDataLayout("default-data-layout",
138 cl::desc("data layout string to use if not specified by module"),
139 cl::value_desc("layout-string"), cl::init(""));
141 // ---------- Define Printers for module and function passes ------------
142 namespace {
144 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
145 static char ID;
146 const PassInfo *PassToPrint;
147 raw_ostream &Out;
148 std::string PassName;
150 CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
151 CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
152 std::string PassToPrintName = PassToPrint->getPassName();
153 PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
156 virtual bool runOnSCC(CallGraphSCC &SCC) {
157 if (!Quiet)
158 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
160 // Get and print pass...
161 for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
162 Function *F = (*I)->getFunction();
163 if (F)
164 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
165 F->getParent());
167 return false;
170 virtual const char *getPassName() const { return PassName.c_str(); }
172 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
173 AU.addRequiredID(PassToPrint->getTypeInfo());
174 AU.setPreservesAll();
178 char CallGraphSCCPassPrinter::ID = 0;
180 struct ModulePassPrinter : public ModulePass {
181 static char ID;
182 const PassInfo *PassToPrint;
183 raw_ostream &Out;
184 std::string PassName;
186 ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
187 : ModulePass(ID), PassToPrint(PI), Out(out) {
188 std::string PassToPrintName = PassToPrint->getPassName();
189 PassName = "ModulePass Printer: " + PassToPrintName;
192 virtual bool runOnModule(Module &M) {
193 if (!Quiet)
194 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
196 // Get and print pass...
197 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
198 return false;
201 virtual const char *getPassName() const { return PassName.c_str(); }
203 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
204 AU.addRequiredID(PassToPrint->getTypeInfo());
205 AU.setPreservesAll();
209 char ModulePassPrinter::ID = 0;
210 struct FunctionPassPrinter : public FunctionPass {
211 const PassInfo *PassToPrint;
212 raw_ostream &Out;
213 static char ID;
214 std::string PassName;
216 FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
217 : FunctionPass(ID), PassToPrint(PI), Out(out) {
218 std::string PassToPrintName = PassToPrint->getPassName();
219 PassName = "FunctionPass Printer: " + PassToPrintName;
222 virtual bool runOnFunction(Function &F) {
223 if (!Quiet)
224 Out << "Printing analysis '" << PassToPrint->getPassName()
225 << "' for function '" << F.getName() << "':\n";
227 // Get and print pass...
228 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
229 F.getParent());
230 return false;
233 virtual const char *getPassName() const { return PassName.c_str(); }
235 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
236 AU.addRequiredID(PassToPrint->getTypeInfo());
237 AU.setPreservesAll();
241 char FunctionPassPrinter::ID = 0;
243 struct LoopPassPrinter : public LoopPass {
244 static char ID;
245 const PassInfo *PassToPrint;
246 raw_ostream &Out;
247 std::string PassName;
249 LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
250 LoopPass(ID), PassToPrint(PI), Out(out) {
251 std::string PassToPrintName = PassToPrint->getPassName();
252 PassName = "LoopPass Printer: " + PassToPrintName;
256 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
257 if (!Quiet)
258 Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
260 // Get and print pass...
261 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
262 L->getHeader()->getParent()->getParent());
263 return false;
266 virtual const char *getPassName() const { return PassName.c_str(); }
268 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
269 AU.addRequiredID(PassToPrint->getTypeInfo());
270 AU.setPreservesAll();
274 char LoopPassPrinter::ID = 0;
276 struct RegionPassPrinter : public RegionPass {
277 static char ID;
278 const PassInfo *PassToPrint;
279 raw_ostream &Out;
280 std::string PassName;
282 RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
283 PassToPrint(PI), Out(out) {
284 std::string PassToPrintName = PassToPrint->getPassName();
285 PassName = "RegionPass Printer: " + PassToPrintName;
288 virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
289 if (!Quiet) {
290 Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
291 << "region: '" << R->getNameStr() << "' in function '"
292 << R->getEntry()->getParent()->getNameStr() << "':\n";
294 // Get and print pass...
295 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
296 R->getEntry()->getParent()->getParent());
297 return false;
300 virtual const char *getPassName() const { return PassName.c_str(); }
302 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
303 AU.addRequiredID(PassToPrint->getTypeInfo());
304 AU.setPreservesAll();
308 char RegionPassPrinter::ID = 0;
310 struct BasicBlockPassPrinter : public BasicBlockPass {
311 const PassInfo *PassToPrint;
312 raw_ostream &Out;
313 static char ID;
314 std::string PassName;
316 BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
317 : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
318 std::string PassToPrintName = PassToPrint->getPassName();
319 PassName = "BasicBlockPass Printer: " + PassToPrintName;
322 virtual bool runOnBasicBlock(BasicBlock &BB) {
323 if (!Quiet)
324 Out << "Printing Analysis info for BasicBlock '" << BB.getName()
325 << "': Pass " << PassToPrint->getPassName() << ":\n";
327 // Get and print pass...
328 getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
329 BB.getParent()->getParent());
330 return false;
333 virtual const char *getPassName() const { return PassName.c_str(); }
335 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
336 AU.addRequiredID(PassToPrint->getTypeInfo());
337 AU.setPreservesAll();
341 char BasicBlockPassPrinter::ID = 0;
343 struct BreakpointPrinter : public FunctionPass {
344 raw_ostream &Out;
345 static char ID;
347 BreakpointPrinter(raw_ostream &out)
348 : FunctionPass(ID), Out(out) {
351 virtual bool runOnFunction(Function &F) {
352 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
353 BasicBlock::const_iterator BI = I->end();
354 --BI;
355 do {
356 const Instruction *In = BI;
357 const DebugLoc DL = In->getDebugLoc();
358 if (!DL.isUnknown()) {
359 DIScope S(DL.getScope(getGlobalContext()));
360 Out << S.getFilename() << " " << DL.getLine() << "\n";
361 break;
363 --BI;
364 } while (BI != I->begin());
365 break;
367 BasicBlock &EntryBB = F.getEntryBlock();
368 for (Function::iterator I = F.begin(), E = F.end(); I != E; ++I) {
369 BasicBlock *BB = I;
370 if (BB == &EntryBB) continue;
371 for (BasicBlock::iterator BI = I->begin(), BE = I->end(); BI != BE; ++BI)
372 if (CallInst *CI = dyn_cast<CallInst>(BI)) {
373 const DebugLoc DL = CI->getDebugLoc();
374 if (!DL.isUnknown()) {
375 DIScope S(DL.getScope(getGlobalContext()));
376 Out << S.getFilename() << " " << DL.getLine() << "\n";
380 return false;
383 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
384 AU.setPreservesAll();
388 char BreakpointPrinter::ID = 0;
390 inline void addPass(PassManagerBase &PM, Pass *P) {
391 // Add the pass to the pass manager...
392 PM.add(P);
394 // If we are verifying all of the intermediate steps, add the verifier...
395 if (VerifyEach) PM.add(createVerifierPass());
398 /// AddOptimizationPasses - This routine adds optimization passes
399 /// based on selected optimization level, OptLevel. This routine
400 /// duplicates llvm-gcc behaviour.
402 /// OptLevel - Optimization Level
403 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
404 unsigned OptLevel) {
405 createStandardFunctionPasses(&FPM, OptLevel);
407 llvm::Pass *InliningPass = 0;
408 if (DisableInline) {
409 // No inlining pass
410 } else if (OptLevel) {
411 unsigned Threshold = 225;
412 if (OptLevel > 2)
413 Threshold = 275;
414 InliningPass = createFunctionInliningPass(Threshold);
415 } else {
416 InliningPass = createAlwaysInlinerPass();
418 createStandardModulePasses(&MPM, OptLevel,
419 /*OptimizeSize=*/ false,
420 UnitAtATime,
421 /*UnrollLoops=*/ OptLevel > 1,
422 !DisableSimplifyLibCalls,
423 /*HaveExceptions=*/ true,
424 InliningPass);
427 void AddStandardCompilePasses(PassManagerBase &PM) {
428 PM.add(createVerifierPass()); // Verify that input is correct
430 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
432 // If the -strip-debug command line option was specified, do it.
433 if (StripDebug)
434 addPass(PM, createStripSymbolsPass(true));
436 if (DisableOptimizations) return;
438 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
440 // -std-compile-opts adds the same module passes as -O3.
441 createStandardModulePasses(&PM, 3,
442 /*OptimizeSize=*/ false,
443 /*UnitAtATime=*/ true,
444 /*UnrollLoops=*/ true,
445 /*SimplifyLibCalls=*/ true,
446 /*HaveExceptions=*/ true,
447 InliningPass);
450 void AddStandardLinkPasses(PassManagerBase &PM) {
451 PM.add(createVerifierPass()); // Verify that input is correct
453 // If the -strip-debug command line option was specified, do it.
454 if (StripDebug)
455 addPass(PM, createStripSymbolsPass(true));
457 if (DisableOptimizations) return;
459 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
460 /*RunInliner=*/ !DisableInline,
461 /*VerifyEach=*/ VerifyEach);
464 } // anonymous namespace
467 //===----------------------------------------------------------------------===//
468 // main for opt
470 int main(int argc, char **argv) {
471 sys::PrintStackTraceOnErrorSignal();
472 llvm::PrettyStackTraceProgram X(argc, argv);
474 // Enable debug stream buffering.
475 EnableDebugBuffering = true;
477 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
478 LLVMContext &Context = getGlobalContext();
480 // Initialize passes
481 PassRegistry &Registry = *PassRegistry::getPassRegistry();
482 initializeCore(Registry);
483 initializeScalarOpts(Registry);
484 initializeIPO(Registry);
485 initializeAnalysis(Registry);
486 initializeIPA(Registry);
487 initializeTransformUtils(Registry);
488 initializeInstCombine(Registry);
489 initializeInstrumentation(Registry);
490 initializeTarget(Registry);
492 cl::ParseCommandLineOptions(argc, argv,
493 "llvm .bc -> .bc modular optimizer and analysis printer\n");
495 if (AnalyzeOnly && NoOutput) {
496 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
497 return 1;
500 // Allocate a full target machine description only if necessary.
501 // FIXME: The choice of target should be controllable on the command line.
502 std::auto_ptr<TargetMachine> target;
504 SMDiagnostic Err;
506 // Load the input module...
507 std::auto_ptr<Module> M;
508 M.reset(ParseIRFile(InputFilename, Err, Context));
510 if (M.get() == 0) {
511 Err.Print(argv[0], errs());
512 return 1;
515 // Figure out what stream we are supposed to write to...
516 OwningPtr<tool_output_file> Out;
517 if (NoOutput) {
518 if (!OutputFilename.empty())
519 errs() << "WARNING: The -o (output filename) option is ignored when\n"
520 "the --disable-output option is used.\n";
521 } else {
522 // Default to standard output.
523 if (OutputFilename.empty())
524 OutputFilename = "-";
526 std::string ErrorInfo;
527 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
528 raw_fd_ostream::F_Binary));
529 if (!ErrorInfo.empty()) {
530 errs() << ErrorInfo << '\n';
531 return 1;
535 // If the output is set to be emitted to standard out, and standard out is a
536 // console, print out a warning message and refuse to do it. We don't
537 // impress anyone by spewing tons of binary goo to a terminal.
538 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
539 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
540 NoOutput = true;
542 // Create a PassManager to hold and optimize the collection of passes we are
543 // about to build...
545 PassManager Passes;
547 // Add an appropriate TargetData instance for this module...
548 TargetData *TD = 0;
549 const std::string &ModuleDataLayout = M.get()->getDataLayout();
550 if (!ModuleDataLayout.empty())
551 TD = new TargetData(ModuleDataLayout);
552 else if (!DefaultDataLayout.empty())
553 TD = new TargetData(DefaultDataLayout);
555 if (TD)
556 Passes.add(TD);
558 OwningPtr<PassManager> FPasses;
559 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
560 FPasses.reset(new PassManager());
561 if (TD)
562 FPasses->add(new TargetData(*TD));
565 if (PrintBreakpoints) {
566 // Default to standard output.
567 if (!Out) {
568 if (OutputFilename.empty())
569 OutputFilename = "-";
571 std::string ErrorInfo;
572 Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
573 raw_fd_ostream::F_Binary));
574 if (!ErrorInfo.empty()) {
575 errs() << ErrorInfo << '\n';
576 return 1;
579 Passes.add(new BreakpointPrinter(Out->os()));
580 NoOutput = true;
583 // If the -strip-debug command line option was specified, add it. If
584 // -std-compile-opts was also specified, it will handle StripDebug.
585 if (StripDebug && !StandardCompileOpts)
586 addPass(Passes, createStripSymbolsPass(true));
588 // Create a new optimization pass for each one specified on the command line
589 for (unsigned i = 0; i < PassList.size(); ++i) {
590 // Check to see if -std-compile-opts was specified before this option. If
591 // so, handle it.
592 if (StandardCompileOpts &&
593 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
594 AddStandardCompilePasses(Passes);
595 StandardCompileOpts = false;
598 if (StandardLinkOpts &&
599 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
600 AddStandardLinkPasses(Passes);
601 StandardLinkOpts = false;
604 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
605 AddOptimizationPasses(Passes, *FPasses, 1);
606 OptLevelO1 = false;
609 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
610 AddOptimizationPasses(Passes, *FPasses, 2);
611 OptLevelO2 = false;
614 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
615 AddOptimizationPasses(Passes, *FPasses, 3);
616 OptLevelO3 = false;
619 const PassInfo *PassInf = PassList[i];
620 Pass *P = 0;
621 if (PassInf->getNormalCtor())
622 P = PassInf->getNormalCtor()();
623 else
624 errs() << argv[0] << ": cannot create pass: "
625 << PassInf->getPassName() << "\n";
626 if (P) {
627 PassKind Kind = P->getPassKind();
628 addPass(Passes, P);
630 if (AnalyzeOnly) {
631 switch (Kind) {
632 case PT_BasicBlock:
633 Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
634 break;
635 case PT_Region:
636 Passes.add(new RegionPassPrinter(PassInf, Out->os()));
637 break;
638 case PT_Loop:
639 Passes.add(new LoopPassPrinter(PassInf, Out->os()));
640 break;
641 case PT_Function:
642 Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
643 break;
644 case PT_CallGraphSCC:
645 Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
646 break;
647 default:
648 Passes.add(new ModulePassPrinter(PassInf, Out->os()));
649 break;
654 if (PrintEachXForm)
655 Passes.add(createPrintModulePass(&errs()));
658 // If -std-compile-opts was specified at the end of the pass list, add them.
659 if (StandardCompileOpts) {
660 AddStandardCompilePasses(Passes);
661 StandardCompileOpts = false;
664 if (StandardLinkOpts) {
665 AddStandardLinkPasses(Passes);
666 StandardLinkOpts = false;
669 if (OptLevelO1)
670 AddOptimizationPasses(Passes, *FPasses, 1);
672 if (OptLevelO2)
673 AddOptimizationPasses(Passes, *FPasses, 2);
675 if (OptLevelO3)
676 AddOptimizationPasses(Passes, *FPasses, 3);
678 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
679 FPasses->run(*M.get());
681 // Check that the module is well formed on completion of optimization
682 if (!NoVerify && !VerifyEach)
683 Passes.add(createVerifierPass());
685 // Write bitcode or assembly to the output as the last step...
686 if (!NoOutput && !AnalyzeOnly) {
687 if (OutputAssembly)
688 Passes.add(createPrintModulePass(&Out->os()));
689 else
690 Passes.add(createBitcodeWriterPass(Out->os()));
693 // Now that we have all of the passes ready, run them.
694 Passes.run(*M.get());
696 // Declare success.
697 if (!NoOutput || PrintBreakpoints)
698 Out->keep();
700 return 0;