xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 18b45339)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Optimizations may be specified an arbitrary number of times on the command
10 // line, They are run in the order specified.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "BreakpointPrinter.h"
15 #include "NewPMDriver.h"
16 #include "PassPrinters.h"
17 #include "llvm/ADT/Triple.h"
18 #include "llvm/Analysis/CallGraph.h"
19 #include "llvm/Analysis/CallGraphSCCPass.h"
20 #include "llvm/Analysis/LoopPass.h"
21 #include "llvm/Analysis/RegionPass.h"
22 #include "llvm/Analysis/TargetLibraryInfo.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/AsmParser/Parser.h"
25 #include "llvm/CodeGen/CommandFlags.h"
26 #include "llvm/CodeGen/TargetPassConfig.h"
27 #include "llvm/Config/llvm-config.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/DebugInfo.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/LLVMRemarkStreamer.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/InitLLVM.h"
45 #include "llvm/Support/PluginLoader.h"
46 #include "llvm/Support/SourceMgr.h"
47 #include "llvm/Support/SystemUtils.h"
48 #include "llvm/Support/TargetRegistry.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/ToolOutputFile.h"
51 #include "llvm/Support/YAMLTraits.h"
52 #include "llvm/Target/TargetMachine.h"
53 #include "llvm/Transforms/Coroutines.h"
54 #include "llvm/Transforms/IPO/AlwaysInliner.h"
55 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
56 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
57 #include "llvm/Transforms/Utils/Cloning.h"
58 #include "llvm/Transforms/Utils/Debugify.h"
59 #include <algorithm>
60 #include <memory>
61 using namespace llvm;
62 using namespace opt_tool;
63 
64 static codegen::RegisterCodeGenFlags CFG;
65 
66 // The OptimizationList is automatically populated with registered Passes by the
67 // PassNameParser.
68 //
69 static cl::list<const PassInfo*, bool, PassNameParser>
70 PassList(cl::desc("Optimizations available:"));
71 
72 static cl::opt<bool> EnableNewPassManager(
73     "enable-new-pm", cl::desc("Enable the new pass manager"), cl::init(false));
74 
75 // This flag specifies a textual description of the optimization pass pipeline
76 // to run over the module. This flag switches opt to use the new pass manager
77 // infrastructure, completely disabling all of the flags specific to the old
78 // pass management.
79 static cl::opt<std::string> PassPipeline(
80     "passes",
81     cl::desc("A textual description of the pass pipeline for optimizing"),
82     cl::Hidden);
83 
84 // Other command line options...
85 //
86 static cl::opt<std::string>
87 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
88     cl::init("-"), cl::value_desc("filename"));
89 
90 static cl::opt<std::string>
91 OutputFilename("o", cl::desc("Override output filename"),
92                cl::value_desc("filename"));
93 
94 static cl::opt<bool>
95 Force("f", cl::desc("Enable binary output on terminals"));
96 
97 static cl::opt<bool>
98 PrintEachXForm("p", cl::desc("Print module after each transformation"));
99 
100 static cl::opt<bool>
101 NoOutput("disable-output",
102          cl::desc("Do not write result bitcode file"), cl::Hidden);
103 
104 static cl::opt<bool>
105 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
106 
107 static cl::opt<bool>
108     OutputThinLTOBC("thinlto-bc",
109                     cl::desc("Write output as ThinLTO-ready bitcode"));
110 
111 static cl::opt<bool>
112     SplitLTOUnit("thinlto-split-lto-unit",
113                  cl::desc("Enable splitting of a ThinLTO LTOUnit"));
114 
115 static cl::opt<std::string> ThinLinkBitcodeFile(
116     "thin-link-bitcode-file", cl::value_desc("filename"),
117     cl::desc(
118         "A file in which to write minimized bitcode for the thin link only"));
119 
120 static cl::opt<bool>
121 NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
122 
123 static cl::opt<bool> NoUpgradeDebugInfo("disable-upgrade-debug-info",
124                                         cl::desc("Generate invalid output"),
125                                         cl::ReallyHidden);
126 
127 static cl::opt<bool> VerifyEach("verify-each",
128                                 cl::desc("Verify after each transform"));
129 
130 static cl::opt<bool>
131     DisableDITypeMap("disable-debug-info-type-map",
132                      cl::desc("Don't use a uniquing type map for debug info"));
133 
134 static cl::opt<bool>
135 StripDebug("strip-debug",
136            cl::desc("Strip debugger symbol info from translation unit"));
137 
138 static cl::opt<bool>
139     StripNamedMetadata("strip-named-metadata",
140                        cl::desc("Strip module-level named metadata"));
141 
142 static cl::opt<bool> DisableInline("disable-inlining",
143                                    cl::desc("Do not run the inliner pass"));
144 
145 static cl::opt<bool>
146 DisableOptimizations("disable-opt",
147                      cl::desc("Do not run any optimization passes"));
148 
149 static cl::opt<bool>
150 StandardLinkOpts("std-link-opts",
151                  cl::desc("Include the standard link time optimizations"));
152 
153 static cl::opt<bool>
154 OptLevelO0("O0",
155   cl::desc("Optimization level 0. Similar to clang -O0"));
156 
157 static cl::opt<bool>
158 OptLevelO1("O1",
159            cl::desc("Optimization level 1. Similar to clang -O1"));
160 
161 static cl::opt<bool>
162 OptLevelO2("O2",
163            cl::desc("Optimization level 2. Similar to clang -O2"));
164 
165 static cl::opt<bool>
166 OptLevelOs("Os",
167            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
168 
169 static cl::opt<bool>
170 OptLevelOz("Oz",
171            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
172 
173 static cl::opt<bool>
174 OptLevelO3("O3",
175            cl::desc("Optimization level 3. Similar to clang -O3"));
176 
177 static cl::opt<unsigned>
178 CodeGenOptLevel("codegen-opt-level",
179                 cl::desc("Override optimization level for codegen hooks"));
180 
181 static cl::opt<std::string>
182 TargetTriple("mtriple", cl::desc("Override target triple for module"));
183 
184 cl::opt<bool> DisableLoopUnrolling(
185     "disable-loop-unrolling",
186     cl::desc("Disable loop unrolling in all relevant passes"), cl::init(false));
187 
188 static cl::opt<bool> EmitSummaryIndex("module-summary",
189                                       cl::desc("Emit module summary index"),
190                                       cl::init(false));
191 
192 static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
193                                     cl::init(false));
194 
195 static cl::opt<bool>
196 DisableSimplifyLibCalls("disable-simplify-libcalls",
197                         cl::desc("Disable simplify-libcalls"));
198 
199 static cl::list<std::string>
200 DisableBuiltins("disable-builtin",
201                 cl::desc("Disable specific target library builtin function"),
202                 cl::ZeroOrMore);
203 
204 static cl::opt<bool>
205 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
206 
207 static cl::opt<bool> EnableDebugify(
208     "enable-debugify",
209     cl::desc(
210         "Start the pipeline with debugify and end it with check-debugify"));
211 
212 static cl::opt<bool> DebugifyEach(
213     "debugify-each",
214     cl::desc(
215         "Start each pass with debugify and end it with check-debugify"));
216 
217 static cl::opt<std::string>
218     DebugifyExport("debugify-export",
219                    cl::desc("Export per-pass debugify statistics to this file"),
220                    cl::value_desc("filename"), cl::init(""));
221 
222 static cl::opt<bool>
223 PrintBreakpoints("print-breakpoints-for-testing",
224                  cl::desc("Print select breakpoints location for testing"));
225 
226 static cl::opt<std::string> ClDataLayout("data-layout",
227                                          cl::desc("data layout string to use"),
228                                          cl::value_desc("layout-string"),
229                                          cl::init(""));
230 
231 static cl::opt<bool> PreserveBitcodeUseListOrder(
232     "preserve-bc-uselistorder",
233     cl::desc("Preserve use-list order when writing LLVM bitcode."),
234     cl::init(true), cl::Hidden);
235 
236 static cl::opt<bool> PreserveAssemblyUseListOrder(
237     "preserve-ll-uselistorder",
238     cl::desc("Preserve use-list order when writing LLVM assembly."),
239     cl::init(false), cl::Hidden);
240 
241 static cl::opt<bool>
242     RunTwice("run-twice",
243              cl::desc("Run all passes twice, re-using the same pass manager."),
244              cl::init(false), cl::Hidden);
245 
246 static cl::opt<bool> DiscardValueNames(
247     "discard-value-names",
248     cl::desc("Discard names from Value (other than GlobalValue)."),
249     cl::init(false), cl::Hidden);
250 
251 static cl::opt<bool> Coroutines(
252   "enable-coroutines",
253   cl::desc("Enable coroutine passes."),
254   cl::init(false), cl::Hidden);
255 
256 static cl::opt<bool> TimeTrace(
257     "time-trace",
258     cl::desc("Record time trace"));
259 
260 static cl::opt<unsigned> TimeTraceGranularity(
261     "time-trace-granularity",
262     cl::desc("Minimum time granularity (in microseconds) traced by time profiler"),
263     cl::init(500), cl::Hidden);
264 
265 static cl::opt<std::string>
266     TimeTraceFile("time-trace-file",
267                     cl::desc("Specify time trace file destination"),
268                     cl::value_desc("filename"));
269 
270 static cl::opt<bool> RemarksWithHotness(
271     "pass-remarks-with-hotness",
272     cl::desc("With PGO, include profile count in optimization remarks"),
273     cl::Hidden);
274 
275 static cl::opt<unsigned>
276     RemarksHotnessThreshold("pass-remarks-hotness-threshold",
277                             cl::desc("Minimum profile count required for "
278                                      "an optimization remark to be output"),
279                             cl::Hidden);
280 
281 static cl::opt<std::string>
282     RemarksFilename("pass-remarks-output",
283                     cl::desc("Output filename for pass remarks"),
284                     cl::value_desc("filename"));
285 
286 static cl::opt<std::string>
287     RemarksPasses("pass-remarks-filter",
288                   cl::desc("Only record optimization remarks from passes whose "
289                            "names match the given regular expression"),
290                   cl::value_desc("regex"));
291 
292 static cl::opt<std::string> RemarksFormat(
293     "pass-remarks-format",
294     cl::desc("The format used for serializing remarks (default: YAML)"),
295     cl::value_desc("format"), cl::init("yaml"));
296 
297 cl::opt<PGOKind>
298     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
299                 cl::desc("The kind of profile guided optimization"),
300                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
301                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
302                                       "Instrument the IR to generate profile."),
303                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
304                                       "Use instrumented profile to guide PGO."),
305                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
306                                       "Use sampled profile to guide PGO.")));
307 cl::opt<std::string> ProfileFile("profile-file",
308                                  cl::desc("Path to the profile."), cl::Hidden);
309 
310 cl::opt<CSPGOKind> CSPGOKindFlag(
311     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
312     cl::desc("The kind of context sensitive profile guided optimization"),
313     cl::values(
314         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
315         clEnumValN(
316             CSInstrGen, "cspgo-instr-gen-pipeline",
317             "Instrument (context sensitive) the IR to generate profile."),
318         clEnumValN(
319             CSInstrUse, "cspgo-instr-use-pipeline",
320             "Use instrumented (context sensitive) profile to guide PGO.")));
321 cl::opt<std::string> CSProfileGenFile(
322     "cs-profilegen-file",
323     cl::desc("Path to the instrumented context sensitive profile."),
324     cl::Hidden);
325 
326 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
327   // Add the pass to the pass manager...
328   PM.add(P);
329 
330   // If we are verifying all of the intermediate steps, add the verifier...
331   if (VerifyEach)
332     PM.add(createVerifierPass());
333 }
334 
335 /// This routine adds optimization passes based on selected optimization level,
336 /// OptLevel.
337 ///
338 /// OptLevel - Optimization Level
339 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
340                                   legacy::FunctionPassManager &FPM,
341                                   TargetMachine *TM, unsigned OptLevel,
342                                   unsigned SizeLevel) {
343   if (!NoVerify || VerifyEach)
344     FPM.add(createVerifierPass()); // Verify that input is correct
345 
346   PassManagerBuilder Builder;
347   Builder.OptLevel = OptLevel;
348   Builder.SizeLevel = SizeLevel;
349 
350   if (DisableInline) {
351     // No inlining pass
352   } else if (OptLevel > 1) {
353     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
354   } else {
355     Builder.Inliner = createAlwaysInlinerLegacyPass();
356   }
357   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
358                                DisableLoopUnrolling : OptLevel == 0;
359 
360   Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
361 
362   Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2;
363 
364   if (TM)
365     TM->adjustPassManager(Builder);
366 
367   if (Coroutines)
368     addCoroutinePassesToExtensionPoints(Builder);
369 
370   switch (PGOKindFlag) {
371   case InstrGen:
372     Builder.EnablePGOInstrGen = true;
373     Builder.PGOInstrGen = ProfileFile;
374     break;
375   case InstrUse:
376     Builder.PGOInstrUse = ProfileFile;
377     break;
378   case SampleUse:
379     Builder.PGOSampleUse = ProfileFile;
380     break;
381   default:
382     break;
383   }
384 
385   switch (CSPGOKindFlag) {
386   case CSInstrGen:
387     Builder.EnablePGOCSInstrGen = true;
388     break;
389   case CSInstrUse:
390     Builder.EnablePGOCSInstrUse = true;
391     break;
392   default:
393     break;
394   }
395 
396   Builder.populateFunctionPassManager(FPM);
397   Builder.populateModulePassManager(MPM);
398 }
399 
400 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
401   PassManagerBuilder Builder;
402   Builder.VerifyInput = true;
403   if (DisableOptimizations)
404     Builder.OptLevel = 0;
405 
406   if (!DisableInline)
407     Builder.Inliner = createFunctionInliningPass();
408   Builder.populateLTOPassManager(PM);
409 }
410 
411 //===----------------------------------------------------------------------===//
412 // CodeGen-related helper functions.
413 //
414 
415 static CodeGenOpt::Level GetCodeGenOptLevel() {
416   if (CodeGenOptLevel.getNumOccurrences())
417     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
418   if (OptLevelO1)
419     return CodeGenOpt::Less;
420   if (OptLevelO2)
421     return CodeGenOpt::Default;
422   if (OptLevelO3)
423     return CodeGenOpt::Aggressive;
424   return CodeGenOpt::None;
425 }
426 
427 // Returns the TargetMachine instance or zero if no triple is provided.
428 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
429                                        StringRef FeaturesStr,
430                                        const TargetOptions &Options) {
431   std::string Error;
432   const Target *TheTarget =
433       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
434   // Some modules don't specify a triple, and this is okay.
435   if (!TheTarget) {
436     return nullptr;
437   }
438 
439   return TheTarget->createTargetMachine(
440       TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
441       Options, codegen::getExplicitRelocModel(),
442       codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
443 }
444 
445 #ifdef BUILD_EXAMPLES
446 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
447 #endif
448 
449 
450 void exportDebugifyStats(llvm::StringRef Path, const DebugifyStatsMap &Map) {
451   std::error_code EC;
452   raw_fd_ostream OS{Path, EC};
453   if (EC) {
454     errs() << "Could not open file: " << EC.message() << ", " << Path << '\n';
455     return;
456   }
457 
458   OS << "Pass Name" << ',' << "# of missing debug values" << ','
459      << "# of missing locations" << ',' << "Missing/Expected value ratio" << ','
460      << "Missing/Expected location ratio" << '\n';
461   for (const auto &Entry : Map) {
462     StringRef Pass = Entry.first;
463     DebugifyStatistics Stats = Entry.second;
464 
465     OS << Pass << ',' << Stats.NumDbgValuesMissing << ','
466        << Stats.NumDbgLocsMissing << ',' << Stats.getMissingValueRatio() << ','
467        << Stats.getEmptyLocationRatio() << '\n';
468   }
469 }
470 
471 struct TimeTracerRAII {
472   TimeTracerRAII(StringRef ProgramName) {
473     if (TimeTrace)
474       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
475   }
476   ~TimeTracerRAII() {
477     if (TimeTrace) {
478       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
479         handleAllErrors(std::move(E), [&](const StringError &SE) {
480           errs() << SE.getMessage() << "\n";
481         });
482         return;
483       }
484       timeTraceProfilerCleanup();
485     }
486   }
487 };
488 
489 //===----------------------------------------------------------------------===//
490 // main for opt
491 //
492 int main(int argc, char **argv) {
493   InitLLVM X(argc, argv);
494 
495   // Enable debug stream buffering.
496   EnableDebugBuffering = true;
497 
498   LLVMContext Context;
499 
500   InitializeAllTargets();
501   InitializeAllTargetMCs();
502   InitializeAllAsmPrinters();
503   InitializeAllAsmParsers();
504 
505   // Initialize passes
506   PassRegistry &Registry = *PassRegistry::getPassRegistry();
507   initializeCore(Registry);
508   initializeCoroutines(Registry);
509   initializeScalarOpts(Registry);
510   initializeObjCARCOpts(Registry);
511   initializeVectorization(Registry);
512   initializeIPO(Registry);
513   initializeAnalysis(Registry);
514   initializeTransformUtils(Registry);
515   initializeInstCombine(Registry);
516   initializeAggressiveInstCombine(Registry);
517   initializeInstrumentation(Registry);
518   initializeTarget(Registry);
519   // For codegen passes, only passes that do IR to IR transformation are
520   // supported.
521   initializeExpandMemCmpPassPass(Registry);
522   initializeScalarizeMaskedMemIntrinPass(Registry);
523   initializeCodeGenPreparePass(Registry);
524   initializeAtomicExpandPass(Registry);
525   initializeRewriteSymbolsLegacyPassPass(Registry);
526   initializeWinEHPreparePass(Registry);
527   initializeDwarfEHPreparePass(Registry);
528   initializeSafeStackLegacyPassPass(Registry);
529   initializeSjLjEHPreparePass(Registry);
530   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
531   initializeGlobalMergePass(Registry);
532   initializeIndirectBrExpandPassPass(Registry);
533   initializeInterleavedLoadCombinePass(Registry);
534   initializeInterleavedAccessPass(Registry);
535   initializeEntryExitInstrumenterPass(Registry);
536   initializePostInlineEntryExitInstrumenterPass(Registry);
537   initializeUnreachableBlockElimLegacyPassPass(Registry);
538   initializeExpandReductionsPass(Registry);
539   initializeWasmEHPreparePass(Registry);
540   initializeWriteBitcodePassPass(Registry);
541   initializeHardwareLoopsPass(Registry);
542   initializeTypePromotionPass(Registry);
543 
544 #ifdef BUILD_EXAMPLES
545   initializeExampleIRTransforms(Registry);
546 #endif
547 
548   cl::ParseCommandLineOptions(argc, argv,
549     "llvm .bc -> .bc modular optimizer and analysis printer\n");
550 
551   if (AnalyzeOnly && NoOutput) {
552     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
553     return 1;
554   }
555 
556   TimeTracerRAII TimeTracer(argv[0]);
557 
558   SMDiagnostic Err;
559 
560   Context.setDiscardValueNames(DiscardValueNames);
561   if (!DisableDITypeMap)
562     Context.enableDebugTypeODRUniquing();
563 
564   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
565       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
566                                    RemarksFormat, RemarksWithHotness,
567                                    RemarksHotnessThreshold);
568   if (Error E = RemarksFileOrErr.takeError()) {
569     errs() << toString(std::move(E)) << '\n';
570     return 1;
571   }
572   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
573 
574   // Load the input module...
575   auto SetDataLayout = [](StringRef) -> Optional<std::string> {
576     if (ClDataLayout.empty())
577       return None;
578     return ClDataLayout;
579   };
580   std::unique_ptr<Module> M;
581   if (NoUpgradeDebugInfo)
582     M = parseAssemblyFileWithIndexNoUpgradeDebugInfo(
583             InputFilename, Err, Context, nullptr, SetDataLayout)
584             .Mod;
585   else
586     M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
587 
588   if (!M) {
589     Err.print(argv[0], errs());
590     return 1;
591   }
592 
593   // Strip debug info before running the verifier.
594   if (StripDebug)
595     StripDebugInfo(*M);
596 
597   // Erase module-level named metadata, if requested.
598   if (StripNamedMetadata) {
599     while (!M->named_metadata_empty()) {
600       NamedMDNode *NMD = &*M->named_metadata_begin();
601       M->eraseNamedMetadata(NMD);
602     }
603   }
604 
605   // If we are supposed to override the target triple or data layout, do so now.
606   if (!TargetTriple.empty())
607     M->setTargetTriple(Triple::normalize(TargetTriple));
608 
609   // Immediately run the verifier to catch any problems before starting up the
610   // pass pipelines.  Otherwise we can crash on broken code during
611   // doInitialization().
612   if (!NoVerify && verifyModule(*M, &errs())) {
613     errs() << argv[0] << ": " << InputFilename
614            << ": error: input module is broken!\n";
615     return 1;
616   }
617 
618   // Enable testing of whole program devirtualization on this module by invoking
619   // the facility for updating public visibility to linkage unit visibility when
620   // specified by an internal option. This is normally done during LTO which is
621   // not performed via opt.
622   updateVCallVisibilityInModule(*M,
623                                 /* WholeProgramVisibilityEnabledInLTO */ false);
624 
625   // Figure out what stream we are supposed to write to...
626   std::unique_ptr<ToolOutputFile> Out;
627   std::unique_ptr<ToolOutputFile> ThinLinkOut;
628   if (NoOutput) {
629     if (!OutputFilename.empty())
630       errs() << "WARNING: The -o (output filename) option is ignored when\n"
631                 "the --disable-output option is used.\n";
632   } else {
633     // Default to standard output.
634     if (OutputFilename.empty())
635       OutputFilename = "-";
636 
637     std::error_code EC;
638     sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text
639                                               : sys::fs::OF_None;
640     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
641     if (EC) {
642       errs() << EC.message() << '\n';
643       return 1;
644     }
645 
646     if (!ThinLinkBitcodeFile.empty()) {
647       ThinLinkOut.reset(
648           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
649       if (EC) {
650         errs() << EC.message() << '\n';
651         return 1;
652       }
653     }
654   }
655 
656   Triple ModuleTriple(M->getTargetTriple());
657   std::string CPUStr, FeaturesStr;
658   TargetMachine *Machine = nullptr;
659   const TargetOptions Options = codegen::InitTargetOptionsFromCodeGenFlags();
660 
661   if (ModuleTriple.getArch()) {
662     CPUStr = codegen::getCPUStr();
663     FeaturesStr = codegen::getFeaturesStr();
664     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
665   } else if (ModuleTriple.getArchName() != "unknown" &&
666              ModuleTriple.getArchName() != "") {
667     errs() << argv[0] << ": unrecognized architecture '"
668            << ModuleTriple.getArchName() << "' provided.\n";
669     return 1;
670   }
671 
672   std::unique_ptr<TargetMachine> TM(Machine);
673 
674   // Override function attributes based on CPUStr, FeaturesStr, and command line
675   // flags.
676   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
677 
678   // If the output is set to be emitted to standard out, and standard out is a
679   // console, print out a warning message and refuse to do it.  We don't
680   // impress anyone by spewing tons of binary goo to a terminal.
681   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
682     if (CheckBitcodeOutputToConsole(Out->os()))
683       NoOutput = true;
684 
685   if (OutputThinLTOBC)
686     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
687 
688   if (EnableNewPassManager || PassPipeline.getNumOccurrences() > 0) {
689     if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) {
690       errs()
691           << "Cannot specify passes via both -foo-pass and --passes=foo-pass";
692       return 1;
693     }
694     SmallVector<StringRef, 4> Passes;
695     for (const auto &P : PassList) {
696       Passes.push_back(P->getPassArgument());
697     }
698     if (OptLevelO0)
699       Passes.push_back("default<O0>");
700     if (OptLevelO1)
701       Passes.push_back("default<O1>");
702     if (OptLevelO2)
703       Passes.push_back("default<O2>");
704     if (OptLevelO3)
705       Passes.push_back("default<O3>");
706     if (OptLevelOs)
707       Passes.push_back("default<Os>");
708     if (OptLevelOz)
709       Passes.push_back("default<Oz>");
710     OutputKind OK = OK_NoOutput;
711     if (!NoOutput)
712       OK = OutputAssembly
713                ? OK_OutputAssembly
714                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
715 
716     VerifierKind VK = VK_VerifyInAndOut;
717     if (NoVerify)
718       VK = VK_NoVerifier;
719     else if (VerifyEach)
720       VK = VK_VerifyEachPass;
721 
722     // The user has asked to use the new pass manager and provided a pipeline
723     // string. Hand off the rest of the functionality to the new code for that
724     // layer.
725     return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
726                            RemarksFile.get(), PassPipeline, Passes, OK, VK,
727                            PreserveAssemblyUseListOrder,
728                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
729                            EmitModuleHash, EnableDebugify, Coroutines)
730                ? 0
731                : 1;
732   }
733 
734   // Create a PassManager to hold and optimize the collection of passes we are
735   // about to build. If the -debugify-each option is set, wrap each pass with
736   // the (-check)-debugify passes.
737   DebugifyCustomPassManager Passes;
738   if (DebugifyEach)
739     Passes.enableDebugifyEach();
740 
741   bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
742 
743   // Add an appropriate TargetLibraryInfo pass for the module's triple.
744   TargetLibraryInfoImpl TLII(ModuleTriple);
745 
746   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
747   if (DisableSimplifyLibCalls)
748     TLII.disableAllFunctions();
749   else {
750     // Disable individual builtin functions in TargetLibraryInfo.
751     LibFunc F;
752     for (auto &FuncName : DisableBuiltins)
753       if (TLII.getLibFunc(FuncName, F))
754         TLII.setUnavailable(F);
755       else {
756         errs() << argv[0] << ": cannot disable nonexistent builtin function "
757                << FuncName << '\n';
758         return 1;
759       }
760   }
761 
762   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
763 
764   // Add internal analysis passes from the target machine.
765   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
766                                                      : TargetIRAnalysis()));
767 
768   if (AddOneTimeDebugifyPasses)
769     Passes.add(createDebugifyModulePass());
770 
771   std::unique_ptr<legacy::FunctionPassManager> FPasses;
772   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
773       OptLevelO3) {
774     FPasses.reset(new legacy::FunctionPassManager(M.get()));
775     FPasses->add(createTargetTransformInfoWrapperPass(
776         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
777   }
778 
779   if (PrintBreakpoints) {
780     // Default to standard output.
781     if (!Out) {
782       if (OutputFilename.empty())
783         OutputFilename = "-";
784 
785       std::error_code EC;
786       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
787                                               sys::fs::OF_None);
788       if (EC) {
789         errs() << EC.message() << '\n';
790         return 1;
791       }
792     }
793     Passes.add(createBreakpointPrinter(Out->os()));
794     NoOutput = true;
795   }
796 
797   if (TM) {
798     // FIXME: We should dyn_cast this when supported.
799     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
800     Pass *TPC = LTM.createPassConfig(Passes);
801     Passes.add(TPC);
802   }
803 
804   // Create a new optimization pass for each one specified on the command line
805   for (unsigned i = 0; i < PassList.size(); ++i) {
806     if (StandardLinkOpts &&
807         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
808       AddStandardLinkPasses(Passes);
809       StandardLinkOpts = false;
810     }
811 
812     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
813       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
814       OptLevelO0 = false;
815     }
816 
817     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
818       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
819       OptLevelO1 = false;
820     }
821 
822     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
823       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
824       OptLevelO2 = false;
825     }
826 
827     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
828       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
829       OptLevelOs = false;
830     }
831 
832     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
833       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
834       OptLevelOz = false;
835     }
836 
837     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
838       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
839       OptLevelO3 = false;
840     }
841 
842     const PassInfo *PassInf = PassList[i];
843     Pass *P = nullptr;
844     if (PassInf->getNormalCtor())
845       P = PassInf->getNormalCtor()();
846     else
847       errs() << argv[0] << ": cannot create pass: "
848              << PassInf->getPassName() << "\n";
849     if (P) {
850       PassKind Kind = P->getPassKind();
851       addPass(Passes, P);
852 
853       if (AnalyzeOnly) {
854         switch (Kind) {
855         case PT_Region:
856           Passes.add(createRegionPassPrinter(PassInf, Out->os()));
857           break;
858         case PT_Loop:
859           Passes.add(createLoopPassPrinter(PassInf, Out->os()));
860           break;
861         case PT_Function:
862           Passes.add(createFunctionPassPrinter(PassInf, Out->os()));
863           break;
864         case PT_CallGraphSCC:
865           Passes.add(createCallGraphPassPrinter(PassInf, Out->os()));
866           break;
867         default:
868           Passes.add(createModulePassPrinter(PassInf, Out->os()));
869           break;
870         }
871       }
872     }
873 
874     if (PrintEachXForm)
875       Passes.add(
876           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
877   }
878 
879   if (StandardLinkOpts) {
880     AddStandardLinkPasses(Passes);
881     StandardLinkOpts = false;
882   }
883 
884   if (OptLevelO0)
885     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
886 
887   if (OptLevelO1)
888     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
889 
890   if (OptLevelO2)
891     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
892 
893   if (OptLevelOs)
894     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
895 
896   if (OptLevelOz)
897     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
898 
899   if (OptLevelO3)
900     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
901 
902   if (FPasses) {
903     FPasses->doInitialization();
904     for (Function &F : *M)
905       FPasses->run(F);
906     FPasses->doFinalization();
907   }
908 
909   // Check that the module is well formed on completion of optimization
910   if (!NoVerify && !VerifyEach)
911     Passes.add(createVerifierPass());
912 
913   if (AddOneTimeDebugifyPasses)
914     Passes.add(createCheckDebugifyModulePass(false));
915 
916   // In run twice mode, we want to make sure the output is bit-by-bit
917   // equivalent if we run the pass manager again, so setup two buffers and
918   // a stream to write to them. Note that llc does something similar and it
919   // may be worth to abstract this out in the future.
920   SmallVector<char, 0> Buffer;
921   SmallVector<char, 0> FirstRunBuffer;
922   std::unique_ptr<raw_svector_ostream> BOS;
923   raw_ostream *OS = nullptr;
924 
925   const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly;
926 
927   // Write bitcode or assembly to the output as the last step...
928   if (ShouldEmitOutput || RunTwice) {
929     assert(Out);
930     OS = &Out->os();
931     if (RunTwice) {
932       BOS = std::make_unique<raw_svector_ostream>(Buffer);
933       OS = BOS.get();
934     }
935     if (OutputAssembly) {
936       if (EmitSummaryIndex)
937         report_fatal_error("Text output is incompatible with -module-summary");
938       if (EmitModuleHash)
939         report_fatal_error("Text output is incompatible with -module-hash");
940       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
941     } else if (OutputThinLTOBC)
942       Passes.add(createWriteThinLTOBitcodePass(
943           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
944     else
945       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
946                                          EmitSummaryIndex, EmitModuleHash));
947   }
948 
949   // Before executing passes, print the final values of the LLVM options.
950   cl::PrintOptionValues();
951 
952   if (!RunTwice) {
953     // Now that we have all of the passes ready, run them.
954     Passes.run(*M);
955   } else {
956     // If requested, run all passes twice with the same pass manager to catch
957     // bugs caused by persistent state in the passes.
958     std::unique_ptr<Module> M2(CloneModule(*M));
959     // Run all passes on the original module first, so the second run processes
960     // the clone to catch CloneModule bugs.
961     Passes.run(*M);
962     FirstRunBuffer = Buffer;
963     Buffer.clear();
964 
965     Passes.run(*M2);
966 
967     // Compare the two outputs and make sure they're the same
968     assert(Out);
969     if (Buffer.size() != FirstRunBuffer.size() ||
970         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
971       errs()
972           << "Running the pass manager twice changed the output.\n"
973              "Writing the result of the second run to the specified output.\n"
974              "To generate the one-run comparison binary, just run without\n"
975              "the compile-twice option\n";
976       if (ShouldEmitOutput) {
977         Out->os() << BOS->str();
978         Out->keep();
979       }
980       if (RemarksFile)
981         RemarksFile->keep();
982       return 1;
983     }
984     if (ShouldEmitOutput)
985       Out->os() << BOS->str();
986   }
987 
988   if (DebugifyEach && !DebugifyExport.empty())
989     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
990 
991   // Declare success.
992   if (!NoOutput || PrintBreakpoints)
993     Out->keep();
994 
995   if (RemarksFile)
996     RemarksFile->keep();
997 
998   if (ThinLinkOut)
999     ThinLinkOut->keep();
1000 
1001   return 0;
1002 }
1003