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