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