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