Transform: add SymbolRewriter pass
[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 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   initializeDebugIRPass(Registry);
311   initializeScalarOpts(Registry);
312   initializeObjCARCOpts(Registry);
313   initializeVectorization(Registry);
314   initializeIPO(Registry);
315   initializeAnalysis(Registry);
316   initializeIPA(Registry);
317   initializeTransformUtils(Registry);
318   initializeInstCombine(Registry);
319   initializeInstrumentation(Registry);
320   initializeTarget(Registry);
321   // For codegen passes, only passes that do IR to IR transformation are
322   // supported.
323   initializeCodeGenPreparePass(Registry);
324   initializeAtomicExpandPass(Registry);
325   initializeRewriteSymbolsPass(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.get()) {
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.get(), 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   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
406
407   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
408   if (DisableSimplifyLibCalls)
409     TLI->disableAllFunctions();
410   Passes.add(TLI);
411
412   // Add an appropriate DataLayout instance for this module.
413   const DataLayout *DL = M.get()->getDataLayout();
414   if (!DL && !DefaultDataLayout.empty()) {
415     M->setDataLayout(DefaultDataLayout);
416     DL = M.get()->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.get())
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.get())
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.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
450       if (EC) {
451         errs() << EC.message() << '\n';
452         return 1;
453       }
454     }
455     Passes.add(createBreakpointPrinter(Out->os()));
456     NoOutput = true;
457   }
458
459   // If the -strip-debug command line option was specified, add it.
460   if (StripDebug)
461     addPass(Passes, createStripSymbolsPass(true));
462
463   // Create a new optimization pass for each one specified on the command line
464   for (unsigned i = 0; i < PassList.size(); ++i) {
465     if (StandardLinkOpts &&
466         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
467       AddStandardLinkPasses(Passes);
468       StandardLinkOpts = false;
469     }
470
471     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
472       AddOptimizationPasses(Passes, *FPasses, 1, 0);
473       OptLevelO1 = false;
474     }
475
476     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
477       AddOptimizationPasses(Passes, *FPasses, 2, 0);
478       OptLevelO2 = false;
479     }
480
481     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
482       AddOptimizationPasses(Passes, *FPasses, 2, 1);
483       OptLevelOs = false;
484     }
485
486     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
487       AddOptimizationPasses(Passes, *FPasses, 2, 2);
488       OptLevelOz = false;
489     }
490
491     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
492       AddOptimizationPasses(Passes, *FPasses, 3, 0);
493       OptLevelO3 = false;
494     }
495
496     const PassInfo *PassInf = PassList[i];
497     Pass *P = nullptr;
498     if (PassInf->getTargetMachineCtor())
499       P = PassInf->getTargetMachineCtor()(TM.get());
500     else if (PassInf->getNormalCtor())
501       P = PassInf->getNormalCtor()();
502     else
503       errs() << argv[0] << ": cannot create pass: "
504              << PassInf->getPassName() << "\n";
505     if (P) {
506       PassKind Kind = P->getPassKind();
507       addPass(Passes, P);
508
509       if (AnalyzeOnly) {
510         switch (Kind) {
511         case PT_BasicBlock:
512           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
513           break;
514         case PT_Region:
515           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
516           break;
517         case PT_Loop:
518           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
519           break;
520         case PT_Function:
521           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
522           break;
523         case PT_CallGraphSCC:
524           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
525           break;
526         default:
527           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
528           break;
529         }
530       }
531     }
532
533     if (PrintEachXForm)
534       Passes.add(createPrintModulePass(errs()));
535   }
536
537   if (StandardLinkOpts) {
538     AddStandardLinkPasses(Passes);
539     StandardLinkOpts = false;
540   }
541
542   if (OptLevelO1)
543     AddOptimizationPasses(Passes, *FPasses, 1, 0);
544
545   if (OptLevelO2)
546     AddOptimizationPasses(Passes, *FPasses, 2, 0);
547
548   if (OptLevelOs)
549     AddOptimizationPasses(Passes, *FPasses, 2, 1);
550
551   if (OptLevelOz)
552     AddOptimizationPasses(Passes, *FPasses, 2, 2);
553
554   if (OptLevelO3)
555     AddOptimizationPasses(Passes, *FPasses, 3, 0);
556
557   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
558     FPasses->doInitialization();
559     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
560       FPasses->run(*F);
561     FPasses->doFinalization();
562   }
563
564   // Check that the module is well formed on completion of optimization
565   if (!NoVerify && !VerifyEach) {
566     Passes.add(createVerifierPass());
567     Passes.add(createDebugInfoVerifierPass());
568   }
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.get());
583
584   // Declare success.
585   if (!NoOutput || PrintBreakpoints)
586     Out->keep();
587
588   return 0;
589 }