xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision c6a96df3)
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>
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> RunTwice("run-twice",
242                               cl::desc("Run all passes twice, re-using the "
243                                        "same pass manager (legacy PM only)."),
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<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
276     RemarksHotnessThreshold(
277         "pass-remarks-hotness-threshold",
278         cl::desc("Minimum profile count required for "
279                  "an optimization remark to be output. "
280                  "Use 'auto' to apply the threshold from profile summary."),
281         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
282 
283 static cl::opt<std::string>
284     RemarksFilename("pass-remarks-output",
285                     cl::desc("Output filename for pass remarks"),
286                     cl::value_desc("filename"));
287 
288 static cl::opt<std::string>
289     RemarksPasses("pass-remarks-filter",
290                   cl::desc("Only record optimization remarks from passes whose "
291                            "names match the given regular expression"),
292                   cl::value_desc("regex"));
293 
294 static cl::opt<std::string> RemarksFormat(
295     "pass-remarks-format",
296     cl::desc("The format used for serializing remarks (default: YAML)"),
297     cl::value_desc("format"), cl::init("yaml"));
298 
299 cl::opt<PGOKind>
300     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
301                 cl::desc("The kind of profile guided optimization"),
302                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
303                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
304                                       "Instrument the IR to generate profile."),
305                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
306                                       "Use instrumented profile to guide PGO."),
307                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
308                                       "Use sampled profile to guide PGO.")));
309 cl::opt<std::string> ProfileFile("profile-file",
310                                  cl::desc("Path to the profile."), cl::Hidden);
311 
312 cl::opt<CSPGOKind> CSPGOKindFlag(
313     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
314     cl::desc("The kind of context sensitive profile guided optimization"),
315     cl::values(
316         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
317         clEnumValN(
318             CSInstrGen, "cspgo-instr-gen-pipeline",
319             "Instrument (context sensitive) the IR to generate profile."),
320         clEnumValN(
321             CSInstrUse, "cspgo-instr-use-pipeline",
322             "Use instrumented (context sensitive) profile to guide PGO.")));
323 cl::opt<std::string> CSProfileGenFile(
324     "cs-profilegen-file",
325     cl::desc("Path to the instrumented context sensitive profile."),
326     cl::Hidden);
327 
328 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
329   // Add the pass to the pass manager...
330   PM.add(P);
331 
332   // If we are verifying all of the intermediate steps, add the verifier...
333   if (VerifyEach)
334     PM.add(createVerifierPass());
335 }
336 
337 /// This routine adds optimization passes based on selected optimization level,
338 /// OptLevel.
339 ///
340 /// OptLevel - Optimization Level
341 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
342                                   legacy::FunctionPassManager &FPM,
343                                   TargetMachine *TM, unsigned OptLevel,
344                                   unsigned SizeLevel) {
345   if (!NoVerify || VerifyEach)
346     FPM.add(createVerifierPass()); // Verify that input is correct
347 
348   PassManagerBuilder Builder;
349   Builder.OptLevel = OptLevel;
350   Builder.SizeLevel = SizeLevel;
351 
352   if (DisableInline) {
353     // No inlining pass
354   } else if (OptLevel > 1) {
355     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
356   } else {
357     Builder.Inliner = createAlwaysInlinerLegacyPass();
358   }
359   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
360                                DisableLoopUnrolling : OptLevel == 0;
361 
362   Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
363 
364   Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2;
365 
366   if (TM)
367     TM->adjustPassManager(Builder);
368 
369   if (Coroutines)
370     addCoroutinePassesToExtensionPoints(Builder);
371 
372   switch (PGOKindFlag) {
373   case InstrGen:
374     Builder.EnablePGOInstrGen = true;
375     Builder.PGOInstrGen = ProfileFile;
376     break;
377   case InstrUse:
378     Builder.PGOInstrUse = ProfileFile;
379     break;
380   case SampleUse:
381     Builder.PGOSampleUse = ProfileFile;
382     break;
383   default:
384     break;
385   }
386 
387   switch (CSPGOKindFlag) {
388   case CSInstrGen:
389     Builder.EnablePGOCSInstrGen = true;
390     break;
391   case CSInstrUse:
392     Builder.EnablePGOCSInstrUse = true;
393     break;
394   default:
395     break;
396   }
397 
398   Builder.populateFunctionPassManager(FPM);
399   Builder.populateModulePassManager(MPM);
400 }
401 
402 static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
403   PassManagerBuilder Builder;
404   Builder.VerifyInput = true;
405   if (DisableOptimizations)
406     Builder.OptLevel = 0;
407 
408   if (!DisableInline)
409     Builder.Inliner = createFunctionInliningPass();
410   Builder.populateLTOPassManager(PM);
411 }
412 
413 //===----------------------------------------------------------------------===//
414 // CodeGen-related helper functions.
415 //
416 
417 static CodeGenOpt::Level GetCodeGenOptLevel() {
418   if (CodeGenOptLevel.getNumOccurrences())
419     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
420   if (OptLevelO1)
421     return CodeGenOpt::Less;
422   if (OptLevelO2)
423     return CodeGenOpt::Default;
424   if (OptLevelO3)
425     return CodeGenOpt::Aggressive;
426   return CodeGenOpt::None;
427 }
428 
429 // Returns the TargetMachine instance or zero if no triple is provided.
430 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
431                                        StringRef FeaturesStr,
432                                        const TargetOptions &Options) {
433   std::string Error;
434   const Target *TheTarget =
435       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
436   // Some modules don't specify a triple, and this is okay.
437   if (!TheTarget) {
438     return nullptr;
439   }
440 
441   return TheTarget->createTargetMachine(
442       TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
443       Options, codegen::getExplicitRelocModel(),
444       codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
445 }
446 
447 #ifdef BUILD_EXAMPLES
448 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
449 #endif
450 
451 struct TimeTracerRAII {
452   TimeTracerRAII(StringRef ProgramName) {
453     if (TimeTrace)
454       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
455   }
456   ~TimeTracerRAII() {
457     if (TimeTrace) {
458       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
459         handleAllErrors(std::move(E), [&](const StringError &SE) {
460           errs() << SE.getMessage() << "\n";
461         });
462         return;
463       }
464       timeTraceProfilerCleanup();
465     }
466   }
467 };
468 
469 // For use in NPM transition. Currently this contains most codegen-specific
470 // passes. Remove passes from here when porting to the NPM.
471 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once
472 // it exists.
473 static bool shouldPinPassToLegacyPM(StringRef Pass) {
474   std::vector<StringRef> PassNameExactToIgnore = {
475       "nvvm-reflect",
476       "nvvm-intr-range",
477       "amdgpu-simplifylib",
478       "amdgpu-usenative",
479       "amdgpu-promote-alloca",
480       "amdgpu-promote-alloca-to-vector",
481       "amdgpu-lower-kernel-attributes",
482       "amdgpu-propagate-attributes-early",
483       "amdgpu-propagate-attributes-late",
484       "amdgpu-unify-metadata",
485       "amdgpu-printf-runtime-binding",
486       "amdgpu-always-inline"};
487   if (llvm::is_contained(PassNameExactToIgnore, Pass))
488     return false;
489 
490   std::vector<StringRef> PassNamePrefix = {
491       "x86-",  "xcore-", "wasm-",    "systemz-", "ppc-",    "nvvm-",   "nvptx-",
492       "mips-", "lanai-", "hexagon-", "bpf-",     "avr-",    "thumb2-", "arm-",
493       "si-",   "gcn-",   "amdgpu-",  "aarch64-", "amdgcn-", "polly-"};
494   std::vector<StringRef> PassNameContain = {"ehprepare"};
495   std::vector<StringRef> PassNameExact = {
496       "safe-stack",           "cost-model",
497       "codegenprepare",       "interleaved-load-combine",
498       "unreachableblockelim", "verify-safepoint-ir",
499       "atomic-expand",
500       "hardware-loops",       "type-promotion",
501       "mve-tail-predication", "interleaved-access",
502       "global-merge",         "pre-isel-intrinsic-lowering",
503       "expand-reductions",    "indirectbr-expand",
504       "generic-to-nvvm",      "expandmemcmp",
505       "loop-reduce",          "lower-amx-type",
506       "polyhedral-info",      "replace-with-veclib"};
507   for (const auto &P : PassNamePrefix)
508     if (Pass.startswith(P))
509       return true;
510   for (const auto &P : PassNameContain)
511     if (Pass.contains(P))
512       return true;
513   return llvm::is_contained(PassNameExact, Pass);
514 }
515 
516 // For use in NPM transition.
517 static bool shouldForceLegacyPM() {
518   for (const auto &P : PassList) {
519     StringRef Arg = P->getPassArgument();
520     if (shouldPinPassToLegacyPM(Arg))
521       return true;
522   }
523   return false;
524 }
525 
526 //===----------------------------------------------------------------------===//
527 // main for opt
528 //
529 int main(int argc, char **argv) {
530   InitLLVM X(argc, argv);
531 
532   // Enable debug stream buffering.
533   EnableDebugBuffering = true;
534 
535   LLVMContext Context;
536 
537   InitializeAllTargets();
538   InitializeAllTargetMCs();
539   InitializeAllAsmPrinters();
540   InitializeAllAsmParsers();
541 
542   // Initialize passes
543   PassRegistry &Registry = *PassRegistry::getPassRegistry();
544   initializeCore(Registry);
545   initializeCoroutines(Registry);
546   initializeScalarOpts(Registry);
547   initializeObjCARCOpts(Registry);
548   initializeVectorization(Registry);
549   initializeIPO(Registry);
550   initializeAnalysis(Registry);
551   initializeTransformUtils(Registry);
552   initializeInstCombine(Registry);
553   initializeAggressiveInstCombine(Registry);
554   initializeInstrumentation(Registry);
555   initializeTarget(Registry);
556   // For codegen passes, only passes that do IR to IR transformation are
557   // supported.
558   initializeExpandMemCmpPassPass(Registry);
559   initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry);
560   initializeCodeGenPreparePass(Registry);
561   initializeAtomicExpandPass(Registry);
562   initializeRewriteSymbolsLegacyPassPass(Registry);
563   initializeWinEHPreparePass(Registry);
564   initializeDwarfEHPrepareLegacyPassPass(Registry);
565   initializeSafeStackLegacyPassPass(Registry);
566   initializeSjLjEHPreparePass(Registry);
567   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
568   initializeGlobalMergePass(Registry);
569   initializeIndirectBrExpandPassPass(Registry);
570   initializeInterleavedLoadCombinePass(Registry);
571   initializeInterleavedAccessPass(Registry);
572   initializeEntryExitInstrumenterPass(Registry);
573   initializePostInlineEntryExitInstrumenterPass(Registry);
574   initializeUnreachableBlockElimLegacyPassPass(Registry);
575   initializeExpandReductionsPass(Registry);
576   initializeWasmEHPreparePass(Registry);
577   initializeWriteBitcodePassPass(Registry);
578   initializeHardwareLoopsPass(Registry);
579   initializeTypePromotionPass(Registry);
580   initializeReplaceWithVeclibLegacyPass(Registry);
581 
582 #ifdef BUILD_EXAMPLES
583   initializeExampleIRTransforms(Registry);
584 #endif
585 
586   cl::ParseCommandLineOptions(argc, argv,
587     "llvm .bc -> .bc modular optimizer and analysis printer\n");
588 
589   if (AnalyzeOnly && NoOutput) {
590     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
591     return 1;
592   }
593 
594   // FIXME: once the legacy PM code is deleted, move runPassPipeline() here and
595   // construct the PassBuilder before parsing IR so we can reuse the same
596   // PassBuilder for print passes.
597   if (PrintPasses) {
598     printPasses(outs());
599     return 0;
600   }
601 
602   TimeTracerRAII TimeTracer(argv[0]);
603 
604   SMDiagnostic Err;
605 
606   Context.setDiscardValueNames(DiscardValueNames);
607   if (!DisableDITypeMap)
608     Context.enableDebugTypeODRUniquing();
609 
610   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
611       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
612                                    RemarksFormat, RemarksWithHotness,
613                                    RemarksHotnessThreshold);
614   if (Error E = RemarksFileOrErr.takeError()) {
615     errs() << toString(std::move(E)) << '\n';
616     return 1;
617   }
618   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
619 
620   // Load the input module...
621   auto SetDataLayout = [](StringRef) -> Optional<std::string> {
622     if (ClDataLayout.empty())
623       return None;
624     return ClDataLayout;
625   };
626   std::unique_ptr<Module> M;
627   if (NoUpgradeDebugInfo)
628     M = parseAssemblyFileWithIndexNoUpgradeDebugInfo(
629             InputFilename, Err, Context, nullptr, SetDataLayout)
630             .Mod;
631   else
632     M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
633 
634   if (!M) {
635     Err.print(argv[0], errs());
636     return 1;
637   }
638 
639   // Strip debug info before running the verifier.
640   if (StripDebug)
641     StripDebugInfo(*M);
642 
643   // Erase module-level named metadata, if requested.
644   if (StripNamedMetadata) {
645     while (!M->named_metadata_empty()) {
646       NamedMDNode *NMD = &*M->named_metadata_begin();
647       M->eraseNamedMetadata(NMD);
648     }
649   }
650 
651   // If we are supposed to override the target triple or data layout, do so now.
652   if (!TargetTriple.empty())
653     M->setTargetTriple(Triple::normalize(TargetTriple));
654 
655   // Immediately run the verifier to catch any problems before starting up the
656   // pass pipelines.  Otherwise we can crash on broken code during
657   // doInitialization().
658   if (!NoVerify && verifyModule(*M, &errs())) {
659     errs() << argv[0] << ": " << InputFilename
660            << ": error: input module is broken!\n";
661     return 1;
662   }
663 
664   // Enable testing of whole program devirtualization on this module by invoking
665   // the facility for updating public visibility to linkage unit visibility when
666   // specified by an internal option. This is normally done during LTO which is
667   // not performed via opt.
668   updateVCallVisibilityInModule(*M,
669                                 /* WholeProgramVisibilityEnabledInLTO */ false,
670                                 /* DynamicExportSymbols */ {});
671 
672   // Figure out what stream we are supposed to write to...
673   std::unique_ptr<ToolOutputFile> Out;
674   std::unique_ptr<ToolOutputFile> ThinLinkOut;
675   if (NoOutput) {
676     if (!OutputFilename.empty())
677       errs() << "WARNING: The -o (output filename) option is ignored when\n"
678                 "the --disable-output option is used.\n";
679   } else {
680     // Default to standard output.
681     if (OutputFilename.empty())
682       OutputFilename = "-";
683 
684     std::error_code EC;
685     sys::fs::OpenFlags Flags = OutputAssembly ? sys::fs::OF_Text
686                                               : sys::fs::OF_None;
687     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
688     if (EC) {
689       errs() << EC.message() << '\n';
690       return 1;
691     }
692 
693     if (!ThinLinkBitcodeFile.empty()) {
694       ThinLinkOut.reset(
695           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
696       if (EC) {
697         errs() << EC.message() << '\n';
698         return 1;
699       }
700     }
701   }
702 
703   Triple ModuleTriple(M->getTargetTriple());
704   std::string CPUStr, FeaturesStr;
705   TargetMachine *Machine = nullptr;
706   const TargetOptions Options =
707       codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
708 
709   if (ModuleTriple.getArch()) {
710     CPUStr = codegen::getCPUStr();
711     FeaturesStr = codegen::getFeaturesStr();
712     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
713   } else if (ModuleTriple.getArchName() != "unknown" &&
714              ModuleTriple.getArchName() != "") {
715     errs() << argv[0] << ": unrecognized architecture '"
716            << ModuleTriple.getArchName() << "' provided.\n";
717     return 1;
718   }
719 
720   std::unique_ptr<TargetMachine> TM(Machine);
721 
722   // Override function attributes based on CPUStr, FeaturesStr, and command line
723   // flags.
724   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
725 
726   // If the output is set to be emitted to standard out, and standard out is a
727   // console, print out a warning message and refuse to do it.  We don't
728   // impress anyone by spewing tons of binary goo to a terminal.
729   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
730     if (CheckBitcodeOutputToConsole(Out->os()))
731       NoOutput = true;
732 
733   if (OutputThinLTOBC)
734     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
735 
736   // Add an appropriate TargetLibraryInfo pass for the module's triple.
737   TargetLibraryInfoImpl TLII(ModuleTriple);
738 
739   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
740   if (DisableSimplifyLibCalls)
741     TLII.disableAllFunctions();
742   else {
743     // Disable individual builtin functions in TargetLibraryInfo.
744     LibFunc F;
745     for (auto &FuncName : DisableBuiltins)
746       if (TLII.getLibFunc(FuncName, F))
747         TLII.setUnavailable(F);
748       else {
749         errs() << argv[0] << ": cannot disable nonexistent builtin function "
750                << FuncName << '\n';
751         return 1;
752       }
753   }
754 
755   // If `-passes=` is specified, use NPM.
756   // If `-enable-new-pm` is specified and there are no codegen passes, use NPM.
757   // e.g. `-enable-new-pm -sroa` will use NPM.
758   // but `-enable-new-pm -codegenprepare` will still revert to legacy PM.
759   if ((EnableNewPassManager && !shouldForceLegacyPM()) ||
760       PassPipeline.getNumOccurrences() > 0) {
761     if (AnalyzeOnly) {
762       errs() << "Cannot specify -analyze under new pass manager, either "
763                 "specify '-enable-new-pm=0', or use the corresponding new pass "
764                 "manager pass, e.g. '-passes=print<scalar-evolution>'. For a "
765                 "full list of passes, see the '--print-passes' flag.\n";
766       return 1;
767     }
768     if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) {
769       errs()
770           << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n";
771       return 1;
772     }
773     SmallVector<StringRef, 4> Passes;
774     if (OptLevelO0)
775       Passes.push_back("default<O0>");
776     if (OptLevelO1)
777       Passes.push_back("default<O1>");
778     if (OptLevelO2)
779       Passes.push_back("default<O2>");
780     if (OptLevelO3)
781       Passes.push_back("default<O3>");
782     if (OptLevelOs)
783       Passes.push_back("default<Os>");
784     if (OptLevelOz)
785       Passes.push_back("default<Oz>");
786     for (const auto &P : PassList)
787       Passes.push_back(P->getPassArgument());
788     OutputKind OK = OK_NoOutput;
789     if (!NoOutput)
790       OK = OutputAssembly
791                ? OK_OutputAssembly
792                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
793 
794     VerifierKind VK = VK_VerifyInAndOut;
795     if (NoVerify)
796       VK = VK_NoVerifier;
797     else if (VerifyEach)
798       VK = VK_VerifyEachPass;
799 
800     // The user has asked to use the new pass manager and provided a pipeline
801     // string. Hand off the rest of the functionality to the new code for that
802     // layer.
803     return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(),
804                            ThinLinkOut.get(), RemarksFile.get(), PassPipeline,
805                            Passes, OK, VK, PreserveAssemblyUseListOrder,
806                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
807                            EmitModuleHash, EnableDebugify, Coroutines)
808                ? 0
809                : 1;
810   }
811 
812   // Create a PassManager to hold and optimize the collection of passes we are
813   // about to build. If the -debugify-each option is set, wrap each pass with
814   // the (-check)-debugify passes.
815   DebugifyCustomPassManager Passes;
816   if (DebugifyEach)
817     Passes.enableDebugifyEach();
818 
819   bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
820 
821   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
822 
823   // Add internal analysis passes from the target machine.
824   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
825                                                      : TargetIRAnalysis()));
826 
827   if (AddOneTimeDebugifyPasses)
828     Passes.add(createDebugifyModulePass());
829 
830   std::unique_ptr<legacy::FunctionPassManager> FPasses;
831   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
832       OptLevelO3) {
833     FPasses.reset(new legacy::FunctionPassManager(M.get()));
834     FPasses->add(createTargetTransformInfoWrapperPass(
835         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
836   }
837 
838   if (PrintBreakpoints) {
839     // Default to standard output.
840     if (!Out) {
841       if (OutputFilename.empty())
842         OutputFilename = "-";
843 
844       std::error_code EC;
845       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
846                                               sys::fs::OF_None);
847       if (EC) {
848         errs() << EC.message() << '\n';
849         return 1;
850       }
851     }
852     Passes.add(createBreakpointPrinter(Out->os()));
853     NoOutput = true;
854   }
855 
856   if (TM) {
857     // FIXME: We should dyn_cast this when supported.
858     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
859     Pass *TPC = LTM.createPassConfig(Passes);
860     Passes.add(TPC);
861   }
862 
863   // Create a new optimization pass for each one specified on the command line
864   for (unsigned i = 0; i < PassList.size(); ++i) {
865     if (StandardLinkOpts &&
866         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
867       AddStandardLinkPasses(Passes);
868       StandardLinkOpts = false;
869     }
870 
871     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
872       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
873       OptLevelO0 = false;
874     }
875 
876     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
877       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
878       OptLevelO1 = false;
879     }
880 
881     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
882       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
883       OptLevelO2 = false;
884     }
885 
886     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
887       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
888       OptLevelOs = false;
889     }
890 
891     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
892       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
893       OptLevelOz = false;
894     }
895 
896     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
897       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
898       OptLevelO3 = false;
899     }
900 
901     const PassInfo *PassInf = PassList[i];
902     Pass *P = nullptr;
903     if (PassInf->getNormalCtor())
904       P = PassInf->getNormalCtor()();
905     else
906       errs() << argv[0] << ": cannot create pass: "
907              << PassInf->getPassName() << "\n";
908     if (P) {
909       PassKind Kind = P->getPassKind();
910       addPass(Passes, P);
911 
912       if (AnalyzeOnly) {
913         switch (Kind) {
914         case PT_Region:
915           Passes.add(createRegionPassPrinter(PassInf, Out->os()));
916           break;
917         case PT_Loop:
918           Passes.add(createLoopPassPrinter(PassInf, Out->os()));
919           break;
920         case PT_Function:
921           Passes.add(createFunctionPassPrinter(PassInf, Out->os()));
922           break;
923         case PT_CallGraphSCC:
924           Passes.add(createCallGraphPassPrinter(PassInf, Out->os()));
925           break;
926         default:
927           Passes.add(createModulePassPrinter(PassInf, Out->os()));
928           break;
929         }
930       }
931     }
932 
933     if (PrintEachXForm)
934       Passes.add(
935           createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
936   }
937 
938   if (StandardLinkOpts) {
939     AddStandardLinkPasses(Passes);
940     StandardLinkOpts = false;
941   }
942 
943   if (OptLevelO0)
944     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
945 
946   if (OptLevelO1)
947     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
948 
949   if (OptLevelO2)
950     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
951 
952   if (OptLevelOs)
953     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
954 
955   if (OptLevelOz)
956     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
957 
958   if (OptLevelO3)
959     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
960 
961   if (FPasses) {
962     FPasses->doInitialization();
963     for (Function &F : *M)
964       FPasses->run(F);
965     FPasses->doFinalization();
966   }
967 
968   // Check that the module is well formed on completion of optimization
969   if (!NoVerify && !VerifyEach)
970     Passes.add(createVerifierPass());
971 
972   if (AddOneTimeDebugifyPasses)
973     Passes.add(createCheckDebugifyModulePass(false));
974 
975   // In run twice mode, we want to make sure the output is bit-by-bit
976   // equivalent if we run the pass manager again, so setup two buffers and
977   // a stream to write to them. Note that llc does something similar and it
978   // may be worth to abstract this out in the future.
979   SmallVector<char, 0> Buffer;
980   SmallVector<char, 0> FirstRunBuffer;
981   std::unique_ptr<raw_svector_ostream> BOS;
982   raw_ostream *OS = nullptr;
983 
984   const bool ShouldEmitOutput = !NoOutput && !AnalyzeOnly;
985 
986   // Write bitcode or assembly to the output as the last step...
987   if (ShouldEmitOutput || RunTwice) {
988     assert(Out);
989     OS = &Out->os();
990     if (RunTwice) {
991       BOS = std::make_unique<raw_svector_ostream>(Buffer);
992       OS = BOS.get();
993     }
994     if (OutputAssembly) {
995       if (EmitSummaryIndex)
996         report_fatal_error("Text output is incompatible with -module-summary");
997       if (EmitModuleHash)
998         report_fatal_error("Text output is incompatible with -module-hash");
999       Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
1000     } else if (OutputThinLTOBC)
1001       Passes.add(createWriteThinLTOBitcodePass(
1002           *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
1003     else
1004       Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
1005                                          EmitSummaryIndex, EmitModuleHash));
1006   }
1007 
1008   // Before executing passes, print the final values of the LLVM options.
1009   cl::PrintOptionValues();
1010 
1011   if (!RunTwice) {
1012     // Now that we have all of the passes ready, run them.
1013     Passes.run(*M);
1014   } else {
1015     // If requested, run all passes twice with the same pass manager to catch
1016     // bugs caused by persistent state in the passes.
1017     std::unique_ptr<Module> M2(CloneModule(*M));
1018     // Run all passes on the original module first, so the second run processes
1019     // the clone to catch CloneModule bugs.
1020     Passes.run(*M);
1021     FirstRunBuffer = Buffer;
1022     Buffer.clear();
1023 
1024     Passes.run(*M2);
1025 
1026     // Compare the two outputs and make sure they're the same
1027     assert(Out);
1028     if (Buffer.size() != FirstRunBuffer.size() ||
1029         (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
1030       errs()
1031           << "Running the pass manager twice changed the output.\n"
1032              "Writing the result of the second run to the specified output.\n"
1033              "To generate the one-run comparison binary, just run without\n"
1034              "the compile-twice option\n";
1035       if (ShouldEmitOutput) {
1036         Out->os() << BOS->str();
1037         Out->keep();
1038       }
1039       if (RemarksFile)
1040         RemarksFile->keep();
1041       return 1;
1042     }
1043     if (ShouldEmitOutput)
1044       Out->os() << BOS->str();
1045   }
1046 
1047   if (DebugifyEach && !DebugifyExport.empty())
1048     exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
1049 
1050   // Declare success.
1051   if (!NoOutput || PrintBreakpoints)
1052     Out->keep();
1053 
1054   if (RemarksFile)
1055     RemarksFile->keep();
1056 
1057   if (ThinLinkOut)
1058     ThinLinkOut->keep();
1059 
1060   return 0;
1061 }
1062