X86-64: Mark WINCALL and more tail call instructions as code gen only.
[llvm.git] / tools / opt / opt.cpp
blob0878737d34bc5068fd51f53b7a50fb38eb6183f9
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/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"
38 #include <memory>
39 #include <algorithm>
40 using namespace llvm;
42 // The OptimizationList is automatically populated with registered Passes by the
43 // PassNameParser.
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("-"));
58 static cl::opt<bool>
59 Force("f", cl::desc("Enable binary output on terminals"));
61 static cl::opt<bool>
62 PrintEachXForm("p", cl::desc("Print module after each transformation"));
64 static cl::opt<bool>
65 NoOutput("disable-output",
66 cl::desc("Do not write result bitcode file"), cl::Hidden);
68 static cl::opt<bool>
69 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
71 static cl::opt<bool>
72 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
74 static cl::opt<bool>
75 VerifyEach("verify-each", cl::desc("Verify after each transform"));
77 static cl::opt<bool>
78 StripDebug("strip-debug",
79 cl::desc("Strip debugger symbol info from translation unit"));
81 static cl::opt<bool>
82 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
84 static cl::opt<bool>
85 DisableOptimizations("disable-opt",
86 cl::desc("Do not run any optimization passes"));
88 static cl::opt<bool>
89 DisableInternalize("disable-internalize",
90 cl::desc("Do not mark all symbols as internal"));
92 static cl::opt<bool>
93 StandardCompileOpts("std-compile-opts",
94 cl::desc("Include the standard compile time optimizations"));
96 static cl::opt<bool>
97 StandardLinkOpts("std-link-opts",
98 cl::desc("Include the standard link time optimizations"));
100 static cl::opt<bool>
101 OptLevelO1("O1",
102 cl::desc("Optimization level 1. Similar to llvm-gcc -O1"));
104 static cl::opt<bool>
105 OptLevelO2("O2",
106 cl::desc("Optimization level 2. Similar to llvm-gcc -O2"));
108 static cl::opt<bool>
109 OptLevelO3("O3",
110 cl::desc("Optimization level 3. Similar to llvm-gcc -O3"));
112 static cl::opt<bool>
113 UnitAtATime("funit-at-a-time",
114 cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
115 cl::init(true));
117 static cl::opt<bool>
118 DisableSimplifyLibCalls("disable-simplify-libcalls",
119 cl::desc("Disable simplify-libcalls"));
121 static cl::opt<bool>
122 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
124 static cl::alias
125 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
127 static cl::opt<bool>
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 ------------
136 namespace {
138 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
139 static char ID;
140 const PassInfo *PassToPrint;
141 CallGraphSCCPassPrinter(const PassInfo *PI) :
142 CallGraphSCCPass(&ID), PassToPrint(PI) {}
144 virtual bool runOnSCC(CallGraphSCC &SCC) {
145 if (!Quiet) {
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();
150 if (F)
151 getAnalysisID<Pass>(PassToPrint).print(outs(), F->getParent());
154 // Get and print pass...
155 return false;
158 virtual const char *getPassName() const { return "'Pass' Printer"; }
160 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
161 AU.addRequiredID(PassToPrint);
162 AU.setPreservesAll();
166 char CallGraphSCCPassPrinter::ID = 0;
168 struct ModulePassPrinter : public ModulePass {
169 static char ID;
170 const PassInfo *PassToPrint;
171 ModulePassPrinter(const PassInfo *PI) : ModulePass(&ID),
172 PassToPrint(PI) {}
174 virtual bool runOnModule(Module &M) {
175 if (!Quiet) {
176 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
177 getAnalysisID<Pass>(PassToPrint).print(outs(), &M);
180 // Get and print pass...
181 return false;
184 virtual const char *getPassName() const { return "'Pass' Printer"; }
186 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
187 AU.addRequiredID(PassToPrint);
188 AU.setPreservesAll();
192 char ModulePassPrinter::ID = 0;
193 struct FunctionPassPrinter : public FunctionPass {
194 const PassInfo *PassToPrint;
195 static char ID;
196 FunctionPassPrinter(const PassInfo *PI) : FunctionPass(&ID),
197 PassToPrint(PI) {}
199 virtual bool runOnFunction(Function &F) {
200 if (!Quiet) {
201 outs() << "Printing analysis '" << PassToPrint->getPassName()
202 << "' for function '" << F.getName() << "':\n";
204 // Get and print pass...
205 getAnalysisID<Pass>(PassToPrint).print(outs(), F.getParent());
206 return false;
209 virtual const char *getPassName() const { return "FunctionPass Printer"; }
211 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
212 AU.addRequiredID(PassToPrint);
213 AU.setPreservesAll();
217 char FunctionPassPrinter::ID = 0;
219 struct LoopPassPrinter : public LoopPass {
220 static char ID;
221 const PassInfo *PassToPrint;
222 LoopPassPrinter(const PassInfo *PI) :
223 LoopPass(&ID), PassToPrint(PI) {}
225 virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
226 if (!Quiet) {
227 outs() << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
228 getAnalysisID<Pass>(PassToPrint).print(outs(),
229 L->getHeader()->getParent()->getParent());
231 // Get and print pass...
232 return false;
235 virtual const char *getPassName() const { return "'Pass' Printer"; }
237 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
238 AU.addRequiredID(PassToPrint);
239 AU.setPreservesAll();
243 char LoopPassPrinter::ID = 0;
245 struct BasicBlockPassPrinter : public BasicBlockPass {
246 const PassInfo *PassToPrint;
247 static char ID;
248 BasicBlockPassPrinter(const PassInfo *PI)
249 : BasicBlockPass(&ID), PassToPrint(PI) {}
251 virtual bool runOnBasicBlock(BasicBlock &BB) {
252 if (!Quiet) {
253 outs() << "Printing Analysis info for BasicBlock '" << BB.getName()
254 << "': Pass " << PassToPrint->getPassName() << ":\n";
257 // Get and print pass...
258 getAnalysisID<Pass>(PassToPrint).print(outs(), BB.getParent()->getParent());
259 return false;
262 virtual const char *getPassName() const { return "BasicBlockPass Printer"; }
264 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
265 AU.addRequiredID(PassToPrint);
266 AU.setPreservesAll();
270 char BasicBlockPassPrinter::ID = 0;
271 inline void addPass(PassManagerBase &PM, Pass *P) {
272 // Add the pass to the pass manager...
273 PM.add(P);
275 // If we are verifying all of the intermediate steps, add the verifier...
276 if (VerifyEach) PM.add(createVerifierPass());
279 /// AddOptimizationPasses - This routine adds optimization passes
280 /// based on selected optimization level, OptLevel. This routine
281 /// duplicates llvm-gcc behaviour.
283 /// OptLevel - Optimization Level
284 void AddOptimizationPasses(PassManagerBase &MPM, PassManagerBase &FPM,
285 unsigned OptLevel) {
286 createStandardFunctionPasses(&FPM, OptLevel);
288 llvm::Pass *InliningPass = 0;
289 if (DisableInline) {
290 // No inlining pass
291 } else if (OptLevel) {
292 unsigned Threshold = 200;
293 if (OptLevel > 2)
294 Threshold = 250;
295 InliningPass = createFunctionInliningPass(Threshold);
296 } else {
297 InliningPass = createAlwaysInlinerPass();
299 createStandardModulePasses(&MPM, OptLevel,
300 /*OptimizeSize=*/ false,
301 UnitAtATime,
302 /*UnrollLoops=*/ OptLevel > 1,
303 !DisableSimplifyLibCalls,
304 /*HaveExceptions=*/ true,
305 InliningPass);
308 void AddStandardCompilePasses(PassManagerBase &PM) {
309 PM.add(createVerifierPass()); // Verify that input is correct
311 addPass(PM, createLowerSetJmpPass()); // Lower llvm.setjmp/.longjmp
313 // If the -strip-debug command line option was specified, do it.
314 if (StripDebug)
315 addPass(PM, createStripSymbolsPass(true));
317 if (DisableOptimizations) return;
319 llvm::Pass *InliningPass = !DisableInline ? createFunctionInliningPass() : 0;
321 // -std-compile-opts adds the same module passes as -O3.
322 createStandardModulePasses(&PM, 3,
323 /*OptimizeSize=*/ false,
324 /*UnitAtATime=*/ true,
325 /*UnrollLoops=*/ true,
326 /*SimplifyLibCalls=*/ true,
327 /*HaveExceptions=*/ true,
328 InliningPass);
331 void AddStandardLinkPasses(PassManagerBase &PM) {
332 PM.add(createVerifierPass()); // Verify that input is correct
334 // If the -strip-debug command line option was specified, do it.
335 if (StripDebug)
336 addPass(PM, createStripSymbolsPass(true));
338 if (DisableOptimizations) return;
340 createStandardLTOPasses(&PM, /*Internalize=*/ !DisableInternalize,
341 /*RunInliner=*/ !DisableInline,
342 /*VerifyEach=*/ VerifyEach);
345 } // anonymous namespace
348 //===----------------------------------------------------------------------===//
349 // main for opt
351 int main(int argc, char **argv) {
352 sys::PrintStackTraceOnErrorSignal();
353 llvm::PrettyStackTraceProgram X(argc, argv);
355 // Enable debug stream buffering.
356 EnableDebugBuffering = true;
358 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
359 LLVMContext &Context = getGlobalContext();
361 cl::ParseCommandLineOptions(argc, argv,
362 "llvm .bc -> .bc modular optimizer and analysis printer\n");
364 // Allocate a full target machine description only if necessary.
365 // FIXME: The choice of target should be controllable on the command line.
366 std::auto_ptr<TargetMachine> target;
368 SMDiagnostic Err;
370 // Load the input module...
371 std::auto_ptr<Module> M;
372 M.reset(ParseIRFile(InputFilename, Err, Context));
374 if (M.get() == 0) {
375 Err.Print(argv[0], errs());
376 return 1;
379 // Figure out what stream we are supposed to write to...
380 raw_ostream *Out = 0;
381 bool DeleteStream = false;
382 if (!NoOutput && !AnalyzeOnly) {
383 if (OutputFilename == "-") {
384 // Print to stdout.
385 Out = &outs();
386 // If we're printing a bitcode file, switch stdout to binary mode.
387 // FIXME: This switches outs() globally, not just for the bitcode output.
388 if (!OutputAssembly)
389 sys::Program::ChangeStdoutToBinary();
390 } else {
391 if (NoOutput || AnalyzeOnly) {
392 errs() << "WARNING: The -o (output filename) option is ignored when\n"
393 "the --disable-output or --analyze options are used.\n";
394 } else {
395 // Make sure that the Output file gets unlinked from the disk if we get
396 // a SIGINT.
397 sys::RemoveFileOnSignal(sys::Path(OutputFilename));
399 std::string ErrorInfo;
400 Out = new raw_fd_ostream(OutputFilename.c_str(), ErrorInfo,
401 raw_fd_ostream::F_Binary);
402 if (!ErrorInfo.empty()) {
403 errs() << ErrorInfo << '\n';
404 delete Out;
405 return 1;
407 DeleteStream = true;
412 // If the output is set to be emitted to standard out, and standard out is a
413 // console, print out a warning message and refuse to do it. We don't
414 // impress anyone by spewing tons of binary goo to a terminal.
415 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
416 if (CheckBitcodeOutputToConsole(*Out, !Quiet))
417 NoOutput = true;
419 // Create a PassManager to hold and optimize the collection of passes we are
420 // about to build...
422 PassManager Passes;
424 // Add an appropriate TargetData instance for this module...
425 TargetData *TD = 0;
426 const std::string &ModuleDataLayout = M.get()->getDataLayout();
427 if (!ModuleDataLayout.empty())
428 TD = new TargetData(ModuleDataLayout);
429 else if (!DefaultDataLayout.empty())
430 TD = new TargetData(DefaultDataLayout);
432 if (TD)
433 Passes.add(TD);
435 OwningPtr<PassManager> FPasses;
436 if (OptLevelO1 || OptLevelO2 || OptLevelO3) {
437 FPasses.reset(new PassManager());
438 if (TD)
439 FPasses->add(new TargetData(*TD));
442 // If the -strip-debug command line option was specified, add it. If
443 // -std-compile-opts was also specified, it will handle StripDebug.
444 if (StripDebug && !StandardCompileOpts)
445 addPass(Passes, createStripSymbolsPass(true));
447 // Create a new optimization pass for each one specified on the command line
448 for (unsigned i = 0; i < PassList.size(); ++i) {
449 // Check to see if -std-compile-opts was specified before this option. If
450 // so, handle it.
451 if (StandardCompileOpts &&
452 StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
453 AddStandardCompilePasses(Passes);
454 StandardCompileOpts = false;
457 if (StandardLinkOpts &&
458 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
459 AddStandardLinkPasses(Passes);
460 StandardLinkOpts = false;
463 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
464 AddOptimizationPasses(Passes, *FPasses, 1);
465 OptLevelO1 = false;
468 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
469 AddOptimizationPasses(Passes, *FPasses, 2);
470 OptLevelO2 = false;
473 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
474 AddOptimizationPasses(Passes, *FPasses, 3);
475 OptLevelO3 = false;
478 const PassInfo *PassInf = PassList[i];
479 Pass *P = 0;
480 if (PassInf->getNormalCtor())
481 P = PassInf->getNormalCtor()();
482 else
483 errs() << argv[0] << ": cannot create pass: "
484 << PassInf->getPassName() << "\n";
485 if (P) {
486 PassKind Kind = P->getPassKind();
487 addPass(Passes, P);
489 if (AnalyzeOnly) {
490 switch (Kind) {
491 case PT_BasicBlock:
492 Passes.add(new BasicBlockPassPrinter(PassInf));
493 break;
494 case PT_Loop:
495 Passes.add(new LoopPassPrinter(PassInf));
496 break;
497 case PT_Function:
498 Passes.add(new FunctionPassPrinter(PassInf));
499 break;
500 case PT_CallGraphSCC:
501 Passes.add(new CallGraphSCCPassPrinter(PassInf));
502 break;
503 default:
504 Passes.add(new ModulePassPrinter(PassInf));
505 break;
510 if (PrintEachXForm)
511 Passes.add(createPrintModulePass(&errs()));
514 // If -std-compile-opts was specified at the end of the pass list, add them.
515 if (StandardCompileOpts) {
516 AddStandardCompilePasses(Passes);
517 StandardCompileOpts = false;
520 if (StandardLinkOpts) {
521 AddStandardLinkPasses(Passes);
522 StandardLinkOpts = false;
525 if (OptLevelO1)
526 AddOptimizationPasses(Passes, *FPasses, 1);
528 if (OptLevelO2)
529 AddOptimizationPasses(Passes, *FPasses, 2);
531 if (OptLevelO3)
532 AddOptimizationPasses(Passes, *FPasses, 3);
534 if (OptLevelO1 || OptLevelO2 || OptLevelO3)
535 FPasses->run(*M.get());
537 // Check that the module is well formed on completion of optimization
538 if (!NoVerify && !VerifyEach)
539 Passes.add(createVerifierPass());
541 // Write bitcode or assembly out to disk or outs() as the last step...
542 if (!NoOutput && !AnalyzeOnly) {
543 if (OutputAssembly)
544 Passes.add(createPrintModulePass(Out));
545 else
546 Passes.add(createBitcodeWriterPass(*Out));
549 // Now that we have all of the passes ready, run them.
550 Passes.run(*M.get());
552 // Delete the raw_fd_ostream.
553 if (DeleteStream)
554 delete Out;
555 return 0;