]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/opt/opt.cpp
Pull down pjdfstest 0.1
[FreeBSD/FreeBSD.git] / contrib / llvm / 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/LegacyPassManager.h"
32 #include "llvm/IR/LegacyPassNameParser.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/Verifier.h"
35 #include "llvm/IRReader/IRReader.h"
36 #include "llvm/InitializePasses.h"
37 #include "llvm/LinkAllIR.h"
38 #include "llvm/LinkAllPasses.h"
39 #include "llvm/MC/SubtargetFeature.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/PluginLoader.h"
45 #include "llvm/Support/PrettyStackTrace.h"
46 #include "llvm/Support/Signals.h"
47 #include "llvm/Support/SourceMgr.h"
48 #include "llvm/Support/SystemUtils.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/ToolOutputFile.h"
52 #include "llvm/Support/YAMLTraits.h"
53 #include "llvm/Target/TargetMachine.h"
54 #include "llvm/Transforms/Coroutines.h"
55 #include "llvm/Transforms/IPO/AlwaysInliner.h"
56 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
57 #include "llvm/Transforms/Utils/Cloning.h"
58 #include <algorithm>
59 #include <memory>
60 using namespace llvm;
61 using namespace opt_tool;
62
63 // The OptimizationList is automatically populated with registered Passes by the
64 // PassNameParser.
65 //
66 static cl::list<const PassInfo*, bool, PassNameParser>
67 PassList(cl::desc("Optimizations available:"));
68
69 // This flag specifies a textual description of the optimization pass pipeline
70 // to run over the module. This flag switches opt to use the new pass manager
71 // infrastructure, completely disabling all of the flags specific to the old
72 // pass management.
73 static cl::opt<std::string> PassPipeline(
74     "passes",
75     cl::desc("A textual description of the pass pipeline for optimizing"),
76     cl::Hidden);
77
78 // Other command line options...
79 //
80 static cl::opt<std::string>
81 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
82     cl::init("-"), cl::value_desc("filename"));
83
84 static cl::opt<std::string>
85 OutputFilename("o", cl::desc("Override output filename"),
86                cl::value_desc("filename"));
87
88 static cl::opt<bool>
89 Force("f", cl::desc("Enable binary output on terminals"));
90
91 static cl::opt<bool>
92 PrintEachXForm("p", cl::desc("Print module after each transformation"));
93
94 static cl::opt<bool>
95 NoOutput("disable-output",
96          cl::desc("Do not write result bitcode file"), cl::Hidden);
97
98 static cl::opt<bool>
99 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
100
101 static cl::opt<bool>
102     OutputThinLTOBC("thinlto-bc",
103                     cl::desc("Write output as ThinLTO-ready bitcode"));
104
105 static cl::opt<bool>
106 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
107
108 static cl::opt<bool>
109 VerifyEach("verify-each", cl::desc("Verify after each transform"));
110
111 static cl::opt<bool>
112     DisableDITypeMap("disable-debug-info-type-map",
113                      cl::desc("Don't use a uniquing type map for debug info"));
114
115 static cl::opt<bool>
116 StripDebug("strip-debug",
117            cl::desc("Strip debugger symbol info from translation unit"));
118
119 static cl::opt<bool>
120 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
121
122 static cl::opt<bool>
123 DisableOptimizations("disable-opt",
124                      cl::desc("Do not run any optimization passes"));
125
126 static cl::opt<bool>
127 StandardLinkOpts("std-link-opts",
128                  cl::desc("Include the standard link time optimizations"));
129
130 static cl::opt<bool>
131 OptLevelO0("O0",
132   cl::desc("Optimization level 0. Similar to clang -O0"));
133
134 static cl::opt<bool>
135 OptLevelO1("O1",
136            cl::desc("Optimization level 1. Similar to clang -O1"));
137
138 static cl::opt<bool>
139 OptLevelO2("O2",
140            cl::desc("Optimization level 2. Similar to clang -O2"));
141
142 static cl::opt<bool>
143 OptLevelOs("Os",
144            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
145
146 static cl::opt<bool>
147 OptLevelOz("Oz",
148            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
149
150 static cl::opt<bool>
151 OptLevelO3("O3",
152            cl::desc("Optimization level 3. Similar to clang -O3"));
153
154 static cl::opt<unsigned>
155 CodeGenOptLevel("codegen-opt-level",
156                 cl::desc("Override optimization level for codegen hooks"));
157
158 static cl::opt<std::string>
159 TargetTriple("mtriple", cl::desc("Override target triple for module"));
160
161 static cl::opt<bool>
162 UnitAtATime("funit-at-a-time",
163             cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
164             cl::init(true));
165
166 static cl::opt<bool>
167 DisableLoopUnrolling("disable-loop-unrolling",
168                      cl::desc("Disable loop unrolling in all relevant passes"),
169                      cl::init(false));
170 static cl::opt<bool>
171 DisableLoopVectorization("disable-loop-vectorization",
172                      cl::desc("Disable the loop vectorization pass"),
173                      cl::init(false));
174
175 static cl::opt<bool>
176 DisableSLPVectorization("disable-slp-vectorization",
177                         cl::desc("Disable the slp vectorization pass"),
178                         cl::init(false));
179
180 static cl::opt<bool> EmitSummaryIndex("module-summary",
181                                       cl::desc("Emit module summary index"),
182                                       cl::init(false));
183
184 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
185                                     cl::init(false));
186
187 static cl::opt<bool>
188 DisableSimplifyLibCalls("disable-simplify-libcalls",
189                         cl::desc("Disable simplify-libcalls"));
190
191 static cl::opt<bool>
192 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
193
194 static cl::alias
195 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
196
197 static cl::opt<bool>
198 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
199
200 static cl::opt<bool>
201 PrintBreakpoints("print-breakpoints-for-testing",
202                  cl::desc("Print select breakpoints location for testing"));
203
204 static cl::opt<std::string>
205 DefaultDataLayout("default-data-layout",
206           cl::desc("data layout string to use if not specified by module"),
207           cl::value_desc("layout-string"), cl::init(""));
208
209 static cl::opt<bool> PreserveBitcodeUseListOrder(
210     "preserve-bc-uselistorder",
211     cl::desc("Preserve use-list order when writing LLVM bitcode."),
212     cl::init(true), cl::Hidden);
213
214 static cl::opt<bool> PreserveAssemblyUseListOrder(
215     "preserve-ll-uselistorder",
216     cl::desc("Preserve use-list order when writing LLVM assembly."),
217     cl::init(false), cl::Hidden);
218
219 static cl::opt<bool>
220     RunTwice("run-twice",
221              cl::desc("Run all passes twice, re-using the same pass manager."),
222              cl::init(false), cl::Hidden);
223
224 static cl::opt<bool> DiscardValueNames(
225     "discard-value-names",
226     cl::desc("Discard names from Value (other than GlobalValue)."),
227     cl::init(false), cl::Hidden);
228
229 static cl::opt<bool> Coroutines(
230   "enable-coroutines",
231   cl::desc("Enable coroutine passes."),
232   cl::init(false), cl::Hidden);
233
234 static cl::opt<bool> PassRemarksWithHotness(
235     "pass-remarks-with-hotness",
236     cl::desc("With PGO, include profile count in optimization remarks"),
237     cl::Hidden);
238
239 static cl::opt<std::string>
240     RemarksFilename("pass-remarks-output",
241                     cl::desc("YAML output filename for pass remarks"),
242                     cl::value_desc("filename"));
243
244 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
245   // Add the pass to the pass manager...
246   PM.add(P);
247
248   // If we are verifying all of the intermediate steps, add the verifier...
249   if (VerifyEach)
250     PM.add(createVerifierPass());
251 }
252
253 /// This routine adds optimization passes based on selected optimization level,
254 /// OptLevel.
255 ///
256 /// OptLevel - Optimization Level
257 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
258                                   legacy::FunctionPassManager &FPM,
259                                   TargetMachine *TM, unsigned OptLevel,
260                                   unsigned SizeLevel) {
261   if (!NoVerify || VerifyEach)
262     FPM.add(createVerifierPass()); // Verify that input is correct
263
264   PassManagerBuilder Builder;
265   Builder.OptLevel = OptLevel;
266   Builder.SizeLevel = SizeLevel;
267
268   if (DisableInline) {
269     // No inlining pass
270   } else if (OptLevel > 1) {
271     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel);
272   } else {
273     Builder.Inliner = createAlwaysInlinerLegacyPass();
274   }
275   Builder.DisableUnitAtATime = !UnitAtATime;
276   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
277                                DisableLoopUnrolling : OptLevel == 0;
278
279   // This is final, unless there is a #pragma vectorize enable
280   if (DisableLoopVectorization)
281     Builder.LoopVectorize = false;
282   // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
283   else if (!Builder.LoopVectorize)
284     Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
285
286   // When #pragma vectorize is on for SLP, do the same as above
287   Builder.SLPVectorize =
288       DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
289
290   // Add target-specific passes that need to run as early as possible.
291   if (TM)
292     Builder.addExtension(
293         PassManagerBuilder::EP_EarlyAsPossible,
294         [&](const PassManagerBuilder &, legacy::PassManagerBase &PM) {
295           TM->addEarlyAsPossiblePasses(PM);
296         });
297
298   if (Coroutines)
299     addCoroutinePassesToExtensionPoints(Builder);
300
301   Builder.populateFunctionPassManager(FPM);
302   Builder.populateModulePassManager(MPM);
303 }
304
305 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
306   PassManagerBuilder Builder;
307   Builder.VerifyInput = true;
308   if (DisableOptimizations)
309     Builder.OptLevel = 0;
310
311   if (!DisableInline)
312     Builder.Inliner = createFunctionInliningPass();
313   Builder.populateLTOPassManager(PM);
314 }
315
316 //===----------------------------------------------------------------------===//
317 // CodeGen-related helper functions.
318 //
319
320 static CodeGenOpt::Level GetCodeGenOptLevel() {
321   if (CodeGenOptLevel.getNumOccurrences())
322     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
323   if (OptLevelO1)
324     return CodeGenOpt::Less;
325   if (OptLevelO2)
326     return CodeGenOpt::Default;
327   if (OptLevelO3)
328     return CodeGenOpt::Aggressive;
329   return CodeGenOpt::None;
330 }
331
332 // Returns the TargetMachine instance or zero if no triple is provided.
333 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
334                                        StringRef FeaturesStr,
335                                        const TargetOptions &Options) {
336   std::string Error;
337   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
338                                                          Error);
339   // Some modules don't specify a triple, and this is okay.
340   if (!TheTarget) {
341     return nullptr;
342   }
343
344   return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
345                                         FeaturesStr, Options, getRelocModel(),
346                                         CMModel, GetCodeGenOptLevel());
347 }
348
349 #ifdef LINK_POLLY_INTO_TOOLS
350 namespace polly {
351 void initializePollyPasses(llvm::PassRegistry &Registry);
352 }
353 #endif
354
355 //===----------------------------------------------------------------------===//
356 // main for opt
357 //
358 int main(int argc, char **argv) {
359   sys::PrintStackTraceOnErrorSignal(argv[0]);
360   llvm::PrettyStackTraceProgram X(argc, argv);
361
362   // Enable debug stream buffering.
363   EnableDebugBuffering = true;
364
365   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
366   LLVMContext Context;
367
368   InitializeAllTargets();
369   InitializeAllTargetMCs();
370   InitializeAllAsmPrinters();
371   InitializeAllAsmParsers();
372
373   // Initialize passes
374   PassRegistry &Registry = *PassRegistry::getPassRegistry();
375   initializeCore(Registry);
376   initializeCoroutines(Registry);
377   initializeScalarOpts(Registry);
378   initializeObjCARCOpts(Registry);
379   initializeVectorization(Registry);
380   initializeIPO(Registry);
381   initializeAnalysis(Registry);
382   initializeTransformUtils(Registry);
383   initializeInstCombine(Registry);
384   initializeInstrumentation(Registry);
385   initializeTarget(Registry);
386   // For codegen passes, only passes that do IR to IR transformation are
387   // supported.
388   initializeCodeGenPreparePass(Registry);
389   initializeAtomicExpandPass(Registry);
390   initializeRewriteSymbolsLegacyPassPass(Registry);
391   initializeWinEHPreparePass(Registry);
392   initializeDwarfEHPreparePass(Registry);
393   initializeSafeStackPass(Registry);
394   initializeSjLjEHPreparePass(Registry);
395   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
396   initializeGlobalMergePass(Registry);
397   initializeInterleavedAccessPass(Registry);
398   initializeCountingFunctionInserterPass(Registry);
399   initializeUnreachableBlockElimLegacyPassPass(Registry);
400
401 #ifdef LINK_POLLY_INTO_TOOLS
402   polly::initializePollyPasses(Registry);
403 #endif
404
405   cl::ParseCommandLineOptions(argc, argv,
406     "llvm .bc -> .bc modular optimizer and analysis printer\n");
407
408   if (AnalyzeOnly && NoOutput) {
409     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
410     return 1;
411   }
412
413   SMDiagnostic Err;
414
415   Context.setDiscardValueNames(DiscardValueNames);
416   if (!DisableDITypeMap)
417     Context.enableDebugTypeODRUniquing();
418
419   if (PassRemarksWithHotness)
420     Context.setDiagnosticHotnessRequested(true);
421
422   std::unique_ptr<tool_output_file> YamlFile;
423   if (RemarksFilename != "") {
424     std::error_code EC;
425     YamlFile = llvm::make_unique<tool_output_file>(RemarksFilename, EC,
426                                                    sys::fs::F_None);
427     if (EC) {
428       errs() << EC.message() << '\n';
429       return 1;
430     }
431     Context.setDiagnosticsOutputFile(
432         llvm::make_unique<yaml::Output>(YamlFile->os()));
433   }
434
435   // Load the input module...
436   std::unique_ptr<Module> M = parseIRFile(InputFilename, Err, Context);
437
438   if (!M) {
439     Err.print(argv[0], errs());
440     return 1;
441   }
442
443   // Strip debug info before running the verifier.
444   if (StripDebug)
445     StripDebugInfo(*M);
446
447   // Immediately run the verifier to catch any problems before starting up the
448   // pass pipelines.  Otherwise we can crash on broken code during
449   // doInitialization().
450   if (!NoVerify && verifyModule(*M, &errs())) {
451     errs() << argv[0] << ": " << InputFilename
452            << ": error: input module is broken!\n";
453     return 1;
454   }
455
456   // If we are supposed to override the target triple, do so now.
457   if (!TargetTriple.empty())
458     M->setTargetTriple(Triple::normalize(TargetTriple));
459
460   // Figure out what stream we are supposed to write to...
461   std::unique_ptr<tool_output_file> Out;
462   if (NoOutput) {
463     if (!OutputFilename.empty())
464       errs() << "WARNING: The -o (output filename) option is ignored when\n"
465                 "the --disable-output option is used.\n";
466   } else {
467     // Default to standard output.
468     if (OutputFilename.empty())
469       OutputFilename = "-";
470
471     std::error_code EC;
472     Out.reset(new tool_output_file(OutputFilename, EC, sys::fs::F_None));
473     if (EC) {
474       errs() << EC.message() << '\n';
475       return 1;
476     }
477   }
478
479   Triple ModuleTriple(M->getTargetTriple());
480   std::string CPUStr, FeaturesStr;
481   TargetMachine *Machine = nullptr;
482   const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
483
484   if (ModuleTriple.getArch()) {
485     CPUStr = getCPUStr();
486     FeaturesStr = getFeaturesStr();
487     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
488   }
489
490   std::unique_ptr<TargetMachine> TM(Machine);
491
492   // Override function attributes based on CPUStr, FeaturesStr, and command line
493   // flags.
494   setFunctionAttributes(CPUStr, FeaturesStr, *M);
495
496   // If the output is set to be emitted to standard out, and standard out is a
497   // console, print out a warning message and refuse to do it.  We don't
498   // impress anyone by spewing tons of binary goo to a terminal.
499   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
500     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
501       NoOutput = true;
502
503   if (PassPipeline.getNumOccurrences() > 0) {
504     OutputKind OK = OK_NoOutput;
505     if (!NoOutput)
506       OK = OutputAssembly ? OK_OutputAssembly : OK_OutputBitcode;
507
508     VerifierKind VK = VK_VerifyInAndOut;
509     if (NoVerify)
510       VK = VK_NoVerifier;
511     else if (VerifyEach)
512       VK = VK_VerifyEachPass;
513
514     // The user has asked to use the new pass manager and provided a pipeline
515     // string. Hand off the rest of the functionality to the new code for that
516     // layer.
517     return runPassPipeline(argv[0], *M, TM.get(), Out.get(),
518                            PassPipeline, OK, VK, PreserveAssemblyUseListOrder,
519                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
520                            EmitModuleHash)
521                ? 0
522                : 1;
523   }
524
525   // Create a PassManager to hold and optimize the collection of passes we are
526   // about to build.
527   //
528   legacy::PassManager Passes;
529
530   // Add an appropriate TargetLibraryInfo pass for the module's triple.
531   TargetLibraryInfoImpl TLII(ModuleTriple);
532
533   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
534   if (DisableSimplifyLibCalls)
535     TLII.disableAllFunctions();
536   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
537
538   // Add an appropriate DataLayout instance for this module.
539   const DataLayout &DL = M->getDataLayout();
540   if (DL.isDefault() && !DefaultDataLayout.empty()) {
541     M->setDataLayout(DefaultDataLayout);
542   }
543
544   // Add internal analysis passes from the target machine.
545   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
546                                                      : TargetIRAnalysis()));
547
548   std::unique_ptr<legacy::FunctionPassManager> FPasses;
549   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
550       OptLevelO3) {
551     FPasses.reset(new legacy::FunctionPassManager(M.get()));
552     FPasses->add(createTargetTransformInfoWrapperPass(
553         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
554   }
555
556   if (PrintBreakpoints) {
557     // Default to standard output.
558     if (!Out) {
559       if (OutputFilename.empty())
560         OutputFilename = "-";
561
562       std::error_code EC;
563       Out = llvm::make_unique<tool_output_file>(OutputFilename, EC,
564                                                 sys::fs::F_None);
565       if (EC) {
566         errs() << EC.message() << '\n';
567         return 1;
568       }
569     }
570     Passes.add(createBreakpointPrinter(Out->os()));
571     NoOutput = true;
572   }
573
574   // Create a new optimization pass for each one specified on the command line
575   for (unsigned i = 0; i < PassList.size(); ++i) {
576     if (StandardLinkOpts &&
577         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
578       AddStandardLinkPasses(Passes);
579       StandardLinkOpts = false;
580     }
581
582     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
583       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
584       OptLevelO0 = false;
585     }
586
587     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
588       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
589       OptLevelO1 = false;
590     }
591
592     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
593       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
594       OptLevelO2 = false;
595     }
596
597     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
598       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
599       OptLevelOs = false;
600     }
601
602     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
603       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
604       OptLevelOz = false;
605     }
606
607     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
608       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
609       OptLevelO3 = false;
610     }
611
612     const PassInfo *PassInf = PassList[i];
613     Pass *P = nullptr;
614     if (PassInf->getTargetMachineCtor())
615       P = PassInf->getTargetMachineCtor()(TM.get());
616     else if (PassInf->getNormalCtor())
617       P = PassInf->getNormalCtor()();
618     else
619       errs() << argv[0] << ": cannot create pass: "
620              << PassInf->getPassName() << "\n";
621     if (P) {
622       PassKind Kind = P->getPassKind();
623       addPass(Passes, P);
624
625       if (AnalyzeOnly) {
626         switch (Kind) {
627         case PT_BasicBlock:
628           Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
629           break;
630         case PT_Region:
631           Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
632           break;
633         case PT_Loop:
634           Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
635           break;
636         case PT_Function:
637           Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
638           break;
639         case PT_CallGraphSCC:
640           Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
641           break;
642         default:
643           Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
644           break;
645         }
646       }
647     }
648
649     if (PrintEachXForm)
650       Passes.add(
651           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
652   }
653
654   if (StandardLinkOpts) {
655     AddStandardLinkPasses(Passes);
656     StandardLinkOpts = false;
657   }
658
659   if (OptLevelO0)
660     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
661
662   if (OptLevelO1)
663     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
664
665   if (OptLevelO2)
666     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
667
668   if (OptLevelOs)
669     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
670
671   if (OptLevelOz)
672     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
673
674   if (OptLevelO3)
675     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
676
677   if (FPasses) {
678     FPasses->doInitialization();
679     for (Function &F : *M)
680       FPasses->run(F);
681     FPasses->doFinalization();
682   }
683
684   // Check that the module is well formed on completion of optimization
685   if (!NoVerify && !VerifyEach)
686     Passes.add(createVerifierPass());
687
688   // In run twice mode, we want to make sure the output is bit-by-bit
689   // equivalent if we run the pass manager again, so setup two buffers and
690   // a stream to write to them. Note that llc does something similar and it
691   // may be worth to abstract this out in the future.
692   SmallVector<char, 0> Buffer;
693   SmallVector<char, 0> CompileTwiceBuffer;
694   std::unique_ptr<raw_svector_ostream> BOS;
695   raw_ostream *OS = nullptr;
696
697   // Write bitcode or assembly to the output as the last step...
698   if (!NoOutput && !AnalyzeOnly) {
699     assert(Out);
700     OS = &Out->os();
701     if (RunTwice) {
702       BOS = make_unique<raw_svector_ostream>(Buffer);
703       OS = BOS.get();
704     }
705     if (OutputAssembly) {
706       if (EmitSummaryIndex)
707         report_fatal_error("Text output is incompatible with -module-summary");
708       if (EmitModuleHash)
709         report_fatal_error("Text output is incompatible with -module-hash");
710       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
711     } else if (OutputThinLTOBC)
712       Passes.add(createWriteThinLTOBitcodePass(*OS));
713     else
714       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
715                                          EmitSummaryIndex, EmitModuleHash));
716   }
717
718   // Before executing passes, print the final values of the LLVM options.
719   cl::PrintOptionValues();
720
721   // If requested, run all passes again with the same pass manager to catch
722   // bugs caused by persistent state in the passes
723   if (RunTwice) {
724       std::unique_ptr<Module> M2(CloneModule(M.get()));
725       Passes.run(*M2);
726       CompileTwiceBuffer = Buffer;
727       Buffer.clear();
728   }
729
730   // Now that we have all of the passes ready, run them.
731   Passes.run(*M);
732
733   // Compare the two outputs and make sure they're the same
734   if (RunTwice) {
735     assert(Out);
736     if (Buffer.size() != CompileTwiceBuffer.size() ||
737         (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
738          0)) {
739       errs() << "Running the pass manager twice changed the output.\n"
740                 "Writing the result of the second run to the specified output.\n"
741                 "To generate the one-run comparison binary, just run without\n"
742                 "the compile-twice option\n";
743       Out->os() << BOS->str();
744       Out->keep();
745       if (YamlFile)
746         YamlFile->keep();
747       return 1;
748     }
749     Out->os() << BOS->str();
750   }
751
752   // Declare success.
753   if (!NoOutput || PrintBreakpoints)
754     Out->keep();
755
756   if (YamlFile)
757     YamlFile->keep();
758
759   return 0;
760 }