Add a Windows EH preparation pass that zaps resumes
[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/Bitcode/BitcodeWriterPass.h"
25 #include "llvm/CodeGen/CommandFlags.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/IRPrintingPasses.h"
28 #include "llvm/IR/LLVMContext.h"
29 #include "llvm/IR/LegacyPassNameParser.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/IRReader/IRReader.h"
33 #include "llvm/InitializePasses.h"
34 #include "llvm/LinkAllIR.h"
35 #include "llvm/LinkAllPasses.h"
36 #include "llvm/MC/SubtargetFeature.h"
37 #include "llvm/PassManager.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/ManagedStatic.h"
41 #include "llvm/Support/PluginLoader.h"
42 #include "llvm/Support/PrettyStackTrace.h"
43 #include "llvm/Support/Signals.h"
44 #include "llvm/Support/SourceMgr.h"
45 #include "llvm/Support/SystemUtils.h"
46 #include "llvm/Support/TargetRegistry.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/ToolOutputFile.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 StandardLinkOpts("std-link-opts",
113                  cl::desc("Include the standard link time optimizations"));
114
115 static cl::opt<bool>
116 OptLevelO1("O1",
117            cl::desc("Optimization level 1. Similar to clang -O1"));
118
119 static cl::opt<bool>
120 OptLevelO2("O2",
121            cl::desc("Optimization level 2. Similar to clang -O2"));
122
123 static cl::opt<bool>
124 OptLevelOs("Os",
125            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
126
127 static cl::opt<bool>
128 OptLevelOz("Oz",
129            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
130
131 static cl::opt<bool>
132 OptLevelO3("O3",
133            cl::desc("Optimization level 3. Similar to clang -O3"));
134
135 static cl::opt<std::string>
136 TargetTriple("mtriple", cl::desc("Override target triple for module"));
137
138 static cl::opt<bool>
139 UnitAtATime("funit-at-a-time",
140             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
141             cl::init(true));
142
143 static cl::opt<bool>
144 DisableLoopUnrolling("disable-loop-unrolling",
145                      cl::desc("Disable loop unrolling in all relevant passes"),
146                      cl::init(false));
147 static cl::opt<bool>
148 DisableLoopVectorization("disable-loop-vectorization",
149                      cl::desc("Disable the loop vectorization pass"),
150                      cl::init(false));
151
152 static cl::opt<bool>
153 DisableSLPVectorization("disable-slp-vectorization",
154                         cl::desc("Disable the slp vectorization pass"),
155                         cl::init(false));
156
157
158 static cl::opt<bool>
159 DisableSimplifyLibCalls("disable-simplify-libcalls",
160                         cl::desc("Disable simplify-libcalls"));
161
162 static cl::opt<bool>
163 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
164
165 static cl::alias
166 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
167
168 static cl::opt<bool>
169 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
170
171 static cl::opt<bool>
172 PrintBreakpoints("print-breakpoints-for-testing",
173                  cl::desc("Print select breakpoints location for testing"));
174
175 static cl::opt<std::string>
176 DefaultDataLayout("default-data-layout",
177           cl::desc("data layout string to use if not specified by module"),
178           cl::value_desc("layout-string"), cl::init(""));
179
180
181
182 static inline void addPass(PassManagerBase &PM, Pass *P) {
183   // Add the pass to the pass manager...
184   PM.add(P);
185
186   // If we are verifying all of the intermediate steps, add the verifier...
187   if (VerifyEach) {
188     PM.add(createVerifierPass());
189     PM.add(createDebugInfoVerifierPass());
190   }
191 }
192
193 /// This routine adds optimization passes based on selected optimization level,
194 /// OptLevel.
195 ///
196 /// OptLevel - Optimization Level
197 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
198                                   unsigned OptLevel, unsigned SizeLevel) {
199   FPM.add(createVerifierPass());          // Verify that input is correct
200   MPM.add(createDebugInfoVerifierPass()); // Verify that debug info 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(PassManagerBase &PM) {
233   PassManagerBuilder Builder;
234   Builder.VerifyInput = true;
235   Builder.StripDebug = StripDebug;
236   if (DisableOptimizations)
237     Builder.OptLevel = 0;
238
239   if (!DisableInline)
240     Builder.Inliner = createFunctionInliningPass();
241   Builder.populateLTOPassManager(PM);
242 }
243
244 //===----------------------------------------------------------------------===//
245 // CodeGen-related helper functions.
246 //
247
248 CodeGenOpt::Level GetCodeGenOptLevel() {
249   if (OptLevelO1)
250     return CodeGenOpt::Less;
251   if (OptLevelO2)
252     return CodeGenOpt::Default;
253   if (OptLevelO3)
254     return CodeGenOpt::Aggressive;
255   return CodeGenOpt::None;
256 }
257
258 // Returns the TargetMachine instance or zero if no triple is provided.
259 static TargetMachine* GetTargetMachine(Triple TheTriple) {
260   std::string Error;
261   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
262                                                          Error);
263   // Some modules don't specify a triple, and this is okay.
264   if (!TheTarget) {
265     return nullptr;
266   }
267
268   // Package up features to be passed to target/subtarget
269   std::string FeaturesStr;
270   if (MAttrs.size()) {
271     SubtargetFeatures Features;
272     for (unsigned i = 0; i != MAttrs.size(); ++i)
273       Features.AddFeature(MAttrs[i]);
274     FeaturesStr = Features.getString();
275   }
276
277   return TheTarget->createTargetMachine(TheTriple.getTriple(),
278                                         MCPU, FeaturesStr,
279                                         InitTargetOptionsFromCodeGenFlags(),
280                                         RelocModel, CMModel,
281                                         GetCodeGenOptLevel());
282 }
283
284 #ifdef LINK_POLLY_INTO_TOOLS
285 namespace polly {
286 void initializePollyPasses(llvm::PassRegistry &Registry);
287 }
288 #endif
289
290 //===----------------------------------------------------------------------===//
291 // main for opt
292 //
293 int main(int argc, char **argv) {
294   sys::PrintStackTraceOnErrorSignal();
295   llvm::PrettyStackTraceProgram X(argc, argv);
296
297   // Enable debug stream buffering.
298   EnableDebugBuffering = true;
299
300   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
301   LLVMContext &Context = getGlobalContext();
302
303   InitializeAllTargets();
304   InitializeAllTargetMCs();
305   InitializeAllAsmPrinters();
306
307   // Initialize passes
308   PassRegistry &Registry = *PassRegistry::getPassRegistry();
309   initializeCore(Registry);
310   initializeScalarOpts(Registry);
311   initializeObjCARCOpts(Registry);
312   initializeVectorization(Registry);
313   initializeIPO(Registry);
314   initializeAnalysis(Registry);
315   initializeIPA(Registry);
316   initializeTransformUtils(Registry);
317   initializeInstCombine(Registry);
318   initializeInstrumentation(Registry);
319   initializeTarget(Registry);
320   // For codegen passes, only passes that do IR to IR transformation are
321   // supported.
322   initializeCodeGenPreparePass(Registry);
323   initializeAtomicExpandPass(Registry);
324   initializeRewriteSymbolsPass(Registry);
325   initializeWinEHPreparePass(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   // If we are supposed to override the target triple, do so now.
350   if (!TargetTriple.empty())
351     M->setTargetTriple(Triple::normalize(TargetTriple));
352
353   // Figure out what stream we are supposed to write to...
354   std::unique_ptr<tool_output_file> Out;
355   if (NoOutput) {
356     if (!OutputFilename.empty())
357       errs() << "WARNING: The -o (output filename) option is ignored when\n"
358                 "the --disable-output option is used.\n";
359   } else {
360     // Default to standard output.
361     if (OutputFilename.empty())
362       OutputFilename = "-";
363
364     std::error_code EC;
365     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
366     if (EC) {
367       errs() << EC.message() << '\n';
368       return 1;
369     }
370   }
371
372   // If the output is set to be emitted to standard out, and standard out is a
373   // console, print out a warning message and refuse to do it.  We don't
374   // impress anyone by spewing tons of binary goo to a terminal.
375   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
376     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
377       NoOutput = true;
378
379   if (PassPipeline.getNumOccurrences() > 0) {
380     OutputKind OK = OK_NoOutput;
381     if (!NoOutput)
382       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
383
384     VerifierKind VK = VK_VerifyInAndOut;
385     if (NoVerify)
386       VK = VK_NoVerifier;
387     else if (VerifyEach)
388       VK = VK_VerifyEachPass;
389
390     // The user has asked to use the new pass manager and provided a pipeline
391     // string. Hand off the rest of the functionality to the new code for that
392     // layer.
393     return runPassPipeline(argv[0], Context, *M, Out.get(), PassPipeline,
394                            OK, VK)
395                ? 0
396                : 1;
397   }
398
399   // Create a PassManager to hold and optimize the collection of passes we are
400   // about to build.
401   //
402   PassManager Passes;
403
404   // Add an appropriate TargetLibraryInfo pass for the module's triple.
405   TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
406
407   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
408   if (DisableSimplifyLibCalls)
409     TLII.disableAllFunctions();
410   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
411
412   // Add an appropriate DataLayout instance for this module.
413   const DataLayout *DL = M->getDataLayout();
414   if (!DL && !DefaultDataLayout.empty()) {
415     M->setDataLayout(DefaultDataLayout);
416     DL = M->getDataLayout();
417   }
418
419   if (DL)
420     Passes.add(new DataLayoutPass());
421
422   Triple ModuleTriple(M->getTargetTriple());
423   TargetMachine *Machine = nullptr;
424   if (ModuleTriple.getArch())
425     Machine = GetTargetMachine(Triple(ModuleTriple));
426   std::unique_ptr<TargetMachine> TM(Machine);
427
428   // Add internal analysis passes from the target machine.
429   if (TM)
430     TM->addAnalysisPasses(Passes);
431
432   std::unique_ptr<FunctionPassManager> FPasses;
433   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
434     FPasses.reset(new FunctionPassManager(M.get()));
435     if (DL)
436       FPasses->add(new DataLayoutPass());
437     if (TM)
438       TM->addAnalysisPasses(*FPasses);
439
440   }
441
442   if (PrintBreakpoints) {
443     // Default to standard output.
444     if (!Out) {
445       if (OutputFilename.empty())
446         OutputFilename = "-";
447
448       std::error_code EC;
449       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
450                                                 sys::fs::F_None);
451       if (EC) {
452         errs() << EC.message() << '\n';
453         return 1;
454       }
455     }
456     Passes.add(createBreakpointPrinter(Out->os()));
457     NoOutput = true;
458   }
459
460   // If the -strip-debug command line option was specified, add it.
461   if (StripDebug)
462     addPass(Passes, createStripSymbolsPass(true));
463
464   // Create a new optimization pass for each one specified on the command line
465   for (unsigned i = 0; i < PassList.size(); ++i) {
466     if (StandardLinkOpts &&
467         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
468       AddStandardLinkPasses(Passes);
469       StandardLinkOpts = false;
470     }
471
472     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
473       AddOptimizationPasses(Passes, *FPasses, 1, 0);
474       OptLevelO1 = false;
475     }
476
477     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
478       AddOptimizationPasses(Passes, *FPasses, 2, 0);
479       OptLevelO2 = false;
480     }
481
482     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
483       AddOptimizationPasses(Passes, *FPasses, 2, 1);
484       OptLevelOs = false;
485     }
486
487     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
488       AddOptimizationPasses(Passes, *FPasses, 2, 2);
489       OptLevelOz = false;
490     }
491
492     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
493       AddOptimizationPasses(Passes, *FPasses, 3, 0);
494       OptLevelO3 = false;
495     }
496
497     const PassInfo *PassInf = PassList[i];
498     Pass *P = nullptr;
499     if (PassInf->getTargetMachineCtor())
500       P = PassInf->getTargetMachineCtor()(TM.get());
501     else if (PassInf->getNormalCtor())
502       P = PassInf->getNormalCtor()();
503     else
504       errs() << argv[0] << ": cannot create pass: "
505              << PassInf->getPassName() << "\n";
506     if (P) {
507       PassKind Kind = P->getPassKind();
508       addPass(Passes, P);
509
510       if (AnalyzeOnly) {
511         switch (Kind) {
512         case PT_BasicBlock:
513           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
514           break;
515         case PT_Region:
516           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
517           break;
518         case PT_Loop:
519           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
520           break;
521         case PT_Function:
522           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
523           break;
524         case PT_CallGraphSCC:
525           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
526           break;
527         default:
528           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
529           break;
530         }
531       }
532     }
533
534     if (PrintEachXForm)
535       Passes.add(createPrintModulePass(errs()));
536   }
537
538   if (StandardLinkOpts) {
539     AddStandardLinkPasses(Passes);
540     StandardLinkOpts = false;
541   }
542
543   if (OptLevelO1)
544     AddOptimizationPasses(Passes, *FPasses, 1, 0);
545
546   if (OptLevelO2)
547     AddOptimizationPasses(Passes, *FPasses, 2, 0);
548
549   if (OptLevelOs)
550     AddOptimizationPasses(Passes, *FPasses, 2, 1);
551
552   if (OptLevelOz)
553     AddOptimizationPasses(Passes, *FPasses, 2, 2);
554
555   if (OptLevelO3)
556     AddOptimizationPasses(Passes, *FPasses, 3, 0);
557
558   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
559     FPasses->doInitialization();
560     for (Function &F : *M)
561       FPasses->run(F);
562     FPasses->doFinalization();
563   }
564
565   // Check that the module is well formed on completion of optimization
566   if (!NoVerify && !VerifyEach) {
567     Passes.add(createVerifierPass());
568     Passes.add(createDebugInfoVerifierPass());
569   }
570
571   // Write bitcode or assembly to the output as the last step...
572   if (!NoOutput && !AnalyzeOnly) {
573     if (OutputAssembly)
574       Passes.add(createPrintModulePass(Out->os()));
575     else
576       Passes.add(createBitcodeWriterPass(Out->os()));
577   }
578
579   // Before executing passes, print the final values of the LLVM options.
580   cl::PrintOptionValues();
581
582   // Now that we have all of the passes ready, run them.
583   Passes.run(*M);
584
585   // Declare success.
586   if (!NoOutput || PrintBreakpoints)
587     Out->keep();
588
589   return 0;
590 }