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