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