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