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