blob: a4967a234d9cece989be8f1ffbf80b2a11047d30 [file] [log] [blame]
Chris Lattner76351aa2004-04-02 05:06:57 +00001//===- opt.cpp - The LLVM Modular Optimizer -------------------------------===//
Misha Brukman3da94ae2005-04-22 00:00:37 +00002//
John Criswell7c0e0222003-10-20 17:47:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattner21c62da2007-12-29 20:44:31 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukman3da94ae2005-04-22 00:00:37 +00007//
John Criswell7c0e0222003-10-20 17:47:21 +00008//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +00009//
Chris Lattner00950542001-06-06 20:29:01 +000010// Optimizations may be specified an arbitrary number of times on the command
Reid Spencerfd90dd52006-08-18 06:34:30 +000011// line, They are run in the order specified.
Chris Lattner00950542001-06-06 20:29:01 +000012//
Chris Lattner0eafc312001-10-18 06:05:15 +000013//===----------------------------------------------------------------------===//
Chris Lattner00950542001-06-06 20:29:01 +000014
Eli Benderskya0ea8fa2014-02-12 16:48:02 +000015#include "BreakpointPrinter.h"
Vedant Kumara4afd1f2018-07-24 00:41:28 +000016#include "Debugify.h"
Chandler Carruth4e728be2014-01-11 08:16:35 +000017#include "NewPMDriver.h"
Eli Bendersky8ed971b2014-02-10 23:34:23 +000018#include "PassPrinters.h"
Chris Lattner2a66aca2011-02-18 22:13:01 +000019#include "llvm/ADT/Triple.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000020#include "llvm/Analysis/CallGraph.h"
Chandler Carruth3251e812013-01-07 15:26:48 +000021#include "llvm/Analysis/CallGraphSCCPass.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000022#include "llvm/Analysis/LoopPass.h"
23#include "llvm/Analysis/RegionPass.h"
Chandler Carruthbda13492015-01-15 02:16:27 +000024#include "llvm/Analysis/TargetLibraryInfo.h"
Chandler Carrutha6a87b52015-01-31 03:43:40 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Chandler Carruthe2dc71d2014-01-13 07:38:24 +000026#include "llvm/Bitcode/BitcodeWriterPass.h"
David Blaikie461bf522018-04-11 18:49:37 +000027#include "llvm/CodeGen/CommandFlags.inc"
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +000028#include "llvm/CodeGen/TargetPassConfig.h"
Nico Weber0f38c602018-04-30 14:59:11 +000029#include "llvm/Config/llvm-config.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000030#include "llvm/IR/DataLayout.h"
Duncan P. N. Exon Smithde892282015-03-27 22:04:28 +000031#include "llvm/IR/DebugInfo.h"
Chandler Carruth8a5351f2014-01-12 11:10:32 +000032#include "llvm/IR/IRPrintingPasses.h"
Chandler Carruth4e728be2014-01-11 08:16:35 +000033#include "llvm/IR/LLVMContext.h"
Keno Fischer6f41c132015-12-04 21:56:46 +000034#include "llvm/IR/LegacyPassManager.h"
Chandler Carruthf7591dd2014-03-04 12:32:42 +000035#include "llvm/IR/LegacyPassNameParser.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000036#include "llvm/IR/Module.h"
Chandler Carruth56e13942014-01-13 09:26:24 +000037#include "llvm/IR/Verifier.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000038#include "llvm/IRReader/IRReader.h"
Chandler Carruth1decd562014-03-04 10:07:28 +000039#include "llvm/InitializePasses.h"
Jakub Staszak446991d2013-01-10 21:56:40 +000040#include "llvm/LinkAllIR.h"
Chandler Carruth90230c82013-01-19 08:03:47 +000041#include "llvm/LinkAllPasses.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000042#include "llvm/MC/SubtargetFeature.h"
David Greene08fc0d32010-01-05 01:30:32 +000043#include "llvm/Support/Debug.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000044#include "llvm/Support/FileSystem.h"
Craig Topper57ff1202015-04-01 05:32:04 +000045#include "llvm/Support/Host.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000046#include "llvm/Support/InitLLVM.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000047#include "llvm/Support/PluginLoader.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000048#include "llvm/Support/SourceMgr.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000049#include "llvm/Support/SystemUtils.h"
Nadav Rotemcbd9a192012-10-18 23:22:48 +000050#include "llvm/Support/TargetRegistry.h"
Nadav Rotem0873bea2012-10-24 17:23:50 +000051#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000052#include "llvm/Support/ToolOutputFile.h"
Adam Nemet47c0d492016-09-27 20:55:07 +000053#include "llvm/Support/YAMLTraits.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000054#include "llvm/Target/TargetMachine.h"
David Majnemer88019052016-07-28 21:04:31 +000055#include "llvm/Transforms/Coroutines.h"
Chandler Carruthb699f7b2016-08-17 02:56:20 +000056#include "llvm/Transforms/IPO/AlwaysInliner.h"
Rafael Espindola3d453ac2011-08-02 21:50:24 +000057#include "llvm/Transforms/IPO/PassManagerBuilder.h"
Keno Fischer6f41c132015-12-04 21:56:46 +000058#include "llvm/Transforms/Utils/Cloning.h"
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000059#include <algorithm>
Chandler Carruthf010c462012-12-04 10:44:52 +000060#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000061using namespace llvm;
Chandler Carruth4a760322014-01-13 03:08:40 +000062using namespace opt_tool;
Chris Lattner9d6e7eb2002-04-12 18:21:13 +000063
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000064// The OptimizationList is automatically populated with registered Passes by the
65// PassNameParser.
66//
Chris Lattner7f500f72006-08-27 22:07:01 +000067static cl::list<const PassInfo*, bool, PassNameParser>
68PassList(cl::desc("Optimizations available:"));
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000069
Chandler Carruth4e728be2014-01-11 08:16:35 +000070// 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.
74static cl::opt<std::string> PassPipeline(
75 "passes",
76 cl::desc("A textual description of the pass pipeline for optimizing"),
77 cl::Hidden);
78
Chris Lattnerc0ce68b2002-07-23 18:12:22 +000079// Other command line options...
Chris Lattnerfb1b3f12002-01-31 00:47:12 +000080//
Chris Lattner6c8103f2003-05-22 20:13:16 +000081static cl::opt<std::string>
Eric Christophera887ae42009-08-21 23:29:40 +000082InputFilename(cl::Positional, cl::desc("<input bitcode file>"),
Reid Spencerfd90dd52006-08-18 06:34:30 +000083 cl::init("-"), cl::value_desc("filename"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000084
Chris Lattner6c8103f2003-05-22 20:13:16 +000085static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000086OutputFilename("o", cl::desc("Override output filename"),
Dan Gohman86cbc1b2010-08-18 17:40:10 +000087 cl::value_desc("filename"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000088
89static cl::opt<bool>
Dan Gohmanbaa26392009-08-25 15:34:52 +000090Force("f", cl::desc("Enable binary output on terminals"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000091
92static cl::opt<bool>
93PrintEachXForm("p", cl::desc("Print module after each transformation"));
94
95static cl::opt<bool>
Chris Lattnerddd5b412003-02-26 20:00:41 +000096NoOutput("disable-output",
Gabor Greifa99be512007-07-05 17:07:56 +000097 cl::desc("Do not write result bitcode file"), cl::Hidden);
Chris Lattnerd70b68e2003-02-12 18:43:33 +000098
99static cl::opt<bool>
Duncan Sands81b0b642009-10-14 20:01:39 +0000100OutputAssembly("S", cl::desc("Write output as LLVM assembly"));
Daniel Dunbar8c042c22009-09-05 11:34:53 +0000101
102static cl::opt<bool>
Peter Collingbourned1504012016-12-16 00:26:30 +0000103 OutputThinLTOBC("thinlto-bc",
104 cl::desc("Write output as ThinLTO-ready bitcode"));
105
Teresa Johnsone3937752019-01-11 18:31:57 +0000106static cl::opt<bool>
107 SplitLTOUnit("thinlto-split-lto-unit",
108 cl::desc("Enable splitting of a ThinLTO LTOUnit"));
109
Teresa Johnson08d0e942017-03-23 19:47:39 +0000110static 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
Peter Collingbourned1504012016-12-16 00:26:30 +0000115static cl::opt<bool>
Vedant Kumaree68a6c2016-03-10 06:58:53 +0000116NoVerify("disable-verify", cl::desc("Do not run the verifier"), cl::Hidden);
Chris Lattnerf3bafc12003-02-12 18:45:08 +0000117
118static cl::opt<bool>
Reid Spencer74ed9972007-02-02 14:46:29 +0000119VerifyEach("verify-each", cl::desc("Verify after each transform"));
120
121static cl::opt<bool>
Teresa Johnson95078852016-04-19 15:48:30 +0000122 DisableDITypeMap("disable-debug-info-type-map",
123 cl::desc("Don't use a uniquing type map for debug info"));
124
125static cl::opt<bool>
Reid Spencer74ed9972007-02-02 14:46:29 +0000126StripDebug("strip-debug",
127 cl::desc("Strip debugger symbol info from translation unit"));
128
129static cl::opt<bool>
Vedant Kumar9e729a32018-06-05 00:56:08 +0000130 StripNamedMetadata("strip-named-metadata",
131 cl::desc("Strip module-level named metadata"));
132
133static cl::opt<bool> DisableInline("disable-inlining",
134 cl::desc("Do not run the inliner pass"));
Reid Spencer74ed9972007-02-02 14:46:29 +0000135
Eric Christophera887ae42009-08-21 23:29:40 +0000136static cl::opt<bool>
137DisableOptimizations("disable-opt",
Reid Spencer74ed9972007-02-02 14:46:29 +0000138 cl::desc("Do not run any optimization passes"));
139
Eric Christophera887ae42009-08-21 23:29:40 +0000140static cl::opt<bool>
Eric Christophera887ae42009-08-21 23:29:40 +0000141StandardLinkOpts("std-link-opts",
Daniel Dunbaradc82882009-07-17 18:09:39 +0000142 cl::desc("Include the standard link time optimizations"));
143
144static cl::opt<bool>
Gor Nishanove648a062016-08-05 16:27:33 +0000145OptLevelO0("O0",
146 cl::desc("Optimization level 0. Similar to clang -O0"));
147
148static cl::opt<bool>
Devang Patel2d7551c2008-09-16 22:25:14 +0000149OptLevelO1("O1",
Chandler Carruth8bc34342012-05-16 08:32:49 +0000150 cl::desc("Optimization level 1. Similar to clang -O1"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000151
152static cl::opt<bool>
153OptLevelO2("O2",
Chandler Carruth8bc34342012-05-16 08:32:49 +0000154 cl::desc("Optimization level 2. Similar to clang -O2"));
155
156static cl::opt<bool>
157OptLevelOs("Os",
158 cl::desc("Like -O2 with extra optimizations for size. Similar to clang -Os"));
159
160static cl::opt<bool>
161OptLevelOz("Oz",
162 cl::desc("Like -Os but reduces code size further. Similar to clang -Oz"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000163
164static cl::opt<bool>
165OptLevelO3("O3",
Chandler Carruth8bc34342012-05-16 08:32:49 +0000166 cl::desc("Optimization level 3. Similar to clang -O3"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000167
Tim Northover97c08262016-04-18 21:48:55 +0000168static cl::opt<unsigned>
169CodeGenOptLevel("codegen-opt-level",
170 cl::desc("Override optimization level for codegen hooks"));
171
Joe Groffe652b522012-04-17 23:05:48 +0000172static cl::opt<std::string>
173TargetTriple("mtriple", cl::desc("Override target triple for module"));
174
Devang Patel2d7551c2008-09-16 22:25:14 +0000175static cl::opt<bool>
176UnitAtATime("funit-at-a-time",
Rafael Espindola9ca2a9a2014-08-21 19:22:24 +0000177 cl::desc("Enable IPO. This corresponds to gcc's -funit-at-a-time"),
Duncan Sands34727662010-07-12 08:16:59 +0000178 cl::init(true));
Devang Patel2d7551c2008-09-16 22:25:14 +0000179
180static cl::opt<bool>
Hal Finkel435798e2013-08-28 18:33:10 +0000181DisableLoopUnrolling("disable-loop-unrolling",
182 cl::desc("Disable loop unrolling in all relevant passes"),
183 cl::init(false));
Arnold Schwaighoferdf9c9da2013-12-03 16:33:06 +0000184static cl::opt<bool>
185DisableLoopVectorization("disable-loop-vectorization",
186 cl::desc("Disable the loop vectorization pass"),
187 cl::init(false));
188
189static cl::opt<bool>
190DisableSLPVectorization("disable-slp-vectorization",
191 cl::desc("Disable the slp vectorization pass"),
192 cl::init(false));
193
Mehdi Aminie58bfc92016-04-12 21:35:18 +0000194static cl::opt<bool> EmitSummaryIndex("module-summary",
195 cl::desc("Emit module summary index"),
196 cl::init(false));
197
198static cl::opt<bool> EmitModuleHash("module-hash", cl::desc("Emit module hash"),
199 cl::init(false));
Hal Finkel435798e2013-08-28 18:33:10 +0000200
201static cl::opt<bool>
Devang Patel2d7551c2008-09-16 22:25:14 +0000202DisableSimplifyLibCalls("disable-simplify-libcalls",
Devang Patel442b1aa2008-09-17 16:01:39 +0000203 cl::desc("Disable simplify-libcalls"));
Devang Patel2d7551c2008-09-16 22:25:14 +0000204
205static cl::opt<bool>
Chris Lattner3153e4f2004-05-27 20:32:10 +0000206Quiet("q", cl::desc("Obsolete option"), cl::Hidden);
Chris Lattner5ff62e92002-07-22 02:10:13 +0000207
Reid Spencerec7eb452004-05-27 16:28:54 +0000208static cl::alias
209QuietA("quiet", cl::desc("Alias for -q"), cl::aliasopt(Quiet));
210
Reid Spencerfd90dd52006-08-18 06:34:30 +0000211static cl::opt<bool>
212AnalyzeOnly("analyze", cl::desc("Only perform analysis, no optimization"));
213
Vedant Kumar48c582c2018-01-23 20:43:50 +0000214static cl::opt<bool> EnableDebugify(
215 "enable-debugify",
216 cl::desc(
217 "Start the pipeline with debugify and end it with check-debugify"));
218
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000219static cl::opt<bool> DebugifyEach(
220 "debugify-each",
221 cl::desc(
222 "Start each pass with debugify and end it with check-debugify"));
223
Vedant Kumar499e3df2018-07-24 00:41:29 +0000224static cl::opt<std::string>
225 DebugifyExport("debugify-export",
226 cl::desc("Export per-pass debugify statistics to this file"),
227 cl::value_desc("filename"), cl::init(""));
228
Devang Patelf5f23002010-12-07 00:33:43 +0000229static cl::opt<bool>
Andrew Tricka41af7a2011-04-05 18:41:31 +0000230PrintBreakpoints("print-breakpoints-for-testing",
Devang Patelf5f23002010-12-07 00:33:43 +0000231 cl::desc("Print select breakpoints location for testing"));
232
Peter Collingbourne4f502782017-02-17 17:36:52 +0000233static cl::opt<std::string> ClDataLayout("data-layout",
234 cl::desc("data layout string to use"),
235 cl::value_desc("layout-string"),
236 cl::init(""));
Chris Lattnerd331cb32009-10-22 00:44:10 +0000237
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +0000238static cl::opt<bool> PreserveBitcodeUseListOrder(
239 "preserve-bc-uselistorder",
240 cl::desc("Preserve use-list order when writing LLVM bitcode."),
241 cl::init(true), cl::Hidden);
Reid Spencerfd90dd52006-08-18 06:34:30 +0000242
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +0000243static cl::opt<bool> PreserveAssemblyUseListOrder(
244 "preserve-ll-uselistorder",
245 cl::desc("Preserve use-list order when writing LLVM assembly."),
246 cl::init(false), cl::Hidden);
Devang Patelf5f23002010-12-07 00:33:43 +0000247
Keno Fischer6f41c132015-12-04 21:56:46 +0000248static cl::opt<bool>
249 RunTwice("run-twice",
250 cl::desc("Run all passes twice, re-using the same pass manager."),
251 cl::init(false), cl::Hidden);
252
Mehdi Amini2de99272016-03-10 01:28:54 +0000253static cl::opt<bool> DiscardValueNames(
254 "discard-value-names",
255 cl::desc("Discard names from Value (other than GlobalValue)."),
256 cl::init(false), cl::Hidden);
257
David Majnemer88019052016-07-28 21:04:31 +0000258static cl::opt<bool> Coroutines(
259 "enable-coroutines",
260 cl::desc("Enable coroutine passes."),
261 cl::init(false), cl::Hidden);
262
Adam Nemetf8cec992016-07-15 17:23:20 +0000263static cl::opt<bool> PassRemarksWithHotness(
264 "pass-remarks-with-hotness",
265 cl::desc("With PGO, include profile count in optimization remarks"),
266 cl::Hidden);
267
Brian Gesiake3305282017-06-30 23:14:53 +0000268static cl::opt<unsigned> PassRemarksHotnessThreshold(
269 "pass-remarks-hotness-threshold",
270 cl::desc("Minimum profile count required for an optimization remark to be output"),
271 cl::Hidden);
272
Adam Nemet47c0d492016-09-27 20:55:07 +0000273static cl::opt<std::string>
274 RemarksFilename("pass-remarks-output",
275 cl::desc("YAML output filename for pass remarks"),
276 cl::value_desc("filename"));
277
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000278class OptCustomPassManager : public legacy::PassManager {
Vedant Kumar499e3df2018-07-24 00:41:29 +0000279 DebugifyStatsMap DIStatsMap;
280
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000281public:
282 using super = legacy::PassManager;
283
284 void add(Pass *P) override {
Vedant Kumar499e3df2018-07-24 00:41:29 +0000285 // Wrap each pass with (-check)-debugify passes if requested, making
286 // exceptions for passes which shouldn't see -debugify instrumentation.
Vedant Kumarf66cfed2018-06-04 00:11:49 +0000287 bool WrapWithDebugify = DebugifyEach && !P->getAsImmutablePass() &&
288 !isIRPrintingPass(P) && !isBitcodeWriterPass(P);
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000289 if (!WrapWithDebugify) {
290 super::add(P);
291 return;
292 }
Vedant Kumar499e3df2018-07-24 00:41:29 +0000293
294 // Apply -debugify/-check-debugify before/after each pass and collect
295 // debug info loss statistics.
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000296 PassKind Kind = P->getPassKind();
Vedant Kumar499e3df2018-07-24 00:41:29 +0000297 StringRef Name = P->getPassName();
298
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000299 // TODO: Implement Debugify for BasicBlockPass, LoopPass.
300 switch (Kind) {
301 case PT_Function:
302 super::add(createDebugifyFunctionPass());
303 super::add(P);
Vedant Kumar499e3df2018-07-24 00:41:29 +0000304 super::add(createCheckDebugifyFunctionPass(true, Name, &DIStatsMap));
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000305 break;
306 case PT_Module:
307 super::add(createDebugifyModulePass());
308 super::add(P);
Vedant Kumar499e3df2018-07-24 00:41:29 +0000309 super::add(createCheckDebugifyModulePass(true, Name, &DIStatsMap));
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000310 break;
311 default:
312 super::add(P);
313 break;
314 }
315 }
Vedant Kumar499e3df2018-07-24 00:41:29 +0000316
317 const DebugifyStatsMap &getDebugifyStatsMap() const { return DIStatsMap; }
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000318};
319
Chandler Carruth417c5c12015-02-13 10:01:29 +0000320static inline void addPass(legacy::PassManagerBase &PM, Pass *P) {
Reid Spencer74ed9972007-02-02 14:46:29 +0000321 // Add the pass to the pass manager...
322 PM.add(P);
323
324 // If we are verifying all of the intermediate steps, add the verifier...
Duncan P. N. Exon Smitha60d4302015-03-19 22:24:17 +0000325 if (VerifyEach)
Duncan P. N. Exon Smith32791b02014-04-15 16:27:38 +0000326 PM.add(createVerifierPass());
Reid Spencer74ed9972007-02-02 14:46:29 +0000327}
328
Rafael Espindola9ca2a9a2014-08-21 19:22:24 +0000329/// This routine adds optimization passes based on selected optimization level,
330/// OptLevel.
Devang Patel2d7551c2008-09-16 22:25:14 +0000331///
332/// OptLevel - Optimization Level
Chandler Carruth417c5c12015-02-13 10:01:29 +0000333static void AddOptimizationPasses(legacy::PassManagerBase &MPM,
334 legacy::FunctionPassManager &FPM,
Justin Lebarae889d32016-04-27 19:08:24 +0000335 TargetMachine *TM, unsigned OptLevel,
336 unsigned SizeLevel) {
Vedant Kumard449fa82016-03-10 03:40:14 +0000337 if (!NoVerify || VerifyEach)
338 FPM.add(createVerifierPass()); // Verify that input is correct
Duncan Sandsa3e585d2011-12-07 17:14:20 +0000339
Chris Lattner52b288962011-05-22 00:21:33 +0000340 PassManagerBuilder Builder;
341 Builder.OptLevel = OptLevel;
Chandler Carruth8bc34342012-05-16 08:32:49 +0000342 Builder.SizeLevel = SizeLevel;
Devang Patel2d7551c2008-09-16 22:25:14 +0000343
Eli Friedman74733a72010-01-18 22:38:31 +0000344 if (DisableInline) {
345 // No inlining pass
Eli Friedman42d41fd2011-06-06 22:13:27 +0000346 } else if (OptLevel > 1) {
Dehao Chen287fe252017-03-21 19:55:36 +0000347 Builder.Inliner = createFunctionInliningPass(OptLevel, SizeLevel, false);
Eli Friedman74733a72010-01-18 22:38:31 +0000348 } else {
Chandler Carruthb699f7b2016-08-17 02:56:20 +0000349 Builder.Inliner = createAlwaysInlinerLegacyPass();
Eli Friedman74733a72010-01-18 22:38:31 +0000350 }
Chris Lattner52b288962011-05-22 00:21:33 +0000351 Builder.DisableUnitAtATime = !UnitAtATime;
Hal Finkel435798e2013-08-28 18:33:10 +0000352 Builder.DisableUnrollLoops = (DisableLoopUnrolling.getNumOccurrences() > 0) ?
353 DisableLoopUnrolling : OptLevel == 0;
Greg Bedwell0568ba62013-10-09 08:55:27 +0000354
Renato Golin07d94712013-12-05 21:20:02 +0000355 // This is final, unless there is a #pragma vectorize enable
356 if (DisableLoopVectorization)
357 Builder.LoopVectorize = false;
358 // If option wasn't forced via cmd line (-vectorize-loops, -loop-vectorize)
359 else if (!Builder.LoopVectorize)
360 Builder.LoopVectorize = OptLevel > 1 && SizeLevel < 2;
361
362 // When #pragma vectorize is on for SLP, do the same as above
Arnold Schwaighoferdf9c9da2013-12-03 16:33:06 +0000363 Builder.SLPVectorize =
364 DisableSLPVectorization ? false : OptLevel > 1 && SizeLevel < 2;
Hal Finkel435798e2013-08-28 18:33:10 +0000365
Justin Lebarae889d32016-04-27 19:08:24 +0000366 if (TM)
Stanislav Mekhanoshinbe4948c2017-01-26 16:49:08 +0000367 TM->adjustPassManager(Builder);
Justin Lebarae889d32016-04-27 19:08:24 +0000368
David Majnemer88019052016-07-28 21:04:31 +0000369 if (Coroutines)
370 addCoroutinePassesToExtensionPoints(Builder);
371
Chris Lattner52b288962011-05-22 00:21:33 +0000372 Builder.populateFunctionPassManager(FPM);
373 Builder.populateModulePassManager(MPM);
Devang Patel2d7551c2008-09-16 22:25:14 +0000374}
375
Chandler Carruth417c5c12015-02-13 10:01:29 +0000376static void AddStandardLinkPasses(legacy::PassManagerBase &PM) {
Chris Lattner52b288962011-05-22 00:21:33 +0000377 PassManagerBuilder Builder;
Rafael Espindola7b4eb022014-08-21 20:03:44 +0000378 Builder.VerifyInput = true;
Rafael Espindola7b4eb022014-08-21 20:03:44 +0000379 if (DisableOptimizations)
380 Builder.OptLevel = 0;
381
Rafael Espindola0b994a702014-08-21 13:35:30 +0000382 if (!DisableInline)
383 Builder.Inliner = createFunctionInliningPass();
384 Builder.populateLTOPassManager(PM);
Daniel Dunbaradc82882009-07-17 18:09:39 +0000385}
386
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000387//===----------------------------------------------------------------------===//
388// CodeGen-related helper functions.
389//
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000390
Benjamin Kramer0df4e222015-03-09 16:23:46 +0000391static CodeGenOpt::Level GetCodeGenOptLevel() {
Tim Northover97c08262016-04-18 21:48:55 +0000392 if (CodeGenOptLevel.getNumOccurrences())
393 return static_cast<CodeGenOpt::Level>(unsigned(CodeGenOptLevel));
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000394 if (OptLevelO1)
395 return CodeGenOpt::Less;
396 if (OptLevelO2)
397 return CodeGenOpt::Default;
398 if (OptLevelO3)
399 return CodeGenOpt::Aggressive;
400 return CodeGenOpt::None;
401}
402
403// Returns the TargetMachine instance or zero if no triple is provided.
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000404static TargetMachine* GetTargetMachine(Triple TheTriple, StringRef CPUStr,
Akira Hatanaka01461202015-05-23 01:14:08 +0000405 StringRef FeaturesStr,
406 const TargetOptions &Options) {
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000407 std::string Error;
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000408 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
409 Error);
Nadav Rotemb338d892013-01-01 08:00:32 +0000410 // Some modules don't specify a triple, and this is okay.
Eric Christopher60d20a82013-04-15 07:31:37 +0000411 if (!TheTarget) {
Craig Topper573faec2014-04-25 04:24:47 +0000412 return nullptr;
Eric Christopher60d20a82013-04-15 07:31:37 +0000413 }
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000414
Rafael Espindolaac8db592016-05-18 22:04:49 +0000415 return TheTarget->createTargetMachine(TheTriple.getTriple(), CPUStr,
416 FeaturesStr, Options, getRelocModel(),
Rafael Espindola9aafb852017-08-03 02:16:21 +0000417 getCodeModel(), GetCodeGenOptLevel());
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000418}
Chris Lattner0be41012002-02-01 04:54:11 +0000419
Sebastian Popbeaa95d2014-03-14 04:04:14 +0000420#ifdef LINK_POLLY_INTO_TOOLS
421namespace polly {
422void initializePollyPasses(llvm::PassRegistry &Registry);
423}
424#endif
425
Chris Lattnerc0ce68b2002-07-23 18:12:22 +0000426//===----------------------------------------------------------------------===//
427// main for opt
428//
Chris Lattner00950542001-06-06 20:29:01 +0000429int main(int argc, char **argv) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000430 InitLLVM X(argc, argv);
Dan Gohmand4c45432010-09-01 14:20:41 +0000431
David Greene08fc0d32010-01-05 01:30:32 +0000432 // Enable debug stream buffering.
433 EnableDebugBuffering = true;
434
Mehdi Amini8be77072016-04-14 21:59:01 +0000435 LLVMContext Context;
Andrew Tricka41af7a2011-04-05 18:41:31 +0000436
Nadav Rotem0873bea2012-10-24 17:23:50 +0000437 InitializeAllTargets();
438 InitializeAllTargetMCs();
Tobias Grosserdf462882014-06-13 16:12:08 +0000439 InitializeAllAsmPrinters();
Teresa Johnson8e04a1b2016-11-14 17:12:32 +0000440 InitializeAllAsmParsers();
Nadav Rotem0873bea2012-10-24 17:23:50 +0000441
Owen Anderson081c34b2010-10-19 17:21:58 +0000442 // Initialize passes
443 PassRegistry &Registry = *PassRegistry::getPassRegistry();
444 initializeCore(Registry);
David Majnemer88019052016-07-28 21:04:31 +0000445 initializeCoroutines(Registry);
Owen Anderson081c34b2010-10-19 17:21:58 +0000446 initializeScalarOpts(Registry);
Michael Gottesman24c48982013-01-28 01:35:51 +0000447 initializeObjCARCOpts(Registry);
Hal Finkelde5e5ec2012-02-01 03:51:43 +0000448 initializeVectorization(Registry);
Owen Anderson081c34b2010-10-19 17:21:58 +0000449 initializeIPO(Registry);
450 initializeAnalysis(Registry);
Owen Anderson081c34b2010-10-19 17:21:58 +0000451 initializeTransformUtils(Registry);
452 initializeInstCombine(Registry);
Craig Topper043b2352018-04-24 00:05:21 +0000453 initializeAggressiveInstCombine(Registry);
Owen Anderson081c34b2010-10-19 17:21:58 +0000454 initializeInstrumentation(Registry);
455 initializeTarget(Registry);
Quentin Colombet8048c442014-02-22 00:07:45 +0000456 // For codegen passes, only passes that do IR to IR transformation are
Tim Northover09da6b52014-04-17 18:22:47 +0000457 // supported.
Clement Courbet3d456012017-11-03 12:12:27 +0000458 initializeExpandMemCmpPassPass(Registry);
Ayman Musaeadb58f2017-05-15 11:30:54 +0000459 initializeScalarizeMaskedMemIntrinPass(Registry);
Quentin Colombet8048c442014-02-22 00:07:45 +0000460 initializeCodeGenPreparePass(Registry);
Robin Morissetcf165c32014-08-21 21:50:01 +0000461 initializeAtomicExpandPass(Registry);
Michael Kupersteinb3391842016-07-25 20:52:00 +0000462 initializeRewriteSymbolsLegacyPassPass(Registry);
Reid Klecknerf77571a2015-01-29 00:41:44 +0000463 initializeWinEHPreparePass(Registry);
Reid Klecknerf89d9b12015-02-18 23:17:41 +0000464 initializeDwarfEHPreparePass(Registry);
Ahmed Bougacha756714d2017-05-10 00:39:22 +0000465 initializeSafeStackLegacyPassPass(Registry);
Reid Kleckner827f2112015-07-09 21:48:40 +0000466 initializeSjLjEHPreparePass(Registry);
Michael Kupersteinf3f8fc62016-06-24 20:13:42 +0000467 initializePreISelIntrinsicLoweringLegacyPassPass(Registry);
Peter Collingbourne28f667b2016-05-19 04:38:56 +0000468 initializeGlobalMergePass(Registry);
Chandler Carruthfd5a8722018-01-22 22:05:25 +0000469 initializeIndirectBrExpandPassPass(Registry);
Martin Elshuber5e067bb2018-11-19 14:26:10 +0000470 initializeInterleavedLoadCombinePass(Registry);
Matthew Simpsond06ea8a2016-05-19 20:08:32 +0000471 initializeInterleavedAccessPass(Registry);
Hans Wennborg5765d842017-11-14 21:09:45 +0000472 initializeEntryExitInstrumenterPass(Registry);
473 initializePostInlineEntryExitInstrumenterPass(Registry);
Wei Mi302c35d2016-07-08 03:32:49 +0000474 initializeUnreachableBlockElimLegacyPassPass(Registry);
Amara Emerson0dd30f82017-05-10 09:42:49 +0000475 initializeExpandReductionsPass(Registry);
Heejin Ahna6e37da2018-05-31 22:02:34 +0000476 initializeWasmEHPreparePass(Registry);
Michael Krused9d01c92017-10-24 17:17:27 +0000477 initializeWriteBitcodePassPass(Registry);
Andrew Tricka41af7a2011-04-05 18:41:31 +0000478
Sebastian Popbeaa95d2014-03-14 04:04:14 +0000479#ifdef LINK_POLLY_INTO_TOOLS
480 polly::initializePollyPasses(Registry);
481#endif
482
Chris Lattner61db1a12009-10-22 00:46:41 +0000483 cl::ParseCommandLineOptions(argc, argv,
484 "llvm .bc -> .bc modular optimizer and analysis printer\n");
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000485
Tobias Grosser7593f342010-12-02 20:35:16 +0000486 if (AnalyzeOnly && NoOutput) {
487 errs() << argv[0] << ": analyze mode conflicts with no-output mode.\n";
488 return 1;
489 }
490
Chris Lattner61db1a12009-10-22 00:46:41 +0000491 SMDiagnostic Err;
Vikram S. Adve18fdfc42002-09-16 16:09:43 +0000492
Mehdi Amini2de99272016-03-10 01:28:54 +0000493 Context.setDiscardValueNames(DiscardValueNames);
Teresa Johnson95078852016-04-19 15:48:30 +0000494 if (!DisableDITypeMap)
495 Context.enableDebugTypeODRUniquing();
Mehdi Amini2de99272016-03-10 01:28:54 +0000496
Adam Nemetf8cec992016-07-15 17:23:20 +0000497 if (PassRemarksWithHotness)
Brian Gesiak8e8ec782017-06-30 18:13:59 +0000498 Context.setDiagnosticsHotnessRequested(true);
Adam Nemetf8cec992016-07-15 17:23:20 +0000499
Brian Gesiake3305282017-06-30 23:14:53 +0000500 if (PassRemarksHotnessThreshold)
501 Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
502
Reid Kleckner97ca9642017-09-23 01:03:17 +0000503 std::unique_ptr<ToolOutputFile> OptRemarkFile;
Adam Nemet47c0d492016-09-27 20:55:07 +0000504 if (RemarksFilename != "") {
505 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000506 OptRemarkFile =
507 llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
Adam Nemet47c0d492016-09-27 20:55:07 +0000508 if (EC) {
509 errs() << EC.message() << '\n';
510 return 1;
511 }
Mehdi Amini1bb4b122016-11-19 18:19:41 +0000512 Context.setDiagnosticsOutputFile(
Sam Elliott74a34d92017-08-20 01:30:45 +0000513 llvm::make_unique<yaml::Output>(OptRemarkFile->os()));
Adam Nemet47c0d492016-09-27 20:55:07 +0000514 }
515
Chris Lattner61db1a12009-10-22 00:46:41 +0000516 // Load the input module...
Adrian Prantl733fe2f2017-10-02 18:31:29 +0000517 std::unique_ptr<Module> M =
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000518 parseIRFile(InputFilename, Err, Context, !NoVerify, ClDataLayout);
Eric Christophera887ae42009-08-21 23:29:40 +0000519
Craig Topper32482232014-12-12 07:52:09 +0000520 if (!M) {
Chris Lattnerd8b7aa22011-10-16 04:47:35 +0000521 Err.print(argv[0], errs());
Chris Lattner61db1a12009-10-22 00:46:41 +0000522 return 1;
523 }
524
Duncan P. N. Exon Smithde892282015-03-27 22:04:28 +0000525 // Strip debug info before running the verifier.
526 if (StripDebug)
527 StripDebugInfo(*M);
528
Vedant Kumar9e729a32018-06-05 00:56:08 +0000529 // Erase module-level named metadata, if requested.
530 if (StripNamedMetadata) {
531 while (!M->named_metadata_empty()) {
532 NamedMDNode *NMD = &*M->named_metadata_begin();
533 M->eraseNamedMetadata(NMD);
534 }
535 }
Vedant Kumar701cfb82018-06-04 00:11:48 +0000536
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000537 // If we are supposed to override the target triple or data layout, do so now.
538 if (!TargetTriple.empty())
539 M->setTargetTriple(Triple::normalize(TargetTriple));
540
Duncan P. N. Exon Smithde892282015-03-27 22:04:28 +0000541 // Immediately run the verifier to catch any problems before starting up the
542 // pass pipelines. Otherwise we can crash on broken code during
543 // doInitialization().
544 if (!NoVerify && verifyModule(*M, &errs())) {
Duncan P. N. Exon Smith4e5fdbf2015-03-31 03:07:23 +0000545 errs() << argv[0] << ": " << InputFilename
546 << ": error: input module is broken!\n";
Duncan P. N. Exon Smithde892282015-03-27 22:04:28 +0000547 return 1;
548 }
549
Chris Lattner61db1a12009-10-22 00:46:41 +0000550 // Figure out what stream we are supposed to write to...
Reid Kleckner97ca9642017-09-23 01:03:17 +0000551 std::unique_ptr<ToolOutputFile> Out;
552 std::unique_ptr<ToolOutputFile> ThinLinkOut;
Dan Gohman4931b312010-08-18 17:42:59 +0000553 if (NoOutput) {
Dan Gohman86cbc1b2010-08-18 17:40:10 +0000554 if (!OutputFilename.empty())
555 errs() << "WARNING: The -o (output filename) option is ignored when\n"
Dan Gohman4931b312010-08-18 17:42:59 +0000556 "the --disable-output option is used.\n";
Dan Gohman86cbc1b2010-08-18 17:40:10 +0000557 } else {
558 // Default to standard output.
559 if (OutputFilename.empty())
560 OutputFilename = "-";
Chris Lattner61db1a12009-10-22 00:46:41 +0000561
Rafael Espindola8c968622014-08-25 18:16:47 +0000562 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000563 Out.reset(new ToolOutputFile(OutputFilename, EC, sys::fs::F_None));
Rafael Espindola8c968622014-08-25 18:16:47 +0000564 if (EC) {
565 errs() << EC.message() << '\n';
Dan Gohman86cbc1b2010-08-18 17:40:10 +0000566 return 1;
Chris Lattner00950542001-06-06 20:29:01 +0000567 }
Teresa Johnson08d0e942017-03-23 19:47:39 +0000568
569 if (!ThinLinkBitcodeFile.empty()) {
570 ThinLinkOut.reset(
Reid Kleckner97ca9642017-09-23 01:03:17 +0000571 new ToolOutputFile(ThinLinkBitcodeFile, EC, sys::fs::F_None));
Teresa Johnson08d0e942017-03-23 19:47:39 +0000572 if (EC) {
573 errs() << EC.message() << '\n';
574 return 1;
575 }
576 }
Chris Lattner61db1a12009-10-22 00:46:41 +0000577 }
Chris Lattner76d12292002-04-18 19:55:25 +0000578
Chandler Carruth7724e8e2015-02-01 10:11:22 +0000579 Triple ModuleTriple(M->getTargetTriple());
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000580 std::string CPUStr, FeaturesStr;
Chandler Carruth7724e8e2015-02-01 10:11:22 +0000581 TargetMachine *Machine = nullptr;
Akira Hatanaka01461202015-05-23 01:14:08 +0000582 const TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Akira Hatanakac17da712015-05-23 01:12:26 +0000583
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000584 if (ModuleTriple.getArch()) {
585 CPUStr = getCPUStr();
586 FeaturesStr = getFeaturesStr();
Akira Hatanaka01461202015-05-23 01:14:08 +0000587 Machine = GetTargetMachine(ModuleTriple, CPUStr, FeaturesStr, Options);
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000588 }
589
Chandler Carruth7724e8e2015-02-01 10:11:22 +0000590 std::unique_ptr<TargetMachine> TM(Machine);
591
Akira Hatanaka6f491352015-05-26 20:17:20 +0000592 // Override function attributes based on CPUStr, FeaturesStr, and command line
593 // flags.
594 setFunctionAttributes(CPUStr, FeaturesStr, *M);
Akira Hatanakae6f04942015-05-06 23:54:14 +0000595
Chris Lattner61db1a12009-10-22 00:46:41 +0000596 // If the output is set to be emitted to standard out, and standard out is a
597 // console, print out a warning message and refuse to do it. We don't
598 // impress anyone by spewing tons of binary goo to a terminal.
Dan Gohmanb56bf582010-01-17 17:47:24 +0000599 if (!Force && !NoOutput && !AnalyzeOnly && !OutputAssembly)
Dan Gohmand4c45432010-09-01 14:20:41 +0000600 if (CheckBitcodeOutputToConsole(Out->os(), !Quiet))
Chris Lattner61db1a12009-10-22 00:46:41 +0000601 NoOutput = true;
Dan Gohmanec080462009-09-11 20:46:33 +0000602
Teresa Johnsone3937752019-01-11 18:31:57 +0000603 if (OutputThinLTOBC)
604 M->addModuleFlag(Module::Error, "EnableSplitLTOUnit", SplitLTOUnit);
605
Chandler Carruth4a760322014-01-13 03:08:40 +0000606 if (PassPipeline.getNumOccurrences() > 0) {
607 OutputKind OK = OK_NoOutput;
608 if (!NoOutput)
Tim Shen2e378852017-06-01 01:02:12 +0000609 OK = OutputAssembly
610 ? OK_OutputAssembly
611 : (OutputThinLTOBC ? OK_OutputThinLTOBitcode : OK_OutputBitcode);
Chandler Carruth4a760322014-01-13 03:08:40 +0000612
Chandler Carruth1d9ab252014-01-20 11:34:08 +0000613 VerifierKind VK = VK_VerifyInAndOut;
614 if (NoVerify)
615 VK = VK_NoVerifier;
616 else if (VerifyEach)
617 VK = VK_VerifyEachPass;
618
Chandler Carruth4e728be2014-01-11 08:16:35 +0000619 // The user has asked to use the new pass manager and provided a pipeline
620 // string. Hand off the rest of the functionality to the new code for that
621 // layer.
Tim Shen2e378852017-06-01 01:02:12 +0000622 return runPassPipeline(argv[0], *M, TM.get(), Out.get(), ThinLinkOut.get(),
Sam Elliott74a34d92017-08-20 01:30:45 +0000623 OptRemarkFile.get(), PassPipeline, OK, VK,
624 PreserveAssemblyUseListOrder,
Teresa Johnson3143f332016-08-12 13:53:02 +0000625 PreserveBitcodeUseListOrder, EmitSummaryIndex,
Vedant Kumarb8c067b2018-02-15 21:14:36 +0000626 EmitModuleHash, EnableDebugify)
Chandler Carruth4e728be2014-01-11 08:16:35 +0000627 ? 0
628 : 1;
Chandler Carruth4a760322014-01-13 03:08:40 +0000629 }
Chandler Carruth4e728be2014-01-11 08:16:35 +0000630
Chris Lattner61db1a12009-10-22 00:46:41 +0000631 // Create a PassManager to hold and optimize the collection of passes we are
Chris Lattner2a66aca2011-02-18 22:13:01 +0000632 // about to build.
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000633 OptCustomPassManager Passes;
634 bool AddOneTimeDebugifyPasses = EnableDebugify && !DebugifyEach;
Chris Lattner00950542001-06-06 20:29:01 +0000635
Chris Lattner2a66aca2011-02-18 22:13:01 +0000636 // Add an appropriate TargetLibraryInfo pass for the module's triple.
Chandler Carruth7724e8e2015-02-01 10:11:22 +0000637 TargetLibraryInfoImpl TLII(ModuleTriple);
Andrew Tricka41af7a2011-04-05 18:41:31 +0000638
Chris Lattner188a7e02011-02-18 22:34:03 +0000639 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
640 if (DisableSimplifyLibCalls)
Chandler Carruth6f409cb2015-01-24 02:06:09 +0000641 TLII.disableAllFunctions();
642 Passes.add(new TargetLibraryInfoWrapperPass(TLII));
Andrew Tricka41af7a2011-04-05 18:41:31 +0000643
Chandler Carruthaeef83c2013-01-07 01:37:14 +0000644 // Add internal analysis passes from the target machine.
Chandler Carruth276f4052015-02-01 12:26:09 +0000645 Passes.add(createTargetTransformInfoWrapperPass(TM ? TM->getTargetIRAnalysis()
646 : TargetIRAnalysis()));
Nadav Rotemcbd9a192012-10-18 23:22:48 +0000647
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000648 if (AddOneTimeDebugifyPasses)
649 Passes.add(createDebugifyModulePass());
Vedant Kumar48c582c2018-01-23 20:43:50 +0000650
Chandler Carruth417c5c12015-02-13 10:01:29 +0000651 std::unique_ptr<legacy::FunctionPassManager> FPasses;
Gor Nishanove648a062016-08-05 16:27:33 +0000652 if (OptLevelO0 || OptLevelO1 || OptLevelO2 || OptLevelOs || OptLevelOz ||
653 OptLevelO3) {
Chandler Carruth417c5c12015-02-13 10:01:29 +0000654 FPasses.reset(new legacy::FunctionPassManager(M.get()));
Chandler Carruth19372332015-01-31 11:17:59 +0000655 FPasses->add(createTargetTransformInfoWrapperPass(
Chandler Carruth276f4052015-02-01 12:26:09 +0000656 TM ? TM->getTargetIRAnalysis() : TargetIRAnalysis()));
Chris Lattner61db1a12009-10-22 00:46:41 +0000657 }
Reid Spencer1ef8bda2004-12-30 05:36:08 +0000658
Devang Patelf5f23002010-12-07 00:33:43 +0000659 if (PrintBreakpoints) {
660 // Default to standard output.
661 if (!Out) {
662 if (OutputFilename.empty())
663 OutputFilename = "-";
Andrew Tricka41af7a2011-04-05 18:41:31 +0000664
Rafael Espindola8c968622014-08-25 18:16:47 +0000665 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000666 Out = llvm::make_unique<ToolOutputFile>(OutputFilename, EC,
667 sys::fs::F_None);
Rafael Espindola8c968622014-08-25 18:16:47 +0000668 if (EC) {
669 errs() << EC.message() << '\n';
Devang Patelf5f23002010-12-07 00:33:43 +0000670 return 1;
671 }
672 }
Eli Benderskya0ea8fa2014-02-12 16:48:02 +0000673 Passes.add(createBreakpointPrinter(Out->os()));
Devang Patelf5f23002010-12-07 00:33:43 +0000674 NoOutput = true;
675 }
676
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +0000677 if (TM) {
Matthias Braun9385cf12017-10-12 22:57:28 +0000678 // FIXME: We should dyn_cast this when supported.
679 auto &LTM = static_cast<LLVMTargetMachine &>(*TM);
680 Pass *TPC = LTM.createPassConfig(Passes);
681 Passes.add(TPC);
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +0000682 }
683
Chris Lattner61db1a12009-10-22 00:46:41 +0000684 // Create a new optimization pass for each one specified on the command line
685 for (unsigned i = 0; i < PassList.size(); ++i) {
Chris Lattner61db1a12009-10-22 00:46:41 +0000686 if (StandardLinkOpts &&
687 StandardLinkOpts.getPosition() < PassList.getPosition(i)) {
Daniel Dunbaradc82882009-07-17 18:09:39 +0000688 AddStandardLinkPasses(Passes);
689 StandardLinkOpts = false;
Eric Christophera887ae42009-08-21 23:29:40 +0000690 }
Daniel Dunbaradc82882009-07-17 18:09:39 +0000691
Gor Nishanove648a062016-08-05 16:27:33 +0000692 if (OptLevelO0 && OptLevelO0.getPosition() < PassList.getPosition(i)) {
693 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
694 OptLevelO0 = false;
695 }
696
Chris Lattner61db1a12009-10-22 00:46:41 +0000697 if (OptLevelO1 && OptLevelO1.getPosition() < PassList.getPosition(i)) {
Justin Lebarae889d32016-04-27 19:08:24 +0000698 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
Chris Lattner61db1a12009-10-22 00:46:41 +0000699 OptLevelO1 = false;
Daniel Dunbaradc82882009-07-17 18:09:39 +0000700 }
Devang Patel2d7551c2008-09-16 22:25:14 +0000701
Chris Lattner61db1a12009-10-22 00:46:41 +0000702 if (OptLevelO2 && OptLevelO2.getPosition() < PassList.getPosition(i)) {
Justin Lebarae889d32016-04-27 19:08:24 +0000703 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
Chris Lattner61db1a12009-10-22 00:46:41 +0000704 OptLevelO2 = false;
Daniel Dunbaradc82882009-07-17 18:09:39 +0000705 }
Devang Patel2d7551c2008-09-16 22:25:14 +0000706
Chandler Carruth8bc34342012-05-16 08:32:49 +0000707 if (OptLevelOs && OptLevelOs.getPosition() < PassList.getPosition(i)) {
Justin Lebarae889d32016-04-27 19:08:24 +0000708 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
Chandler Carruth8bc34342012-05-16 08:32:49 +0000709 OptLevelOs = false;
710 }
711
712 if (OptLevelOz && OptLevelOz.getPosition() < PassList.getPosition(i)) {
Justin Lebarae889d32016-04-27 19:08:24 +0000713 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
Chandler Carruth8bc34342012-05-16 08:32:49 +0000714 OptLevelOz = false;
715 }
716
Chris Lattner61db1a12009-10-22 00:46:41 +0000717 if (OptLevelO3 && OptLevelO3.getPosition() < PassList.getPosition(i)) {
Justin Lebarae889d32016-04-27 19:08:24 +0000718 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
Chris Lattner61db1a12009-10-22 00:46:41 +0000719 OptLevelO3 = false;
Daniel Dunbaradc82882009-07-17 18:09:39 +0000720 }
Devang Patel2d7551c2008-09-16 22:25:14 +0000721
Chris Lattner61db1a12009-10-22 00:46:41 +0000722 const PassInfo *PassInf = PassList[i];
Craig Topper573faec2014-04-25 04:24:47 +0000723 Pass *P = nullptr;
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +0000724 if (PassInf->getNormalCtor())
Chris Lattner61db1a12009-10-22 00:46:41 +0000725 P = PassInf->getNormalCtor()();
726 else
727 errs() << argv[0] << ": cannot create pass: "
728 << PassInf->getPassName() << "\n";
729 if (P) {
Benjamin Kramer3460f222010-02-18 12:57:05 +0000730 PassKind Kind = P->getPassKind();
Chris Lattner61db1a12009-10-22 00:46:41 +0000731 addPass(Passes, P);
732
733 if (AnalyzeOnly) {
Benjamin Kramer3460f222010-02-18 12:57:05 +0000734 switch (Kind) {
Chris Lattner476e9bd2010-01-22 06:03:06 +0000735 case PT_BasicBlock:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000736 Passes.add(createBasicBlockPassPrinter(PassInf, Out->os(), Quiet));
Chris Lattner476e9bd2010-01-22 06:03:06 +0000737 break;
Tobias Grosser65513602010-10-20 01:54:44 +0000738 case PT_Region:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000739 Passes.add(createRegionPassPrinter(PassInf, Out->os(), Quiet));
Tobias Grosser65513602010-10-20 01:54:44 +0000740 break;
Chris Lattner476e9bd2010-01-22 06:03:06 +0000741 case PT_Loop:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000742 Passes.add(createLoopPassPrinter(PassInf, Out->os(), Quiet));
Chris Lattner476e9bd2010-01-22 06:03:06 +0000743 break;
744 case PT_Function:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000745 Passes.add(createFunctionPassPrinter(PassInf, Out->os(), Quiet));
Chris Lattner476e9bd2010-01-22 06:03:06 +0000746 break;
747 case PT_CallGraphSCC:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000748 Passes.add(createCallGraphPassPrinter(PassInf, Out->os(), Quiet));
Chris Lattner476e9bd2010-01-22 06:03:06 +0000749 break;
750 default:
Eli Bendersky8ed971b2014-02-10 23:34:23 +0000751 Passes.add(createModulePassPrinter(PassInf, Out->os(), Quiet));
Chris Lattner476e9bd2010-01-22 06:03:06 +0000752 break;
753 }
Chris Lattner61db1a12009-10-22 00:46:41 +0000754 }
Devang Patel2d7551c2008-09-16 22:25:14 +0000755 }
756
Chris Lattner61db1a12009-10-22 00:46:41 +0000757 if (PrintEachXForm)
Duncan P. N. Exon Smith8d61ee92015-04-15 03:14:06 +0000758 Passes.add(
759 createPrintModulePass(errs(), "", PreserveAssemblyUseListOrder));
Chris Lattnerfb1b3f12002-01-31 00:47:12 +0000760 }
Chris Lattner61db1a12009-10-22 00:46:41 +0000761
Chris Lattner61db1a12009-10-22 00:46:41 +0000762 if (StandardLinkOpts) {
763 AddStandardLinkPasses(Passes);
764 StandardLinkOpts = false;
765 }
766
Gor Nishanove648a062016-08-05 16:27:33 +0000767 if (OptLevelO0)
768 AddOptimizationPasses(Passes, *FPasses, TM.get(), 0, 0);
769
Chris Lattner61db1a12009-10-22 00:46:41 +0000770 if (OptLevelO1)
Justin Lebarae889d32016-04-27 19:08:24 +0000771 AddOptimizationPasses(Passes, *FPasses, TM.get(), 1, 0);
Chris Lattner61db1a12009-10-22 00:46:41 +0000772
773 if (OptLevelO2)
Justin Lebarae889d32016-04-27 19:08:24 +0000774 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 0);
Chandler Carruth8bc34342012-05-16 08:32:49 +0000775
776 if (OptLevelOs)
Justin Lebarae889d32016-04-27 19:08:24 +0000777 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 1);
Chandler Carruth8bc34342012-05-16 08:32:49 +0000778
779 if (OptLevelOz)
Justin Lebarae889d32016-04-27 19:08:24 +0000780 AddOptimizationPasses(Passes, *FPasses, TM.get(), 2, 2);
Chris Lattner61db1a12009-10-22 00:46:41 +0000781
782 if (OptLevelO3)
Justin Lebarae889d32016-04-27 19:08:24 +0000783 AddOptimizationPasses(Passes, *FPasses, TM.get(), 3, 0);
Chris Lattner61db1a12009-10-22 00:46:41 +0000784
Patrik Hagglundbed36c42016-06-15 10:32:00 +0000785 if (FPasses) {
Chris Lattner3e8984a2011-05-22 06:44:19 +0000786 FPasses->doInitialization();
Craig Topper0ea6f982014-12-12 07:52:11 +0000787 for (Function &F : *M)
788 FPasses->run(F);
Chris Lattner3e8984a2011-05-22 06:44:19 +0000789 FPasses->doFinalization();
790 }
Chris Lattner61db1a12009-10-22 00:46:41 +0000791
792 // Check that the module is well formed on completion of optimization
Duncan P. N. Exon Smitha60d4302015-03-19 22:24:17 +0000793 if (!NoVerify && !VerifyEach)
Chris Lattner61db1a12009-10-22 00:46:41 +0000794 Passes.add(createVerifierPass());
795
Vedant Kumarb12dd1f2018-05-15 00:29:27 +0000796 if (AddOneTimeDebugifyPasses)
797 Passes.add(createCheckDebugifyModulePass(false));
Vedant Kumar48c582c2018-01-23 20:43:50 +0000798
Keno Fischer6f41c132015-12-04 21:56:46 +0000799 // In run twice mode, we want to make sure the output is bit-by-bit
800 // equivalent if we run the pass manager again, so setup two buffers and
801 // a stream to write to them. Note that llc does something similar and it
802 // may be worth to abstract this out in the future.
803 SmallVector<char, 0> Buffer;
Roman Tereshin9899cf02018-04-13 21:23:11 +0000804 SmallVector<char, 0> FirstRunBuffer;
Keno Fischer6f41c132015-12-04 21:56:46 +0000805 std::unique_ptr<raw_svector_ostream> BOS;
Keno Fischer357108c2015-12-05 00:06:37 +0000806 raw_ostream *OS = nullptr;
Keno Fischer6f41c132015-12-04 21:56:46 +0000807
Dan Gohman4931b312010-08-18 17:42:59 +0000808 // Write bitcode or assembly to the output as the last step...
Chris Lattner61db1a12009-10-22 00:46:41 +0000809 if (!NoOutput && !AnalyzeOnly) {
Keno Fischer357108c2015-12-05 00:06:37 +0000810 assert(Out);
811 OS = &Out->os();
812 if (RunTwice) {
813 BOS = make_unique<raw_svector_ostream>(Buffer);
814 OS = BOS.get();
815 }
Mehdi Aminibd3bdfc2016-04-13 17:20:10 +0000816 if (OutputAssembly) {
817 if (EmitSummaryIndex)
818 report_fatal_error("Text output is incompatible with -module-summary");
819 if (EmitModuleHash)
820 report_fatal_error("Text output is incompatible with -module-hash");
Keno Fischer6f41c132015-12-04 21:56:46 +0000821 Passes.add(createPrintModulePass(*OS, "", PreserveAssemblyUseListOrder));
Peter Collingbourned1504012016-12-16 00:26:30 +0000822 } else if (OutputThinLTOBC)
Teresa Johnson08d0e942017-03-23 19:47:39 +0000823 Passes.add(createWriteThinLTOBitcodePass(
824 *OS, ThinLinkOut ? &ThinLinkOut->os() : nullptr));
Peter Collingbourned1504012016-12-16 00:26:30 +0000825 else
Mehdi Aminie58bfc92016-04-12 21:35:18 +0000826 Passes.add(createBitcodeWriterPass(*OS, PreserveBitcodeUseListOrder,
827 EmitSummaryIndex, EmitModuleHash));
Chris Lattner61db1a12009-10-22 00:46:41 +0000828 }
829
Andrew Trickce969022011-04-05 18:54:36 +0000830 // Before executing passes, print the final values of the LLVM options.
831 cl::PrintOptionValues();
832
Roman Tereshin883750c2018-04-13 21:22:24 +0000833 if (!RunTwice) {
834 // Now that we have all of the passes ready, run them.
835 Passes.run(*M);
836 } else {
837 // If requested, run all passes twice with the same pass manager to catch
838 // bugs caused by persistent state in the passes.
Rafael Espindola22b77242018-02-14 19:50:40 +0000839 std::unique_ptr<Module> M2(CloneModule(*M));
Roman Tereshin883750c2018-04-13 21:22:24 +0000840 // Run all passes on the original module first, so the second run processes
841 // the clone to catch CloneModule bugs.
842 Passes.run(*M);
Roman Tereshin9899cf02018-04-13 21:23:11 +0000843 FirstRunBuffer = Buffer;
Rafael Espindola22b77242018-02-14 19:50:40 +0000844 Buffer.clear();
Keno Fischer36873822015-12-05 01:38:12 +0000845
Roman Tereshin883750c2018-04-13 21:22:24 +0000846 Passes.run(*M2);
Keno Fischer36873822015-12-05 01:38:12 +0000847
Roman Tereshin883750c2018-04-13 21:22:24 +0000848 // Compare the two outputs and make sure they're the same
Keno Fischer357108c2015-12-05 00:06:37 +0000849 assert(Out);
Roman Tereshin9899cf02018-04-13 21:23:11 +0000850 if (Buffer.size() != FirstRunBuffer.size() ||
851 (memcmp(Buffer.data(), FirstRunBuffer.data(), Buffer.size()) != 0)) {
852 errs()
853 << "Running the pass manager twice changed the output.\n"
854 "Writing the result of the second run to the specified output.\n"
855 "To generate the one-run comparison binary, just run without\n"
856 "the compile-twice option\n";
Keno Fischer6f41c132015-12-04 21:56:46 +0000857 Out->os() << BOS->str();
858 Out->keep();
Sam Elliott74a34d92017-08-20 01:30:45 +0000859 if (OptRemarkFile)
860 OptRemarkFile->keep();
Keno Fischer6f41c132015-12-04 21:56:46 +0000861 return 1;
862 }
863 Out->os() << BOS->str();
864 }
865
Vedant Kumar499e3df2018-07-24 00:41:29 +0000866 if (DebugifyEach && !DebugifyExport.empty())
867 exportDebugifyStats(DebugifyExport, Passes.getDebugifyStatsMap());
868
Dan Gohmand5826a32010-08-20 01:07:01 +0000869 // Declare success.
Devang Patelf5f23002010-12-07 00:33:43 +0000870 if (!NoOutput || PrintBreakpoints)
Dan Gohmand5826a32010-08-20 01:07:01 +0000871 Out->keep();
872
Sam Elliott74a34d92017-08-20 01:30:45 +0000873 if (OptRemarkFile)
874 OptRemarkFile->keep();
Adam Nemet47c0d492016-09-27 20:55:07 +0000875
Teresa Johnson08d0e942017-03-23 19:47:39 +0000876 if (ThinLinkOut)
877 ThinLinkOut->keep();
878
Chris Lattner61db1a12009-10-22 00:46:41 +0000879 return 0;
Chris Lattner00950542001-06-06 20:29:01 +0000880}