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