[PM] Remove the old 'PassManager.h' header file at the top level of
[oota-llvm.git] / tools / opt / opt.cpp
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.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "BreakpointPrinter.h"
16 #include "NewPMDriver.h"
17 #include "PassPrinters.h"
18 #include "llvm/ADT/Triple.h"
19 #include "llvm/Analysis/CallGraph.h"
20 #include "llvm/Analysis/CallGraphSCCPass.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/RegionPass.h"
23 #include "llvm/Analysis/TargetLibraryInfo.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Bitcode/BitcodeWriterPass.h"
26 #include "llvm/CodeGen/CommandFlags.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/IRPrintingPasses.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LegacyPassNameParser.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/IRReader/IRReader.h"
34 #include "llvm/InitializePasses.h"
35 #include "llvm/LinkAllIR.h"
36 #include "llvm/LinkAllPasses.h"
37 #include "llvm/MC/SubtargetFeature.h"
38 #include "llvm/IR/LegacyPassManager.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FileSystem.h"
41 #include "llvm/Support/ManagedStatic.h"
42 #include "llvm/Support/PluginLoader.h"
43 #include "llvm/Support/PrettyStackTrace.h"
44 #include "llvm/Support/Signals.h"
45 #include "llvm/Support/SourceMgr.h"
46 #include "llvm/Support/SystemUtils.h"
47 #include "llvm/Support/TargetRegistry.h"
48 #include "llvm/Support/TargetSelect.h"
49 #include "llvm/Support/ToolOutputFile.h"
50 #include "llvm/Target/TargetMachine.h"
51 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
52 #include <algorithm>
53 #include <memory>
54 using namespace llvm;
55 using namespace opt_tool;
56
57 // The OptimizationList is automatically populated with registered Passes by the
58 // PassNameParser.
59 //
60 static cl::list<const PassInfo*, bool, PassNameParser>
61 PassList(cl::desc("Optimizations available:"));
62
63 // This flag specifies a textual description of the optimization pass pipeline
64 // to run over the module. This flag switches opt to use the new pass manager
65 // infrastructure, completely disabling all of the flags specific to the old
66 // pass management.
67 static cl::opt<std::string> PassPipeline(
68     "passes",
69     cl::desc("A textual description of the pass pipeline for optimizing"),
70     cl::Hidden);
71
72 // Other command line options...
73 //
74 static cl::opt<std::string>
75 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
76     cl::init("-"), cl::value_desc("filename"));
77
78 static cl::opt<std::string>
79 OutputFilename("o", cl::desc("Override output filename"),
80                cl::value_desc("filename"));
81
82 static cl::opt<bool>
83 Force("f", cl::desc("Enable binary output on terminals"));
84
85 static cl::opt<bool>
86 PrintEachXForm("p", cl::desc("Print module after each transformation"));
87
88 static cl::opt<bool>
89 NoOutput("disable-output",
90          cl::desc("Do not write result bitcode file"), cl::Hidden);
91
92 static cl::opt<bool>
93 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
94
95 static cl::opt<bool>
96 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
97
98 static cl::opt<bool>
99 VerifyEach("verify-each", cl::desc("Verify after each transform"));
100
101 static cl::opt<bool>
102 StripDebug("strip-debug",
103            cl::desc("Strip debugger symbol info from translation unit"));
104
105 static cl::opt<bool>
106 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
107
108 static cl::opt<bool>
109 DisableOptimizations("disable-opt",
110                      cl::desc("Do not run any optimization passes"));
111
112 static cl::opt<bool>
113 StandardLinkOpts("std-link-opts",
114                  cl::desc("Include the standard link time optimizations"));
115
116 static cl::opt<bool>
117 OptLevelO1("O1",
118            cl::desc("Optimization level 1. Similar to clang -O1"));
119
120 static cl::opt<bool>
121 OptLevelO2("O2",
122            cl::desc("Optimization level 2. Similar to clang -O2"));
123
124 static cl::opt<bool>
125 OptLevelOs("Os",
126            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
127
128 static cl::opt<bool>
129 OptLevelOz("Oz",
130            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
131
132 static cl::opt<bool>
133 OptLevelO3("O3",
134            cl::desc("Optimization level 3. Similar to clang -O3"));
135
136 static cl::opt<std::string>
137 TargetTriple("mtriple", cl::desc("Override target triple for module"));
138
139 static cl::opt<bool>
140 UnitAtATime("funit-at-a-time",
141             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
142             cl::init(true));
143
144 static cl::opt<bool>
145 DisableLoopUnrolling("disable-loop-unrolling",
146                      cl::desc("Disable loop unrolling in all relevant passes"),
147                      cl::init(false));
148 static cl::opt<bool>
149 DisableLoopVectorization("disable-loop-vectorization",
150                      cl::desc("Disable the loop vectorization pass"),
151                      cl::init(false));
152
153 static cl::opt<bool>
154 DisableSLPVectorization("disable-slp-vectorization",
155                         cl::desc("Disable the slp vectorization pass"),
156                         cl::init(false));
157
158
159 static cl::opt<bool>
160 DisableSimplifyLibCalls("disable-simplify-libcalls",
161                         cl::desc("Disable simplify-libcalls"));
162
163 static cl::opt<bool>
164 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
165
166 static cl::alias
167 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
168
169 static cl::opt<bool>
170 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
171
172 static cl::opt<bool>
173 PrintBreakpoints("print-breakpoints-for-testing",
174                  cl::desc("Print select breakpoints location for testing"));
175
176 static cl::opt<std::string>
177 DefaultDataLayout("default-data-layout",
178           cl::desc("data layout string to use if not specified by module"),
179           cl::value_desc("layout-string"), cl::init(""));
180
181
182
183 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
184   // Add the pass to the pass manager...
185   PM.add(P);
186
187   // If we are verifying all of the intermediate steps, add the verifier...
188   if (VerifyEach) {
189     PM.add(createVerifierPass());
190     PM.add(createDebugInfoVerifierPass());
191   }
192 }
193
194 /// This routine adds optimization passes based on selected optimization level,
195 /// OptLevel.
196 ///
197 /// OptLevel - Optimization Level
198 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
199                                   legacy::FunctionPassManager &FPM,
200                                   unsigned OptLevel, unsigned SizeLevel) {
201   FPM.add(createVerifierPass());          // Verify that input is correct
202   MPM.add(createDebugInfoVerifierPass()); // Verify that debug info is correct
203
204   PassManagerBuilder Builder;
205   Builder.OptLevel = OptLevel;
206   Builder.SizeLevel = SizeLevel;
207
208   if (DisableInline) {
209     // No inlining pass
210   } else if (OptLevel > 1) {
211     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
212   } else {
213     Builder.Inliner = createAlwaysInlinerPass();
214   }
215   Builder.DisableUnitAtATime = !UnitAtATime;
216   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
217                                DisableLoopUnrolling : OptLevel == 0;
218
219   // This is final, unless there is a #pragma vectorize enable
220   if (DisableLoopVectorization)
221     Builder.LoopVectorize = false;
222   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
223   else if (!Builder.LoopVectorize)
224     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
225
226   // When #pragma vectorize is on for SLP, do the same as above
227   Builder.SLPVectorize =
228       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
229
230   Builder.populateFunctionPassManager(FPM);
231   Builder.populateModulePassManager(MPM);
232 }
233
234 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
235   PassManagerBuilder Builder;
236   Builder.VerifyInput = true;
237   Builder.StripDebug = StripDebug;
238   if (DisableOptimizations)
239     Builder.OptLevel = 0;
240
241   if (!DisableInline)
242     Builder.Inliner = createFunctionInliningPass();
243   Builder.populateLTOPassManager(PM);
244 }
245
246 //===----------------------------------------------------------------------===//
247 // CodeGen-related helper functions.
248 //
249
250 CodeGenOpt::Level GetCodeGenOptLevel() {
251   if (OptLevelO1)
252     return CodeGenOpt::Less;
253   if (OptLevelO2)
254     return CodeGenOpt::Default;
255   if (OptLevelO3)
256     return CodeGenOpt::Aggressive;
257   return CodeGenOpt::None;
258 }
259
260 // Returns the TargetMachine instance or zero if no triple is provided.
261 static TargetMachine* GetTargetMachine(Triple TheTriple) {
262   std::string Error;
263   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
264                                                          Error);
265   // Some modules don't specify a triple, and this is okay.
266   if (!TheTarget) {
267     return nullptr;
268   }
269
270   // Package up features to be passed to target/subtarget
271   std::string FeaturesStr;
272   if (MAttrs.size()) {
273     SubtargetFeatures Features;
274     for (unsigned i = 0; i != MAttrs.size(); ++i)
275       Features.AddFeature(MAttrs[i]);
276     FeaturesStr = Features.getString();
277   }
278
279   return TheTarget->createTargetMachine(TheTriple.getTriple(),
280                                         MCPU, FeaturesStr,
281                                         InitTargetOptionsFromCodeGenFlags(),
282                                         RelocModel, CMModel,
283                                         GetCodeGenOptLevel());
284 }
285
286 #ifdef LINK_POLLY_INTO_TOOLS
287 namespace polly {
288 void initializePollyPasses(llvm::PassRegistry &Registry);
289 }
290 #endif
291
292 //===----------------------------------------------------------------------===//
293 // main for opt
294 //
295 int main(int argc, char **argv) {
296   sys::PrintStackTraceOnErrorSignal();
297   llvm::PrettyStackTraceProgram X(argc, argv);
298
299   // Enable debug stream buffering.
300   EnableDebugBuffering = true;
301
302   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
303   LLVMContext &Context = getGlobalContext();
304
305   InitializeAllTargets();
306   InitializeAllTargetMCs();
307   InitializeAllAsmPrinters();
308
309   // Initialize passes
310   PassRegistry &Registry = *PassRegistry::getPassRegistry();
311   initializeCore(Registry);
312   initializeScalarOpts(Registry);
313   initializeObjCARCOpts(Registry);
314   initializeVectorization(Registry);
315   initializeIPO(Registry);
316   initializeAnalysis(Registry);
317   initializeIPA(Registry);
318   initializeTransformUtils(Registry);
319   initializeInstCombine(Registry);
320   initializeInstrumentation(Registry);
321   initializeTarget(Registry);
322   // For codegen passes, only passes that do IR to IR transformation are
323   // supported.
324   initializeCodeGenPreparePass(Registry);
325   initializeAtomicExpandPass(Registry);
326   initializeRewriteSymbolsPass(Registry);
327   initializeWinEHPreparePass(Registry);
328
329 #ifdef LINK_POLLY_INTO_TOOLS
330   polly::initializePollyPasses(Registry);
331 #endif
332
333   cl::ParseCommandLineOptions(argc, argv,
334     "llvm .bc -> .bc modular optimizer and analysis printer\n");
335
336   if (AnalyzeOnly && NoOutput) {
337     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
338     return 1;
339   }
340
341   SMDiagnostic Err;
342
343   // Load the input module...
344   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
345
346   if (!M) {
347     Err.print(argv[0], errs());
348     return 1;
349   }
350
351   // If we are supposed to override the target triple, do so now.
352   if (!TargetTriple.empty())
353     M->setTargetTriple(Triple::normalize(TargetTriple));
354
355   // Figure out what stream we are supposed to write to...
356   std::unique_ptr<tool_output_file> Out;
357   if (NoOutput) {
358     if (!OutputFilename.empty())
359       errs() << "WARNING: The -o (output filename) option is ignored when\n"
360                 "the --disable-output option is used.\n";
361   } else {
362     // Default to standard output.
363     if (OutputFilename.empty())
364       OutputFilename = "-";
365
366     std::error_code EC;
367     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
368     if (EC) {
369       errs() << EC.message() << '\n';
370       return 1;
371     }
372   }
373
374   Triple ModuleTriple(M->getTargetTriple());
375   TargetMachine *Machine = nullptr;
376   if (ModuleTriple.getArch())
377     Machine = GetTargetMachine(ModuleTriple);
378   std::unique_ptr<TargetMachine> TM(Machine);
379
380   // If the output is set to be emitted to standard out, and standard out is a
381   // console, print out a warning message and refuse to do it.  We don't
382   // impress anyone by spewing tons of binary goo to a terminal.
383   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
384     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
385       NoOutput = true;
386
387   if (PassPipeline.getNumOccurrences() > 0) {
388     OutputKind OK = OK_NoOutput;
389     if (!NoOutput)
390       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
391
392     VerifierKind VK = VK_VerifyInAndOut;
393     if (NoVerify)
394       VK = VK_NoVerifier;
395     else if (VerifyEach)
396       VK = VK_VerifyEachPass;
397
398     // The user has asked to use the new pass manager and provided a pipeline
399     // string. Hand off the rest of the functionality to the new code for that
400     // layer.
401     return runPassPipeline(argv[0], Context, *M, TM.get(), Out.get(),
402                            PassPipeline, OK, VK)
403                ? 0
404                : 1;
405   }
406
407   // Create a PassManager to hold and optimize the collection of passes we are
408   // about to build.
409   //
410   legacy::PassManager Passes;
411
412   // Add an appropriate TargetLibraryInfo pass for the module's triple.
413   TargetLibraryInfoImpl TLII(ModuleTriple);
414
415   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
416   if (DisableSimplifyLibCalls)
417     TLII.disableAllFunctions();
418   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
419
420   // Add an appropriate DataLayout instance for this module.
421   const DataLayout *DL = M->getDataLayout();
422   if (!DL && !DefaultDataLayout.empty()) {
423     M->setDataLayout(DefaultDataLayout);
424     DL = M->getDataLayout();
425   }
426
427   if (DL)
428     Passes.add(new DataLayoutPass());
429
430   // Add internal analysis passes from the target machine.
431   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
432                                                      : TargetIRAnalysis()));
433
434   std::unique_ptr<legacy::FunctionPassManager> FPasses;
435   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
436     FPasses.reset(new legacy::FunctionPassManager(M.get()));
437     if (DL)
438       FPasses->add(new DataLayoutPass());
439     FPasses->add(createTargetTransformInfoWrapperPass(
440         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
441   }
442
443   if (PrintBreakpoints) {
444     // Default to standard output.
445     if (!Out) {
446       if (OutputFilename.empty())
447         OutputFilename = "-";
448
449       std::error_code EC;
450       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
451                                                 sys::fs::F_None);
452       if (EC) {
453         errs() << EC.message() << '\n';
454         return 1;
455       }
456     }
457     Passes.add(createBreakpointPrinter(Out->os()));
458     NoOutput = true;
459   }
460
461   // If the -strip-debug command line option was specified, add it.
462   if (StripDebug)
463     addPass(Passes, createStripSymbolsPass(true));
464
465   // Create a new optimization pass for each one specified on the command line
466   for (unsigned i = 0; i < PassList.size(); ++i) {
467     if (StandardLinkOpts &&
468         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
469       AddStandardLinkPasses(Passes);
470       StandardLinkOpts = false;
471     }
472
473     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
474       AddOptimizationPasses(Passes, *FPasses, 1, 0);
475       OptLevelO1 = false;
476     }
477
478     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
479       AddOptimizationPasses(Passes, *FPasses, 2, 0);
480       OptLevelO2 = false;
481     }
482
483     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
484       AddOptimizationPasses(Passes, *FPasses, 2, 1);
485       OptLevelOs = false;
486     }
487
488     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
489       AddOptimizationPasses(Passes, *FPasses, 2, 2);
490       OptLevelOz = false;
491     }
492
493     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
494       AddOptimizationPasses(Passes, *FPasses, 3, 0);
495       OptLevelO3 = false;
496     }
497
498     const PassInfo *PassInf = PassList[i];
499     Pass *P = nullptr;
500     if (PassInf->getTargetMachineCtor())
501       P = PassInf->getTargetMachineCtor()(TM.get());
502     else if (PassInf->getNormalCtor())
503       P = PassInf->getNormalCtor()();
504     else
505       errs() << argv[0] << ": cannot create pass: "
506              << PassInf->getPassName() << "\n";
507     if (P) {
508       PassKind Kind = P->getPassKind();
509       addPass(Passes, P);
510
511       if (AnalyzeOnly) {
512         switch (Kind) {
513         case PT_BasicBlock:
514           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
515           break;
516         case PT_Region:
517           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
518           break;
519         case PT_Loop:
520           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
521           break;
522         case PT_Function:
523           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
524           break;
525         case PT_CallGraphSCC:
526           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
527           break;
528         default:
529           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
530           break;
531         }
532       }
533     }
534
535     if (PrintEachXForm)
536       Passes.add(createPrintModulePass(errs()));
537   }
538
539   if (StandardLinkOpts) {
540     AddStandardLinkPasses(Passes);
541     StandardLinkOpts = false;
542   }
543
544   if (OptLevelO1)
545     AddOptimizationPasses(Passes, *FPasses, 1, 0);
546
547   if (OptLevelO2)
548     AddOptimizationPasses(Passes, *FPasses, 2, 0);
549
550   if (OptLevelOs)
551     AddOptimizationPasses(Passes, *FPasses, 2, 1);
552
553   if (OptLevelOz)
554     AddOptimizationPasses(Passes, *FPasses, 2, 2);
555
556   if (OptLevelO3)
557     AddOptimizationPasses(Passes, *FPasses, 3, 0);
558
559   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
560     FPasses->doInitialization();
561     for (Function &F : *M)
562       FPasses->run(F);
563     FPasses->doFinalization();
564   }
565
566   // Check that the module is well formed on completion of optimization
567   if (!NoVerify && !VerifyEach) {
568     Passes.add(createVerifierPass());
569     Passes.add(createDebugInfoVerifierPass());
570   }
571
572   // Write bitcode or assembly to the output as the last step...
573   if (!NoOutput && !AnalyzeOnly) {
574     if (OutputAssembly)
575       Passes.add(createPrintModulePass(Out->os()));
576     else
577       Passes.add(createBitcodeWriterPass(Out->os()));
578   }
579
580   // Before executing passes, print the final values of the LLVM options.
581   cl::PrintOptionValues();
582
583   // Now that we have all of the passes ready, run them.
584   Passes.run(*M);
585
586   // Declare success.
587   if (!NoOutput || PrintBreakpoints)
588     Out->keep();
589
590   return 0;
591 }