xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision cd2e36ea)
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 "llvm/ADT/Triple.h"
17 #include "llvm/Analysis/CallGraph.h"
18 #include "llvm/Analysis/CallGraphSCCPass.h"
19 #include "llvm/Analysis/LoopPass.h"
20 #include "llvm/Analysis/RegionPass.h"
21 #include "llvm/Analysis/TargetLibraryInfo.h"
22 #include "llvm/Analysis/TargetTransformInfo.h"
23 #include "llvm/AsmParser/Parser.h"
24 #include "llvm/CodeGen/CommandFlags.h"
25 #include "llvm/CodeGen/TargetPassConfig.h"
26 #include "llvm/Config/llvm-config.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DebugInfo.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/IR/LLVMRemarkStreamer.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/LegacyPassNameParser.h"
33 #include "llvm/IR/Module.h"
34 #include "llvm/IR/ModuleSummaryIndex.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/Passes/PassPlugin.h"
43 #include "llvm/Remarks/HotnessThresholdParser.h"
44 #include "llvm/Support/Debug.h"
45 #include "llvm/Support/FileSystem.h"
46 #include "llvm/Support/Host.h"
47 #include "llvm/Support/InitLLVM.h"
48 #include "llvm/Support/PluginLoader.h"
49 #include "llvm/Support/SourceMgr.h"
50 #include "llvm/Support/SystemUtils.h"
51 #include "llvm/Support/TargetSelect.h"
52 #include "llvm/Support/ToolOutputFile.h"
53 #include "llvm/Support/YAMLTraits.h"
54 #include "llvm/Target/TargetMachine.h"
55 #include "llvm/Transforms/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(true));
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> DisableBuiltins(
196     "disable-builtin",
197     cl::desc("Disable specific target library builtin function"));
198 
199 static cl::opt<bool> EnableDebugify(
200     "enable-debugify",
201     cl::desc(
202         "Start the pipeline with debugify and end it with check-debugify"));
203 
204 static cl::opt<bool> VerifyDebugInfoPreserve(
205     "verify-debuginfo-preserve",
206     cl::desc("Start the pipeline with collecting and end it with checking of "
207              "debug info preservation."));
208 
209 static cl::opt<bool>
210 PrintBreakpoints("print-breakpoints-for-testing",
211                  cl::desc("Print select breakpoints location for testing"));
212 
213 static cl::opt<std::string> ClDataLayout("data-layout",
214                                          cl::desc("data layout string to use"),
215                                          cl::value_desc("layout-string"),
216                                          cl::init(""));
217 
218 static cl::opt<bool> PreserveBitcodeUseListOrder(
219     "preserve-bc-uselistorder",
220     cl::desc("Preserve use-list order when writing LLVM bitcode."),
221     cl::init(true), cl::Hidden);
222 
223 static cl::opt<bool> PreserveAssemblyUseListOrder(
224     "preserve-ll-uselistorder",
225     cl::desc("Preserve use-list order when writing LLVM assembly."),
226     cl::init(false), cl::Hidden);
227 
228 static cl::opt<bool> RunTwice("run-twice",
229                               cl::desc("Run all passes twice, re-using the "
230                                        "same pass manager (legacy PM only)."),
231                               cl::init(false), cl::Hidden);
232 
233 static cl::opt<bool> DiscardValueNames(
234     "discard-value-names",
235     cl::desc("Discard names from Value (other than GlobalValue)."),
236     cl::init(false), cl::Hidden);
237 
238 static cl::opt<bool> TimeTrace(
239     "time-trace",
240     cl::desc("Record time trace"));
241 
242 static cl::opt<unsigned> TimeTraceGranularity(
243     "time-trace-granularity",
244     cl::desc("Minimum time granularity (in microseconds) traced by time profiler"),
245     cl::init(500), cl::Hidden);
246 
247 static cl::opt<std::string>
248     TimeTraceFile("time-trace-file",
249                     cl::desc("Specify time trace file destination"),
250                     cl::value_desc("filename"));
251 
252 static cl::opt<bool> RemarksWithHotness(
253     "pass-remarks-with-hotness",
254     cl::desc("With PGO, include profile count in optimization remarks"),
255     cl::Hidden);
256 
257 static cl::opt<Optional<uint64_t>, false, remarks::HotnessThresholdParser>
258     RemarksHotnessThreshold(
259         "pass-remarks-hotness-threshold",
260         cl::desc("Minimum profile count required for "
261                  "an optimization remark to be output. "
262                  "Use 'auto' to apply the threshold from profile summary."),
263         cl::value_desc("N or 'auto'"), cl::init(0), cl::Hidden);
264 
265 static cl::opt<std::string>
266     RemarksFilename("pass-remarks-output",
267                     cl::desc("Output filename for pass remarks"),
268                     cl::value_desc("filename"));
269 
270 static cl::opt<std::string>
271     RemarksPasses("pass-remarks-filter",
272                   cl::desc("Only record optimization remarks from passes whose "
273                            "names match the given regular expression"),
274                   cl::value_desc("regex"));
275 
276 static cl::opt<std::string> RemarksFormat(
277     "pass-remarks-format",
278     cl::desc("The format used for serializing remarks (default: YAML)"),
279     cl::value_desc("format"), cl::init("yaml"));
280 
281 static cl::list<std::string>
282     PassPlugins("load-pass-plugin",
283                 cl::desc("Load passes from plugin library"));
284 
285 namespace llvm {
286 cl::opt<PGOKind>
287     PGOKindFlag("pgo-kind", cl::init(NoPGO), cl::Hidden,
288                 cl::desc("The kind of profile guided optimization"),
289                 cl::values(clEnumValN(NoPGO, "nopgo", "Do not use PGO."),
290                            clEnumValN(InstrGen, "pgo-instr-gen-pipeline",
291                                       "Instrument the IR to generate profile."),
292                            clEnumValN(InstrUse, "pgo-instr-use-pipeline",
293                                       "Use instrumented profile to guide PGO."),
294                            clEnumValN(SampleUse, "pgo-sample-use-pipeline",
295                                       "Use sampled profile to guide PGO.")));
296 cl::opt<std::string> ProfileFile("profile-file",
297                                  cl::desc("Path to the profile."), cl::Hidden);
298 
299 cl::opt<CSPGOKind> CSPGOKindFlag(
300     "cspgo-kind", cl::init(NoCSPGO), cl::Hidden,
301     cl::desc("The kind of context sensitive profile guided optimization"),
302     cl::values(
303         clEnumValN(NoCSPGO, "nocspgo", "Do not use CSPGO."),
304         clEnumValN(
305             CSInstrGen, "cspgo-instr-gen-pipeline",
306             "Instrument (context sensitive) the IR to generate profile."),
307         clEnumValN(
308             CSInstrUse, "cspgo-instr-use-pipeline",
309             "Use instrumented (context sensitive) profile to guide PGO.")));
310 cl::opt<std::string> CSProfileGenFile(
311     "cs-profilegen-file",
312     cl::desc("Path to the instrumented context sensitive profile."),
313     cl::Hidden);
314 } // namespace llvm
315 
316 static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
317   // Add the pass to the pass manager...
318   PM.add(P);
319 
320   // If we are verifying all of the intermediate steps, add the verifier...
321   if (VerifyEach)
322     PM.add(createVerifierPass());
323 }
324 
325 /// This routine adds optimization passes based on selected optimization level,
326 /// OptLevel.
327 ///
328 /// OptLevel - Optimization Level
329 static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
330                                   legacy::FunctionPassManager &FPM,
331                                   TargetMachine *TM, unsigned OptLevel,
332                                   unsigned SizeLevel) {
333   if (!NoVerify || VerifyEach)
334     FPM.add(createVerifierPass()); // Verify that input is correct
335 
336   PassManagerBuilder Builder;
337   Builder.OptLevel = OptLevel;
338   Builder.SizeLevel = SizeLevel;
339 
340   if (OptLevel > 1) {
341     Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
342   } else {
343     Builder.Inliner = createAlwaysInlinerLegacyPass();
344   }
345   Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
346                                DisableLoopUnrolling : OptLevel == 0;
347 
348   Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
349 
350   Builder.SLPVectorize = OptLevel > 1 && SizeLevel < 2;
351 
352   if (TM)
353     TM->adjustPassManager(Builder);
354 
355   switch (PGOKindFlag) {
356   case InstrGen:
357     Builder.EnablePGOInstrGen = true;
358     Builder.PGOInstrGen = ProfileFile;
359     break;
360   case InstrUse:
361     Builder.PGOInstrUse = ProfileFile;
362     break;
363   case SampleUse:
364     Builder.PGOSampleUse = ProfileFile;
365     break;
366   default:
367     break;
368   }
369 
370   switch (CSPGOKindFlag) {
371   case CSInstrGen:
372     Builder.EnablePGOCSInstrGen = true;
373     break;
374   case CSInstrUse:
375     Builder.EnablePGOCSInstrUse = true;
376     break;
377   default:
378     break;
379   }
380 
381   Builder.populateFunctionPassManager(FPM);
382   Builder.populateModulePassManager(MPM);
383 }
384 
385 //===----------------------------------------------------------------------===//
386 // CodeGen-related helper functions.
387 //
388 
389 static CodeGenOpt::Level GetCodeGenOptLevel() {
390   if (CodeGenOptLevel.getNumOccurrences())
391     return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
392   if (OptLevelO1)
393     return CodeGenOpt::Less;
394   if (OptLevelO2)
395     return CodeGenOpt::Default;
396   if (OptLevelO3)
397     return CodeGenOpt::Aggressive;
398   return CodeGenOpt::None;
399 }
400 
401 // Returns the TargetMachine instance or zero if no triple is provided.
402 static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
403                                        StringRef FeaturesStr,
404                                        const TargetOptions &Options) {
405   std::string Error;
406   const Target *TheTarget =
407       TargetRegistry::lookupTarget(codegen::getMArch(), TheTriple, Error);
408   // Some modules don't specify a triple, and this is okay.
409   if (!TheTarget) {
410     return nullptr;
411   }
412 
413   return TheTarget->createTargetMachine(
414       TheTriple.getTriple(), codegen::getCPUStr(), codegen::getFeaturesStr(),
415       Options, codegen::getExplicitRelocModel(),
416       codegen::getExplicitCodeModel(), GetCodeGenOptLevel());
417 }
418 
419 #ifdef BUILD_EXAMPLES
420 void initializeExampleIRTransforms(llvm::PassRegistry &Registry);
421 #endif
422 
423 struct TimeTracerRAII {
424   TimeTracerRAII(StringRef ProgramName) {
425     if (TimeTrace)
426       timeTraceProfilerInitialize(TimeTraceGranularity, ProgramName);
427   }
428   ~TimeTracerRAII() {
429     if (TimeTrace) {
430       if (auto E = timeTraceProfilerWrite(TimeTraceFile, OutputFilename)) {
431         handleAllErrors(std::move(E), [&](const StringError &SE) {
432           errs() << SE.getMessage() << "\n";
433         });
434         return;
435       }
436       timeTraceProfilerCleanup();
437     }
438   }
439 };
440 
441 // For use in NPM transition. Currently this contains most codegen-specific
442 // passes. Remove passes from here when porting to the NPM.
443 // TODO: use a codegen version of PassRegistry.def/PassBuilder::is*Pass() once
444 // it exists.
445 static bool shouldPinPassToLegacyPM(StringRef Pass) {
446   std::vector<StringRef> PassNameExactToIgnore = {
447       "nvvm-reflect",
448       "nvvm-intr-range",
449       "amdgpu-simplifylib",
450       "amdgpu-usenative",
451       "amdgpu-promote-alloca",
452       "amdgpu-promote-alloca-to-vector",
453       "amdgpu-lower-kernel-attributes",
454       "amdgpu-propagate-attributes-early",
455       "amdgpu-propagate-attributes-late",
456       "amdgpu-unify-metadata",
457       "amdgpu-printf-runtime-binding",
458       "amdgpu-always-inline"};
459   if (llvm::is_contained(PassNameExactToIgnore, Pass))
460     return false;
461 
462   std::vector<StringRef> PassNamePrefix = {
463       "x86-",    "xcore-", "wasm-",  "systemz-", "ppc-",    "nvvm-",
464       "nvptx-",  "mips-",  "lanai-", "hexagon-", "bpf-",    "avr-",
465       "thumb2-", "arm-",   "si-",    "gcn-",     "amdgpu-", "aarch64-",
466       "amdgcn-", "polly-", "riscv-", "dxil-"};
467   std::vector<StringRef> PassNameContain = {"ehprepare"};
468   std::vector<StringRef> PassNameExact = {
469       "safe-stack",           "cost-model",
470       "codegenprepare",       "interleaved-load-combine",
471       "unreachableblockelim", "verify-safepoint-ir",
472       "atomic-expand",        "expandvp",
473       "hardware-loops",       "type-promotion",
474       "mve-tail-predication", "interleaved-access",
475       "global-merge",         "pre-isel-intrinsic-lowering",
476       "expand-reductions",    "indirectbr-expand",
477       "generic-to-nvvm",      "expandmemcmp",
478       "loop-reduce",          "lower-amx-type",
479       "pre-amx-config",       "lower-amx-intrinsics",
480       "polyhedral-info",      "print-polyhedral-info",
481       "replace-with-veclib",  "jmc-instrument",
482       "dot-regions",          "dot-regions-only",
483       "view-regions",         "view-regions-only",
484       "select-optimize"};
485   for (const auto &P : PassNamePrefix)
486     if (Pass.startswith(P))
487       return true;
488   for (const auto &P : PassNameContain)
489     if (Pass.contains(P))
490       return true;
491   return llvm::is_contained(PassNameExact, Pass);
492 }
493 
494 // For use in NPM transition.
495 static bool shouldForceLegacyPM() {
496   for (const auto &P : PassList) {
497     StringRef Arg = P->getPassArgument();
498     if (shouldPinPassToLegacyPM(Arg))
499       return true;
500   }
501   return false;
502 }
503 
504 //===----------------------------------------------------------------------===//
505 // main for opt
506 //
507 int main(int argc, char **argv) {
508   InitLLVM X(argc, argv);
509 
510   // Enable debug stream buffering.
511   EnableDebugBuffering = true;
512 
513   InitializeAllTargets();
514   InitializeAllTargetMCs();
515   InitializeAllAsmPrinters();
516   InitializeAllAsmParsers();
517 
518   // Initialize passes
519   PassRegistry &Registry = *PassRegistry::getPassRegistry();
520   initializeCore(Registry);
521   initializeScalarOpts(Registry);
522   initializeObjCARCOpts(Registry);
523   initializeVectorization(Registry);
524   initializeIPO(Registry);
525   initializeAnalysis(Registry);
526   initializeTransformUtils(Registry);
527   initializeInstCombine(Registry);
528   initializeAggressiveInstCombine(Registry);
529   initializeInstrumentation(Registry);
530   initializeTarget(Registry);
531   // For codegen passes, only passes that do IR to IR transformation are
532   // supported.
533   initializeExpandMemCmpPassPass(Registry);
534   initializeScalarizeMaskedMemIntrinLegacyPassPass(Registry);
535   initializeSelectOptimizePass(Registry);
536   initializeCodeGenPreparePass(Registry);
537   initializeAtomicExpandPass(Registry);
538   initializeRewriteSymbolsLegacyPassPass(Registry);
539   initializeWinEHPreparePass(Registry);
540   initializeDwarfEHPrepareLegacyPassPass(Registry);
541   initializeSafeStackLegacyPassPass(Registry);
542   initializeSjLjEHPreparePass(Registry);
543   initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
544   initializeGlobalMergePass(Registry);
545   initializeIndirectBrExpandPassPass(Registry);
546   initializeInterleavedLoadCombinePass(Registry);
547   initializeInterleavedAccessPass(Registry);
548   initializeEntryExitInstrumenterPass(Registry);
549   initializePostInlineEntryExitInstrumenterPass(Registry);
550   initializeUnreachableBlockElimLegacyPassPass(Registry);
551   initializeExpandReductionsPass(Registry);
552   initializeExpandVectorPredicationPass(Registry);
553   initializeWasmEHPreparePass(Registry);
554   initializeWriteBitcodePassPass(Registry);
555   initializeHardwareLoopsPass(Registry);
556   initializeTypePromotionPass(Registry);
557   initializeReplaceWithVeclibLegacyPass(Registry);
558   initializeJMCInstrumenterPass(Registry);
559 
560 #ifdef BUILD_EXAMPLES
561   initializeExampleIRTransforms(Registry);
562 #endif
563 
564   SmallVector<PassPlugin, 1> PluginList;
565   PassPlugins.setCallback([&](const std::string &PluginPath) {
566     auto Plugin = PassPlugin::Load(PluginPath);
567     if (!Plugin) {
568       errs() << "Failed to load passes from '" << PluginPath
569              << "'. Request ignored.\n";
570       return;
571     }
572     PluginList.emplace_back(Plugin.get());
573   });
574 
575   cl::ParseCommandLineOptions(argc, argv,
576     "llvm .bc -> .bc modular optimizer and analysis printer\n");
577 
578   LLVMContext Context;
579 
580   // If `-passes=` is specified, use NPM.
581   // If `-enable-new-pm` is specified and there are no codegen passes, use NPM.
582   // e.g. `-enable-new-pm -sroa` will use NPM.
583   // but `-enable-new-pm -codegenprepare` will still revert to legacy PM.
584   const bool UseNPM = (EnableNewPassManager && !shouldForceLegacyPM()) ||
585                       PassPipeline.getNumOccurrences() > 0;
586 
587   if (!UseNPM && PluginList.size()) {
588     errs() << argv[0] << ": " << PassPlugins.ArgStr
589            << " specified with legacy PM.\n";
590     return 1;
591   }
592 
593   // FIXME: once the legacy PM code is deleted, move runPassPipeline() here and
594   // construct the PassBuilder before parsing IR so we can reuse the same
595   // PassBuilder for print passes.
596   if (PrintPasses) {
597     printPasses(outs());
598     return 0;
599   }
600 
601   TimeTracerRAII TimeTracer(argv[0]);
602 
603   SMDiagnostic Err;
604 
605   Context.setDiscardValueNames(DiscardValueNames);
606   if (!DisableDITypeMap)
607     Context.enableDebugTypeODRUniquing();
608 
609   Expected<std::unique_ptr<ToolOutputFile>> RemarksFileOrErr =
610       setupLLVMOptimizationRemarks(Context, RemarksFilename, RemarksPasses,
611                                    RemarksFormat, RemarksWithHotness,
612                                    RemarksHotnessThreshold);
613   if (Error E = RemarksFileOrErr.takeError()) {
614     errs() << toString(std::move(E)) << '\n';
615     return 1;
616   }
617   std::unique_ptr<ToolOutputFile> RemarksFile = std::move(*RemarksFileOrErr);
618 
619   // Load the input module...
620   auto SetDataLayout = [](StringRef) -> Optional<std::string> {
621     if (ClDataLayout.empty())
622       return None;
623     return ClDataLayout;
624   };
625   std::unique_ptr<Module> M;
626   if (NoUpgradeDebugInfo)
627     M = parseAssemblyFileWithIndexNoUpgradeDebugInfo(
628             InputFilename, Err, Context, nullptr, SetDataLayout)
629             .Mod;
630   else
631     M = parseIRFile(InputFilename, Err, Context, SetDataLayout);
632 
633   if (!M) {
634     Err.print(argv[0], errs());
635     return 1;
636   }
637 
638   // Strip debug info before running the verifier.
639   if (StripDebug)
640     StripDebugInfo(*M);
641 
642   // Erase module-level named metadata, if requested.
643   if (StripNamedMetadata) {
644     while (!M->named_metadata_empty()) {
645       NamedMDNode *NMD = &*M->named_metadata_begin();
646       M->eraseNamedMetadata(NMD);
647     }
648   }
649 
650   // If we are supposed to override the target triple or data layout, do so now.
651   if (!TargetTriple.empty())
652     M->setTargetTriple(Triple::normalize(TargetTriple));
653 
654   // Immediately run the verifier to catch any problems before starting up the
655   // pass pipelines.  Otherwise we can crash on broken code during
656   // doInitialization().
657   if (!NoVerify && verifyModule(*M, &errs())) {
658     errs() << argv[0] << ": " << InputFilename
659            << ": error: input module is broken!\n";
660     return 1;
661   }
662 
663   // Enable testing of whole program devirtualization on this module by invoking
664   // the facility for updating public visibility to linkage unit visibility when
665   // specified by an internal option. This is normally done during LTO which is
666   // not performed via opt.
667   updateVCallVisibilityInModule(*M,
668                                 /* WholeProgramVisibilityEnabledInLTO */ false,
669                                 /* DynamicExportSymbols */ {});
670 
671   // Figure out what stream we are supposed to write to...
672   std::unique_ptr<ToolOutputFile> Out;
673   std::unique_ptr<ToolOutputFile> ThinLinkOut;
674   if (NoOutput) {
675     if (!OutputFilename.empty())
676       errs() << "WARNING: The -o (output filename) option is ignored when\n"
677                 "the --disable-output option is used.\n";
678   } else {
679     // Default to standard output.
680     if (OutputFilename.empty())
681       OutputFilename = "-";
682 
683     std::error_code EC;
684     sys::fs::OpenFlags Flags =
685         OutputAssembly ? sys::fs::OF_TextWithCRLF : sys::fs::OF_None;
686     Out.reset(new ToolOutputFile(OutputFilename, EC, Flags));
687     if (EC) {
688       errs() << EC.message() << '\n';
689       return 1;
690     }
691 
692     if (!ThinLinkBitcodeFile.empty()) {
693       ThinLinkOut.reset(
694           new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::OF_None));
695       if (EC) {
696         errs() << EC.message() << '\n';
697         return 1;
698       }
699     }
700   }
701 
702   Triple ModuleTriple(M->getTargetTriple());
703   std::string CPUStr, FeaturesStr;
704   TargetMachine *Machine = nullptr;
705   const TargetOptions Options =
706       codegen::InitTargetOptionsFromCodeGenFlags(ModuleTriple);
707 
708   if (ModuleTriple.getArch()) {
709     CPUStr = codegen::getCPUStr();
710     FeaturesStr = codegen::getFeaturesStr();
711     Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
712   } else if (ModuleTriple.getArchName() != "unknown" &&
713              ModuleTriple.getArchName() != "") {
714     errs() << argv[0] << ": unrecognized architecture '"
715            << ModuleTriple.getArchName() << "' provided.\n";
716     return 1;
717   }
718 
719   std::unique_ptr<TargetMachine> TM(Machine);
720 
721   // Override function attributes based on CPUStr, FeaturesStr, and command line
722   // flags.
723   codegen::setFunctionAttributes(CPUStr, FeaturesStr, *M);
724 
725   // If the output is set to be emitted to standard out, and standard out is a
726   // console, print out a warning message and refuse to do it.  We don't
727   // impress anyone by spewing tons of binary goo to a terminal.
728   if (!Force && !NoOutput && !OutputAssembly)
729     if (CheckBitcodeOutputToConsole(Out->os()))
730       NoOutput = true;
731 
732   if (OutputThinLTOBC)
733     M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
734 
735   // Add an appropriate TargetLibraryInfo pass for the module's triple.
736   TargetLibraryInfoImpl TLII(ModuleTriple);
737 
738   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
739   if (DisableSimplifyLibCalls)
740     TLII.disableAllFunctions();
741   else {
742     // Disable individual builtin functions in TargetLibraryInfo.
743     LibFunc F;
744     for (auto &FuncName : DisableBuiltins)
745       if (TLII.getLibFunc(FuncName, F))
746         TLII.setUnavailable(F);
747       else {
748         errs() << argv[0] << ": cannot disable nonexistent builtin function "
749                << FuncName << '\n';
750         return 1;
751       }
752   }
753 
754   if (UseNPM) {
755     if (legacy::debugPassSpecified()) {
756       errs()
757           << "-debug-pass does not work with the new PM, either use "
758              "-debug-pass-manager, or use the legacy PM (-enable-new-pm=0)\n";
759       return 1;
760     }
761     if (PassPipeline.getNumOccurrences() > 0 && PassList.size() > 0) {
762       errs()
763           << "Cannot specify passes via both -foo-pass and --passes=foo-pass\n";
764       return 1;
765     }
766     auto NumOLevel = OptLevelO0 + OptLevelO1 + OptLevelO2 + OptLevelO3 +
767                      OptLevelOs + OptLevelOz;
768     if (NumOLevel > 1) {
769       errs() << "Cannot specify multiple -O#\n";
770       return 1;
771     }
772     if (NumOLevel > 0 &&
773         (PassPipeline.getNumOccurrences() > 0 || PassList.size() > 0)) {
774       errs() << "Cannot specify -O# and --passes=/--foo-pass, use "
775                 "-passes='default<O#>,other-pass'\n";
776       return 1;
777     }
778     std::string Pipeline = PassPipeline;
779 
780     SmallVector<StringRef, 4> Passes;
781     if (OptLevelO0)
782       Pipeline = "default<O0>";
783     if (OptLevelO1)
784       Pipeline = "default<O1>";
785     if (OptLevelO2)
786       Pipeline = "default<O2>";
787     if (OptLevelO3)
788       Pipeline = "default<O3>";
789     if (OptLevelOs)
790       Pipeline = "default<Os>";
791     if (OptLevelOz)
792       Pipeline = "default<Oz>";
793     for (const auto &P : PassList)
794       Passes.push_back(P->getPassArgument());
795     OutputKind OK = OK_NoOutput;
796     if (!NoOutput)
797       OK = OutputAssembly
798                ? OK_OutputAssembly
799                : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
800 
801     VerifierKind VK = VK_VerifyInAndOut;
802     if (NoVerify)
803       VK = VK_NoVerifier;
804     else if (VerifyEach)
805       VK = VK_VerifyEachPass;
806 
807     // The user has asked to use the new pass manager and provided a pipeline
808     // string. Hand off the rest of the functionality to the new code for that
809     // layer.
810     return runPassPipeline(argv[0], *M, TM.get(), &TLII, Out.get(),
811                            ThinLinkOut.get(), RemarksFile.get(), Pipeline,
812                            Passes, PluginList, OK, VK, PreserveAssemblyUseListOrder,
813                            PreserveBitcodeUseListOrder, EmitSummaryIndex,
814                            EmitModuleHash, EnableDebugify,
815                            VerifyDebugInfoPreserve)
816                ? 0
817                : 1;
818   }
819 
820   // Create a PassManager to hold and optimize the collection of passes we are
821   // about to build. If the -debugify-each option is set, wrap each pass with
822   // the (-check)-debugify passes.
823   DebugifyCustomPassManager Passes;
824   DebugifyStatsMap DIStatsMap;
825   DebugInfoPerPass DebugInfoBeforePass;
826   if (DebugifyEach) {
827     Passes.setDebugifyMode(DebugifyMode::SyntheticDebugInfo);
828     Passes.setDIStatsMap(DIStatsMap);
829   } else if (VerifyEachDebugInfoPreserve) {
830     Passes.setDebugifyMode(DebugifyMode::OriginalDebugInfo);
831     Passes.setDebugInfoBeforePass(DebugInfoBeforePass);
832     if (!VerifyDIPreserveExport.empty())
833       Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport);
834   }
835 
836   bool AddOneTimeDebugifyPasses =
837       (EnableDebugify && !DebugifyEach) ||
838       (VerifyDebugInfoPreserve && !VerifyEachDebugInfoPreserve);
839 
840   Passes.add(new TargetLibraryInfoWrapperPass(TLII));
841 
842   // Add internal analysis passes from the target machine.
843   Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
844                                                      : TargetIRAnalysis()));
845 
846   if (AddOneTimeDebugifyPasses) {
847     if (EnableDebugify) {
848       Passes.setDIStatsMap(DIStatsMap);
849       Passes.add(createDebugifyModulePass());
850     } else if (VerifyDebugInfoPreserve) {
851       Passes.setDebugInfoBeforePass(DebugInfoBeforePass);
852       Passes.add(createDebugifyModulePass(
853           DebugifyMode::OriginalDebugInfo, "",
854           &(Passes.getDebugInfoPerPass())));
855     }
856   }
857 
858   std::unique_ptr<legacy::FunctionPassManager> FPasses;
859   if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
860       OptLevelO3) {
861     FPasses.reset(new legacy::FunctionPassManager(M.get()));
862     FPasses->add(createTargetTransformInfoWrapperPass(
863         TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
864   }
865 
866   if (PrintBreakpoints) {
867     // Default to standard output.
868     if (!Out) {
869       if (OutputFilename.empty())
870         OutputFilename = "-";
871 
872       std::error_code EC;
873       Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,
874                                               sys::fs::OF_None);
875       if (EC) {
876         errs() << EC.message() << '\n';
877         return 1;
878       }
879     }
880     Passes.add(createBreakpointPrinter(Out->os()));
881     NoOutput = true;
882   }
883 
884   if (TM) {
885     // FIXME: We should dyn_cast this when supported.
886     auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
887     Pass *TPC = LTM.createPassConfig(Passes);
888     Passes.add(TPC);
889   }
890 
891   // Create a new optimization pass for each one specified on the command line
892   for (unsigned i = 0; i < PassList.size(); ++i) {
893     if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
894       AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
895       OptLevelO0 = false;
896     }
897 
898     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
899       AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
900       OptLevelO1 = false;
901     }
902 
903     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
904       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
905       OptLevelO2 = false;
906     }
907 
908     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
909       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
910       OptLevelOs = false;
911     }
912 
913     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
914       AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
915       OptLevelOz = false;
916     }
917 
918     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
919       AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
920       OptLevelO3 = false;
921     }
922 
923     const PassInfo *PassInf = PassList[i];
924     Pass *P = nullptr;
925     if (PassInf->getNormalCtor())
926       P = PassInf->getNormalCtor()();
927     else
928       errs() << argv[0] << ": cannot create pass: "
929              << PassInf->getPassName() << "\n";
930     if (P)
931       addPass(Passes, P);
932   }
933 
934   if (OptLevelO0)
935     AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
936 
937   if (OptLevelO1)
938     AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
939 
940   if (OptLevelO2)
941     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
942 
943   if (OptLevelOs)
944     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
945 
946   if (OptLevelOz)
947     AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
948 
949   if (OptLevelO3)
950     AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
951 
952   if (FPasses) {
953     FPasses->doInitialization();
954     for (Function &F : *M)
955       FPasses->run(F);
956     FPasses->doFinalization();
957   }
958 
959   // Check that the module is well formed on completion of optimization
960   if (!NoVerify && !VerifyEach)
961     Passes.add(createVerifierPass());
962 
963   if (AddOneTimeDebugifyPasses) {
964     if (EnableDebugify)
965       Passes.add(createCheckDebugifyModulePass(false));
966     else if (VerifyDebugInfoPreserve) {
967       if (!VerifyDIPreserveExport.empty())
968         Passes.setOrigDIVerifyBugsReportFilePath(VerifyDIPreserveExport);
969       Passes.add(createCheckDebugifyModulePass(
970           false, "", nullptr, DebugifyMode::OriginalDebugInfo,
971           &(Passes.getDebugInfoPerPass()), VerifyDIPreserveExport));
972     }
973   }
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;
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