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