xref: /llvm-project-15.0.7/llvm/tools/opt/opt.cpp (revision 12b0809e)
1 //===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // Optimizations may be specified an arbitrary number of times on the command
11 // line, They are run in the order specified.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/LLVMContext.h"
16 #include "llvm/ADT/StringSet.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/Verifier.h"
23 #include "llvm/Assembly/PrintModulePass.h"
24 #include "llvm/Bitcode/ReaderWriter.h"
25 #include "llvm/CodeGen/CommandFlags.h"
26 #include "llvm/DebugInfo.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/IRReader/IRReader.h"
30 #include "llvm/LinkAllIR.h"
31 #include "llvm/LinkAllPasses.h"
32 #include "llvm/MC/SubtargetFeature.h"
33 #include "llvm/PassManager.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/PassNameParser.h"
37 #include "llvm/Support/PluginLoader.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/SystemUtils.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/ToolOutputFile.h"
45 #include "llvm/Target/TargetLibraryInfo.h"
46 #include "llvm/Target/TargetMachine.h"
47 #include "llvm/Transforms/IPO/PassManagerBuilder.h"
48 #include <algorithm>
49 #include <memory>
50 using namespace llvm;
51 
52 // The OptimizationList is automatically populated with registered Passes by the
53 // PassNameParser.
54 //
55 static cl::list<const PassInfo*, bool, PassNameParser>
56 PassList(cl::desc("Optimizations available:"));
57 
58 // Other command line options...
59 //
60 static cl::opt<std::string>
61 InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
62     cl::init("-"), cl::value_desc("filename"));
63 
64 static cl::opt<std::string>
65 OutputFilename("o", cl::desc("Override output filename"),
66                cl::value_desc("filename"));
67 
68 static cl::opt<bool>
69 Force("f", cl::desc("Enable binary output on terminals"));
70 
71 static cl::opt<bool>
72 PrintEachXForm("p", cl::desc("Print module after each transformation"));
73 
74 static cl::opt<bool>
75 NoOutput("disable-output",
76          cl::desc("Do not write result bitcode file"), cl::Hidden);
77 
78 static cl::opt<bool>
79 OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
80 
81 static cl::opt<bool>
82 NoVerify("disable-verify", cl::desc("Do not verify result module"), cl::Hidden);
83 
84 static cl::opt<bool>
85 VerifyEach("verify-each", cl::desc("Verify after each transform"));
86 
87 static cl::opt<bool>
88 StripDebug("strip-debug",
89            cl::desc("Strip debugger symbol info from translation unit"));
90 
91 static cl::opt<bool>
92 DisableInline("disable-inlining", cl::desc("Do not run the inliner pass"));
93 
94 static cl::opt<bool>
95 DisableOptimizations("disable-opt",
96                      cl::desc("Do not run any optimization passes"));
97 
98 static cl::opt<bool>
99 DisableInternalize("disable-internalize",
100                    cl::desc("Do not mark all symbols as internal"));
101 
102 static cl::opt<bool>
103 StandardCompileOpts("std-compile-opts",
104                    cl::desc("Include the standard compile time optimizations"));
105 
106 static cl::opt<bool>
107 StandardLinkOpts("std-link-opts",
108                  cl::desc("Include the standard link time optimizations"));
109 
110 static cl::opt<bool>
111 OptLevelO1("O1",
112            cl::desc("Optimization level 1. Similar to clang -O1"));
113 
114 static cl::opt<bool>
115 OptLevelO2("O2",
116            cl::desc("Optimization level 2. Similar to clang -O2"));
117 
118 static cl::opt<bool>
119 OptLevelOs("Os",
120            cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
121 
122 static cl::opt<bool>
123 OptLevelOz("Oz",
124            cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
125 
126 static cl::opt<bool>
127 OptLevelO3("O3",
128            cl::desc("Optimization level 3. Similar to clang -O3"));
129 
130 static cl::opt<std::string>
131 TargetTriple("mtriple", cl::desc("Override target triple for module"));
132 
133 static cl::opt<bool>
134 UnitAtATime("funit-at-a-time",
135             cl::desc("Enable IPO. This is same as llvm-gcc's -funit-at-a-time"),
136             cl::init(true));
137 
138 static cl::opt<bool>
139 DisableSimplifyLibCalls("disable-simplify-libcalls",
140                         cl::desc("Disable simplify-libcalls"));
141 
142 static cl::opt<bool>
143 Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
144 
145 static cl::alias
146 QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
147 
148 static cl::opt<bool>
149 AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
150 
151 static cl::opt<bool>
152 PrintBreakpoints("print-breakpoints-for-testing",
153                  cl::desc("Print select breakpoints location for testing"));
154 
155 static cl::opt<std::string>
156 DefaultDataLayout("default-data-layout",
157           cl::desc("data layout string to use if not specified by module"),
158           cl::value_desc("layout-string"), cl::init(""));
159 
160 // ---------- Define Printers for module and function passes ------------
161 namespace {
162 
163 struct CallGraphSCCPassPrinter : public CallGraphSCCPass {
164   static char ID;
165   const PassInfo *PassToPrint;
166   raw_ostream &Out;
167   std::string PassName;
168 
169   CallGraphSCCPassPrinter(const PassInfo *PI, raw_ostream &out) :
170     CallGraphSCCPass(ID), PassToPrint(PI), Out(out) {
171       std::string PassToPrintName =  PassToPrint->getPassName();
172       PassName = "CallGraphSCCPass Printer: " + PassToPrintName;
173     }
174 
175   virtual bool runOnSCC(CallGraphSCC &SCC) {
176     if (!Quiet)
177       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
178 
179     // Get and print pass...
180     for (CallGraphSCC::iterator I = SCC.begin(), E = SCC.end(); I != E; ++I) {
181       Function *F = (*I)->getFunction();
182       if (F)
183         getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
184                                                               F->getParent());
185     }
186     return false;
187   }
188 
189   virtual const char *getPassName() const { return PassName.c_str(); }
190 
191   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
192     AU.addRequiredID(PassToPrint->getTypeInfo());
193     AU.setPreservesAll();
194   }
195 };
196 
197 char CallGraphSCCPassPrinter::ID = 0;
198 
199 struct ModulePassPrinter : public ModulePass {
200   static char ID;
201   const PassInfo *PassToPrint;
202   raw_ostream &Out;
203   std::string PassName;
204 
205   ModulePassPrinter(const PassInfo *PI, raw_ostream &out)
206     : ModulePass(ID), PassToPrint(PI), Out(out) {
207       std::string PassToPrintName =  PassToPrint->getPassName();
208       PassName = "ModulePass Printer: " + PassToPrintName;
209     }
210 
211   virtual bool runOnModule(Module &M) {
212     if (!Quiet)
213       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
214 
215     // Get and print pass...
216     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out, &M);
217     return false;
218   }
219 
220   virtual const char *getPassName() const { return PassName.c_str(); }
221 
222   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
223     AU.addRequiredID(PassToPrint->getTypeInfo());
224     AU.setPreservesAll();
225   }
226 };
227 
228 char ModulePassPrinter::ID = 0;
229 struct FunctionPassPrinter : public FunctionPass {
230   const PassInfo *PassToPrint;
231   raw_ostream &Out;
232   static char ID;
233   std::string PassName;
234 
235   FunctionPassPrinter(const PassInfo *PI, raw_ostream &out)
236     : FunctionPass(ID), PassToPrint(PI), Out(out) {
237       std::string PassToPrintName =  PassToPrint->getPassName();
238       PassName = "FunctionPass Printer: " + PassToPrintName;
239     }
240 
241   virtual bool runOnFunction(Function &F) {
242     if (!Quiet)
243       Out << "Printing analysis '" << PassToPrint->getPassName()
244           << "' for function '" << F.getName() << "':\n";
245 
246     // Get and print pass...
247     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
248             F.getParent());
249     return false;
250   }
251 
252   virtual const char *getPassName() const { return PassName.c_str(); }
253 
254   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
255     AU.addRequiredID(PassToPrint->getTypeInfo());
256     AU.setPreservesAll();
257   }
258 };
259 
260 char FunctionPassPrinter::ID = 0;
261 
262 struct LoopPassPrinter : public LoopPass {
263   static char ID;
264   const PassInfo *PassToPrint;
265   raw_ostream &Out;
266   std::string PassName;
267 
268   LoopPassPrinter(const PassInfo *PI, raw_ostream &out) :
269     LoopPass(ID), PassToPrint(PI), Out(out) {
270       std::string PassToPrintName =  PassToPrint->getPassName();
271       PassName = "LoopPass Printer: " + PassToPrintName;
272     }
273 
274 
275   virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
276     if (!Quiet)
277       Out << "Printing analysis '" << PassToPrint->getPassName() << "':\n";
278 
279     // Get and print pass...
280     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
281                         L->getHeader()->getParent()->getParent());
282     return false;
283   }
284 
285   virtual const char *getPassName() const { return PassName.c_str(); }
286 
287   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
288     AU.addRequiredID(PassToPrint->getTypeInfo());
289     AU.setPreservesAll();
290   }
291 };
292 
293 char LoopPassPrinter::ID = 0;
294 
295 struct RegionPassPrinter : public RegionPass {
296   static char ID;
297   const PassInfo *PassToPrint;
298   raw_ostream &Out;
299   std::string PassName;
300 
301   RegionPassPrinter(const PassInfo *PI, raw_ostream &out) : RegionPass(ID),
302     PassToPrint(PI), Out(out) {
303     std::string PassToPrintName =  PassToPrint->getPassName();
304     PassName = "RegionPass Printer: " + PassToPrintName;
305   }
306 
307   virtual bool runOnRegion(Region *R, RGPassManager &RGM) {
308     if (!Quiet) {
309       Out << "Printing analysis '" << PassToPrint->getPassName() << "' for "
310           << "region: '" << R->getNameStr() << "' in function '"
311           << R->getEntry()->getParent()->getName() << "':\n";
312     }
313     // Get and print pass...
314    getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
315                        R->getEntry()->getParent()->getParent());
316     return false;
317   }
318 
319   virtual const char *getPassName() const { return PassName.c_str(); }
320 
321   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
322     AU.addRequiredID(PassToPrint->getTypeInfo());
323     AU.setPreservesAll();
324   }
325 };
326 
327 char RegionPassPrinter::ID = 0;
328 
329 struct BasicBlockPassPrinter : public BasicBlockPass {
330   const PassInfo *PassToPrint;
331   raw_ostream &Out;
332   static char ID;
333   std::string PassName;
334 
335   BasicBlockPassPrinter(const PassInfo *PI, raw_ostream &out)
336     : BasicBlockPass(ID), PassToPrint(PI), Out(out) {
337       std::string PassToPrintName =  PassToPrint->getPassName();
338       PassName = "BasicBlockPass Printer: " + PassToPrintName;
339     }
340 
341   virtual bool runOnBasicBlock(BasicBlock &BB) {
342     if (!Quiet)
343       Out << "Printing Analysis info for BasicBlock '" << BB.getName()
344           << "': Pass " << PassToPrint->getPassName() << ":\n";
345 
346     // Get and print pass...
347     getAnalysisID<Pass>(PassToPrint->getTypeInfo()).print(Out,
348             BB.getParent()->getParent());
349     return false;
350   }
351 
352   virtual const char *getPassName() const { return PassName.c_str(); }
353 
354   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
355     AU.addRequiredID(PassToPrint->getTypeInfo());
356     AU.setPreservesAll();
357   }
358 };
359 
360 char BasicBlockPassPrinter::ID = 0;
361 
362 struct BreakpointPrinter : public ModulePass {
363   raw_ostream &Out;
364   static char ID;
365 
366   BreakpointPrinter(raw_ostream &out)
367     : ModulePass(ID), Out(out) {
368     }
369 
370   void getContextName(DIDescriptor Context, std::string &N) {
371     if (Context.isNameSpace()) {
372       DINameSpace NS(Context);
373       if (!NS.getName().empty()) {
374         getContextName(NS.getContext(), N);
375         N = N + NS.getName().str() + "::";
376       }
377     } else if (Context.isType()) {
378       DIType TY(Context);
379       if (!TY.getName().empty()) {
380         getContextName(TY.getContext(), N);
381         N = N + TY.getName().str() + "::";
382       }
383     }
384   }
385 
386   virtual bool runOnModule(Module &M) {
387     StringSet<> Processed;
388     if (NamedMDNode *NMD = M.getNamedMetadata("llvm.dbg.sp"))
389       for (unsigned i = 0, e = NMD->getNumOperands(); i != e; ++i) {
390         std::string Name;
391         DISubprogram SP(NMD->getOperand(i));
392         assert((!SP || SP.isSubprogram()) &&
393           "A MDNode in llvm.dbg.sp should be null or a DISubprogram.");
394         if (!SP)
395           continue;
396         getContextName(SP.getContext(), Name);
397         Name = Name + SP.getDisplayName().str();
398         if (!Name.empty() && Processed.insert(Name)) {
399           Out << Name << "\n";
400         }
401       }
402     return false;
403   }
404 
405   virtual void getAnalysisUsage(AnalysisUsage &AU) const {
406     AU.setPreservesAll();
407   }
408 };
409 
410 } // anonymous namespace
411 
412 char BreakpointPrinter::ID = 0;
413 
414 static inline void addPass(PassManagerBase &PM, Pass *P) {
415   // Add the pass to the pass manager...
416   PM.add(P);
417 
418   // If we are verifying all of the intermediate steps, add the verifier...
419   if (VerifyEach) PM.add(createVerifierPass());
420 }
421 
422 /// AddOptimizationPasses - This routine adds optimization passes
423 /// based on selected optimization level, OptLevel. This routine
424 /// duplicates llvm-gcc behaviour.
425 ///
426 /// OptLevel - Optimization Level
427 static void AddOptimizationPasses(PassManagerBase &MPM,FunctionPassManager &FPM,
428                                   unsigned OptLevel, unsigned SizeLevel) {
429   FPM.add(createVerifierPass());                  // Verify that input is correct
430 
431   PassManagerBuilder Builder;
432   Builder.OptLevel = OptLevel;
433   Builder.SizeLevel = SizeLevel;
434 
435   if (DisableInline) {
436     // No inlining pass
437   } else if (OptLevel > 1) {
438     unsigned Threshold = 225;
439     if (SizeLevel == 1)      // -Os
440       Threshold = 75;
441     else if (SizeLevel == 2) // -Oz
442       Threshold = 25;
443     if (OptLevel > 2)
444       Threshold = 275;
445     Builder.Inliner = createFunctionInliningPass(Threshold);
446   } else {
447     Builder.Inliner = createAlwaysInlinerPass();
448   }
449   Builder.DisableUnitAtATime = !UnitAtATime;
450   Builder.DisableUnrollLoops = OptLevel == 0;
451 
452   Builder.populateFunctionPassManager(FPM);
453   Builder.populateModulePassManager(MPM);
454 
455   Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
456 }
457 
458 static void AddStandardCompilePasses(PassManagerBase &PM) {
459   PM.add(createVerifierPass());                  // Verify that input is correct
460 
461   // If the -strip-debug command line option was specified, do it.
462   if (StripDebug)
463     addPass(PM, createStripSymbolsPass(true));
464 
465   if (DisableOptimizations) return;
466 
467   // -std-compile-opts adds the same module passes as -O3.
468   PassManagerBuilder Builder;
469   if (!DisableInline)
470     Builder.Inliner = createFunctionInliningPass();
471   Builder.OptLevel = 3;
472   Builder.populateModulePassManager(PM);
473 }
474 
475 static void AddStandardLinkPasses(PassManagerBase &PM) {
476   PM.add(createVerifierPass());                  // Verify that input is correct
477 
478   // If the -strip-debug command line option was specified, do it.
479   if (StripDebug)
480     addPass(PM, createStripSymbolsPass(true));
481 
482   if (DisableOptimizations) return;
483 
484   PassManagerBuilder Builder;
485   Builder.populateLTOPassManager(PM, /*Internalize=*/ !DisableInternalize,
486                                  /*RunInliner=*/ !DisableInline);
487 }
488 
489 //===----------------------------------------------------------------------===//
490 // CodeGen-related helper functions.
491 //
492 static TargetOptions GetTargetOptions() {
493   TargetOptions Options;
494   Options.LessPreciseFPMADOption = EnableFPMAD;
495   Options.NoFramePointerElim = DisableFPElim;
496   Options.AllowFPOpFusion = FuseFPOps;
497   Options.UnsafeFPMath = EnableUnsafeFPMath;
498   Options.NoInfsFPMath = EnableNoInfsFPMath;
499   Options.NoNaNsFPMath = EnableNoNaNsFPMath;
500   Options.HonorSignDependentRoundingFPMathOption =
501   EnableHonorSignDependentRoundingFPMath;
502   Options.UseSoftFloat = GenerateSoftFloatCalls;
503   if (FloatABIForCalls != FloatABI::Default)
504     Options.FloatABIType = FloatABIForCalls;
505   Options.NoZerosInBSS = DontPlaceZerosInBSS;
506   Options.GuaranteedTailCallOpt = EnableGuaranteedTailCallOpt;
507   Options.DisableTailCalls = DisableTailCalls;
508   Options.StackAlignmentOverride = OverrideStackAlignment;
509   Options.TrapFuncName = TrapFuncName;
510   Options.PositionIndependentExecutable = EnablePIE;
511   Options.EnableSegmentedStacks = SegmentedStacks;
512   Options.UseInitArray = UseInitArray;
513   return Options;
514 }
515 
516 CodeGenOpt::Level GetCodeGenOptLevel() {
517   if (OptLevelO1)
518     return CodeGenOpt::Less;
519   if (OptLevelO2)
520     return CodeGenOpt::Default;
521   if (OptLevelO3)
522     return CodeGenOpt::Aggressive;
523   return CodeGenOpt::None;
524 }
525 
526 // Returns the TargetMachine instance or zero if no triple is provided.
527 static TargetMachine* GetTargetMachine(Triple TheTriple) {
528   std::string Error;
529   const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
530                                                          Error);
531   // Some modules don't specify a triple, and this is okay.
532   if (!TheTarget) {
533     return 0;
534   }
535 
536   // Package up features to be passed to target/subtarget
537   std::string FeaturesStr;
538   if (MAttrs.size()) {
539     SubtargetFeatures Features;
540     for (unsigned i = 0; i != MAttrs.size(); ++i)
541       Features.AddFeature(MAttrs[i]);
542     FeaturesStr = Features.getString();
543   }
544 
545   return TheTarget->createTargetMachine(TheTriple.getTriple(),
546                                         MCPU, FeaturesStr, GetTargetOptions(),
547                                         RelocModel, CMModel,
548                                         GetCodeGenOptLevel());
549 }
550 
551 //===----------------------------------------------------------------------===//
552 // main for opt
553 //
554 int main(int argc, char **argv) {
555   sys::PrintStackTraceOnErrorSignal();
556   llvm::PrettyStackTraceProgram X(argc, argv);
557 
558   // Enable debug stream buffering.
559   EnableDebugBuffering = true;
560 
561   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
562   LLVMContext &Context = getGlobalContext();
563 
564   InitializeAllTargets();
565   InitializeAllTargetMCs();
566 
567   // Initialize passes
568   PassRegistry &Registry = *PassRegistry::getPassRegistry();
569   initializeCore(Registry);
570   initializeDebugIRPass(Registry);
571   initializeScalarOpts(Registry);
572   initializeObjCARCOpts(Registry);
573   initializeVectorization(Registry);
574   initializeIPO(Registry);
575   initializeAnalysis(Registry);
576   initializeIPA(Registry);
577   initializeTransformUtils(Registry);
578   initializeInstCombine(Registry);
579   initializeInstrumentation(Registry);
580   initializeTarget(Registry);
581 
582   cl::ParseCommandLineOptions(argc, argv,
583     "llvm .bc -> .bc modular optimizer and analysis printer\n");
584 
585   if (AnalyzeOnly && NoOutput) {
586     errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
587     return 1;
588   }
589 
590   SMDiagnostic Err;
591 
592   // Load the input module...
593   OwningPtr<Module> M;
594   M.reset(ParseIRFile(InputFilename, Err, Context));
595 
596   if (M.get() == 0) {
597     Err.print(argv[0], errs());
598     return 1;
599   }
600 
601   // If we are supposed to override the target triple, do so now.
602   if (!TargetTriple.empty())
603     M->setTargetTriple(Triple::normalize(TargetTriple));
604 
605   // Figure out what stream we are supposed to write to...
606   OwningPtr<tool_output_file> Out;
607   if (NoOutput) {
608     if (!OutputFilename.empty())
609       errs() << "WARNING: The -o (output filename) option is ignored when\n"
610                 "the --disable-output option is used.\n";
611   } else {
612     // Default to standard output.
613     if (OutputFilename.empty())
614       OutputFilename = "-";
615 
616     std::string ErrorInfo;
617     Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
618                                    sys::fs::F_Binary));
619     if (!ErrorInfo.empty()) {
620       errs() << ErrorInfo << '\n';
621       return 1;
622     }
623   }
624 
625   // If the output is set to be emitted to standard out, and standard out is a
626   // console, print out a warning message and refuse to do it.  We don't
627   // impress anyone by spewing tons of binary goo to a terminal.
628   if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
629     if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
630       NoOutput = true;
631 
632   // Create a PassManager to hold and optimize the collection of passes we are
633   // about to build.
634   //
635   PassManager Passes;
636 
637   // Add an appropriate TargetLibraryInfo pass for the module's triple.
638   TargetLibraryInfo *TLI = new TargetLibraryInfo(Triple(M->getTargetTriple()));
639 
640   // The -disable-simplify-libcalls flag actually disables all builtin optzns.
641   if (DisableSimplifyLibCalls)
642     TLI->disableAllFunctions();
643   Passes.add(TLI);
644 
645   // Add an appropriate DataLayout instance for this module.
646   DataLayout *TD = 0;
647   const std::string &ModuleDataLayout = M.get()->getDataLayout();
648   if (!ModuleDataLayout.empty())
649     TD = new DataLayout(ModuleDataLayout);
650   else if (!DefaultDataLayout.empty())
651     TD = new DataLayout(DefaultDataLayout);
652 
653   if (TD)
654     Passes.add(TD);
655 
656   Triple ModuleTriple(M->getTargetTriple());
657   TargetMachine *Machine = 0;
658   if (ModuleTriple.getArch())
659     Machine = GetTargetMachine(Triple(ModuleTriple));
660   OwningPtr<TargetMachine> TM(Machine);
661 
662   // Add internal analysis passes from the target machine.
663   if (TM.get())
664     TM->addAnalysisPasses(Passes);
665 
666   OwningPtr<FunctionPassManager> FPasses;
667   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
668     FPasses.reset(new FunctionPassManager(M.get()));
669     if (TD)
670       FPasses->add(new DataLayout(*TD));
671     if (TM.get())
672       TM->addAnalysisPasses(*FPasses);
673 
674   }
675 
676   if (PrintBreakpoints) {
677     // Default to standard output.
678     if (!Out) {
679       if (OutputFilename.empty())
680         OutputFilename = "-";
681 
682       std::string ErrorInfo;
683       Out.reset(new tool_output_file(OutputFilename.c_str(), ErrorInfo,
684                                      sys::fs::F_Binary));
685       if (!ErrorInfo.empty()) {
686         errs() << ErrorInfo << '\n';
687         return 1;
688       }
689     }
690     Passes.add(new BreakpointPrinter(Out->os()));
691     NoOutput = true;
692   }
693 
694   // If the -strip-debug command line option was specified, add it.  If
695   // -std-compile-opts was also specified, it will handle StripDebug.
696   if (StripDebug && !StandardCompileOpts)
697     addPass(Passes, createStripSymbolsPass(true));
698 
699   // Create a new optimization pass for each one specified on the command line
700   for (unsigned i = 0; i < PassList.size(); ++i) {
701     // Check to see if -std-compile-opts was specified before this option.  If
702     // so, handle it.
703     if (StandardCompileOpts &&
704         StandardCompileOpts.getPosition() < PassList.getPosition(i)) {
705       AddStandardCompilePasses(Passes);
706       StandardCompileOpts = false;
707     }
708 
709     if (StandardLinkOpts &&
710         StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
711       AddStandardLinkPasses(Passes);
712       StandardLinkOpts = false;
713     }
714 
715     if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
716       AddOptimizationPasses(Passes, *FPasses, 1, 0);
717       OptLevelO1 = false;
718     }
719 
720     if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
721       AddOptimizationPasses(Passes, *FPasses, 2, 0);
722       OptLevelO2 = false;
723     }
724 
725     if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
726       AddOptimizationPasses(Passes, *FPasses, 2, 1);
727       OptLevelOs = false;
728     }
729 
730     if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
731       AddOptimizationPasses(Passes, *FPasses, 2, 2);
732       OptLevelOz = false;
733     }
734 
735     if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
736       AddOptimizationPasses(Passes, *FPasses, 3, 0);
737       OptLevelO3 = false;
738     }
739 
740     const PassInfo *PassInf = PassList[i];
741     Pass *P = 0;
742     if (PassInf->getNormalCtor())
743       P = PassInf->getNormalCtor()();
744     else
745       errs() << argv[0] << ": cannot create pass: "
746              << PassInf->getPassName() << "\n";
747     if (P) {
748       PassKind Kind = P->getPassKind();
749       addPass(Passes, P);
750 
751       if (AnalyzeOnly) {
752         switch (Kind) {
753         case PT_BasicBlock:
754           Passes.add(new BasicBlockPassPrinter(PassInf, Out->os()));
755           break;
756         case PT_Region:
757           Passes.add(new RegionPassPrinter(PassInf, Out->os()));
758           break;
759         case PT_Loop:
760           Passes.add(new LoopPassPrinter(PassInf, Out->os()));
761           break;
762         case PT_Function:
763           Passes.add(new FunctionPassPrinter(PassInf, Out->os()));
764           break;
765         case PT_CallGraphSCC:
766           Passes.add(new CallGraphSCCPassPrinter(PassInf, Out->os()));
767           break;
768         default:
769           Passes.add(new ModulePassPrinter(PassInf, Out->os()));
770           break;
771         }
772       }
773     }
774 
775     if (PrintEachXForm)
776       Passes.add(createPrintModulePass(&errs()));
777   }
778 
779   // If -std-compile-opts was specified at the end of the pass list, add them.
780   if (StandardCompileOpts) {
781     AddStandardCompilePasses(Passes);
782     StandardCompileOpts = false;
783   }
784 
785   if (StandardLinkOpts) {
786     AddStandardLinkPasses(Passes);
787     StandardLinkOpts = false;
788   }
789 
790   if (OptLevelO1)
791     AddOptimizationPasses(Passes, *FPasses, 1, 0);
792 
793   if (OptLevelO2)
794     AddOptimizationPasses(Passes, *FPasses, 2, 0);
795 
796   if (OptLevelOs)
797     AddOptimizationPasses(Passes, *FPasses, 2, 1);
798 
799   if (OptLevelOz)
800     AddOptimizationPasses(Passes, *FPasses, 2, 2);
801 
802   if (OptLevelO3)
803     AddOptimizationPasses(Passes, *FPasses, 3, 0);
804 
805   if (OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz || OptLevelO3) {
806     FPasses->doInitialization();
807     for (Module::iterator F = M->begin(), E = M->end(); F != E; ++F)
808       FPasses->run(*F);
809     FPasses->doFinalization();
810   }
811 
812   // Check that the module is well formed on completion of optimization
813   if (!NoVerify && !VerifyEach)
814     Passes.add(createVerifierPass());
815 
816   // Write bitcode or assembly to the output as the last step...
817   if (!NoOutput && !AnalyzeOnly) {
818     if (OutputAssembly)
819       Passes.add(createPrintModulePass(&Out->os()));
820     else
821       Passes.add(createBitcodeWriterPass(Out->os()));
822   }
823 
824   // Before executing passes, print the final values of the LLVM options.
825   cl::PrintOptionValues();
826 
827   // Now that we have all of the passes ready, run them.
828   Passes.run(*M.get());
829 
830   // Declare success.
831   if (!NoOutput || PrintBreakpoints)
832     Out->keep();
833 
834   return 0;
835 }
836