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