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