blob: 2329fb3e87c973558766b2bb6e538d2d359bc2f4 [file] [log] [blame]
Chris Lattner5b836c42003-06-20 15:49:04 +00001//===-- llc.cpp - Implement the LLVM Native Code Generator ----------------===//
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 Lattnere737c7a2001-09-07 22:20:50 +00009//
Brian Gaekee40eae72004-03-16 21:47:20 +000010// This is the llc code generator driver. It provides a convenient
Misha Brukman3da94ae2005-04-22 00:00:37 +000011// command-line interface for generating native assembly-language code
Gabor Greifa99be512007-07-05 17:07:56 +000012// or C code, given LLVM bitcode.
Chris Lattnere737c7a2001-09-07 22:20:50 +000013//
Chris Lattnerb79757c2001-10-04 01:40:53 +000014//===----------------------------------------------------------------------===//
Vikram S. Advecb465fc2001-07-21 12:42:29 +000015
Benjamin Kramerd59c5f92015-03-01 21:28:53 +000016#include "llvm/ADT/STLExtras.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000017#include "llvm/ADT/Triple.h"
Chandler Carruthbda13492015-01-15 02:16:27 +000018#include "llvm/Analysis/TargetLibraryInfo.h"
David Blaikie461bf522018-04-11 18:49:37 +000019#include "llvm/CodeGen/CommandFlags.inc"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000020#include "llvm/CodeGen/LinkAllAsmWriterComponents.h"
21#include "llvm/CodeGen/LinkAllCodegenComponents.h"
Alex Lorenz61aecc82015-05-27 18:02:19 +000022#include "llvm/CodeGen/MIRParser/MIRParser.h"
Matthias Braunbbeb3ea2016-05-10 01:32:44 +000023#include "llvm/CodeGen/MachineFunctionPass.h"
Matthias Braun3c559a02016-05-10 02:09:32 +000024#include "llvm/CodeGen/MachineModuleInfo.h"
Matthias Braun6a6190d2016-05-10 03:21:59 +000025#include "llvm/CodeGen/TargetPassConfig.h"
David Blaikiee3a9b4c2017-11-17 01:07:10 +000026#include "llvm/CodeGen/TargetSubtargetInfo.h"
Yaxun Liu7c2d0492018-01-30 22:32:39 +000027#include "llvm/IR/AutoUpgrade.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000028#include "llvm/IR/DataLayout.h"
Renato Golin3b0d3772016-05-16 14:28:02 +000029#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/DiagnosticPrinter.h"
Chandler Carruth9f20a4c2014-01-13 08:04:33 +000031#include "llvm/IR/IRPrintingPasses.h"
32#include "llvm/IR/LLVMContext.h"
Chandler Carruth417c5c12015-02-13 10:01:29 +000033#include "llvm/IR/LegacyPassManager.h"
Chandler Carruth0b8c9a82013-01-02 11:36:10 +000034#include "llvm/IR/Module.h"
Duncan P. N. Exon Smithde892282015-03-27 22:04:28 +000035#include "llvm/IR/Verifier.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000036#include "llvm/IRReader/IRReader.h"
Evan Chengab8be962011-06-29 01:14:12 +000037#include "llvm/MC/SubtargetFeature.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000038#include "llvm/Pass.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000039#include "llvm/Support/CommandLine.h"
David Greenec58d01b2010-01-05 01:30:21 +000040#include "llvm/Support/Debug.h"
Benjamin Kramer7259f142014-04-29 23:26:49 +000041#include "llvm/Support/FileSystem.h"
David Greene71847812009-07-14 20:18:05 +000042#include "llvm/Support/FormattedStream.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000043#include "llvm/Support/Host.h"
Rui Ueyama0b9d56a2018-04-13 18:26:06 +000044#include "llvm/Support/InitLLVM.h"
Chris Lattnerc30598b2006-12-06 01:18:01 +000045#include "llvm/Support/ManagedStatic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000046#include "llvm/Support/PluginLoader.h"
Chandler Carruth7fc162f2013-03-26 02:25:37 +000047#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000048#include "llvm/Support/TargetRegistry.h"
49#include "llvm/Support/TargetSelect.h"
Chandler Carruthf010c462012-12-04 10:44:52 +000050#include "llvm/Support/ToolOutputFile.h"
Jonas Devlieghere30429212018-06-23 16:51:10 +000051#include "llvm/Support/WithColor.h"
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +000052#include "llvm/Target/TargetMachine.h"
Keno Fischer6f41c132015-12-04 21:56:46 +000053#include "llvm/Transforms/Utils/Cloning.h"
Reid Spencer86f42bd2004-07-04 12:20:55 +000054#include <memory>
Brian Gaeked0fde302003-11-11 22:41:34 +000055using namespace llvm;
56
Vikram S. Adve7d0ba022002-09-16 16:35:34 +000057// General options for llc. Other pass-specific options are specified
58// within the corresponding llc passes, and target-specific options
59// and back-end code generation options are specified with the target machine.
Misha Brukman3da94ae2005-04-22 00:00:37 +000060//
Chris Lattnerb5881f12003-04-25 05:26:11 +000061static cl::opt<std::string>
Gabor Greifa99be512007-07-05 17:07:56 +000062InputFilename(cl::Positional, cl::desc("<input bitcode>"), cl::init("-"));
Chris Lattner5ff62e92002-07-22 02:10:13 +000063
Chris Lattnerb5881f12003-04-25 05:26:11 +000064static cl::opt<std::string>
Matthias Braunf6326272017-06-06 20:06:57 +000065InputLanguage("x", cl::desc("Input language ('ir' or 'mir')"));
66
67static cl::opt<std::string>
Chris Lattner5ff62e92002-07-22 02:10:13 +000068OutputFilename("o", cl::desc("Output filename"), cl::value_desc("filename"));
69
Peter Collingbourne9ffe0732018-05-21 20:16:41 +000070static cl::opt<std::string>
71 SplitDwarfOutputFile("split-dwarf-output",
72 cl::desc(".dwo output filename"),
73 cl::value_desc("filename"));
74
Jakob Stoklund Olesen88209282012-11-30 21:42:47 +000075static cl::opt<unsigned>
76TimeCompilations("time-compilations", cl::Hidden, cl::init(1u),
77 cl::value_desc("N"),
78 cl::desc("Repeat compilation N times for timing"));
79
Rafael Espindola9f5066c2014-02-21 03:13:54 +000080static cl::opt<bool>
81NoIntegratedAssembler("no-integrated-as", cl::Hidden,
82 cl::desc("Disable integrated assembler"));
83
Nirav Daveaee0f142016-07-11 12:42:14 +000084static cl::opt<bool>
Nirav Davedcf00532016-07-13 14:20:41 +000085 PreserveComments("preserve-as-comments", cl::Hidden,
Nirav Dave72d33ec2016-07-12 15:32:36 +000086 cl::desc("Preserve Comments in outputted assembly"),
87 cl::init(true));
Nirav Daveaee0f142016-07-11 12:42:14 +000088
Evan Cheng712e80e2009-05-04 23:05:19 +000089// Determine optimization level.
Bill Wendling98a366d2009-04-29 23:29:43 +000090static cl::opt<char>
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000091OptLevel("O",
Evan Cheng712e80e2009-05-04 23:05:19 +000092 cl::desc("Optimization level. [-O0, -O1, -O2, or -O3] "
93 "(default = '-O2')"),
Bill Wendlingbe8cc2a2009-04-29 00:15:41 +000094 cl::Prefix,
95 cl::ZeroOrMore,
Bill Wendling98a366d2009-04-29 23:29:43 +000096 cl::init(' '));
Chris Lattner178e0c42005-11-08 02:12:17 +000097
Chris Lattnerf33b86632005-12-16 04:59:57 +000098static cl::opt<std::string>
Chris Lattnerbe193832005-12-16 05:19:55 +000099TargetTriple("mtriple", cl::desc("Override target triple for module"));
Chris Lattner178e0c42005-11-08 02:12:17 +0000100
David Blaikie9c1b0af2017-04-21 23:35:26 +0000101static cl::opt<std::string> SplitDwarfFile(
102 "split-dwarf-file",
103 cl::desc(
104 "Specify the name of the .dwo file to encode in the DWARF output"));
105
Eric Christopher9a379862014-05-21 21:05:05 +0000106static cl::opt<bool> NoVerify("disable-verify", cl::Hidden,
107 cl::desc("Do not verify input module"));
Reid Spencer4418c2b2005-07-28 02:25:30 +0000108
Eric Christopher9a379862014-05-21 21:05:05 +0000109static cl::opt<bool> DisableSimplifyLibCalls("disable-simplify-libcalls",
110 cl::desc("Disable simplify-libcalls"));
Chad Rosier35907e92012-08-21 16:15:24 +0000111
Eric Christopherd1b5bda2014-05-21 21:05:09 +0000112static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
113 cl::desc("Show encoding in .s output"));
114
115static cl::opt<bool> EnableDwarfDirectory(
116 "enable-dwarf-directory", cl::Hidden,
117 cl::desc("Use .file directives with an explicit directory."));
118
119static cl::opt<bool> AsmVerbose("asm-verbose",
120 cl::desc("Add comments to directives."),
121 cl::init(true));
122
Keno Fischer6f41c132015-12-04 21:56:46 +0000123static cl::opt<bool>
124 CompileTwice("compile-twice", cl::Hidden,
125 cl::desc("Run everything twice, re-using the same pass "
Sanjay Patel322ee9e2015-12-07 19:21:39 +0000126 "manager and verify the result is the same."),
Keno Fischer6f41c132015-12-04 21:56:46 +0000127 cl::init(false));
128
Mehdi Amini2de99272016-03-10 01:28:54 +0000129static cl::opt<bool> DiscardValueNames(
130 "discard-value-names",
131 cl::desc("Discard names from Value (other than GlobalValue)."),
132 cl::init(false), cl::Hidden);
133
Saleem Abdulrasool50116a22017-01-05 05:56:39 +0000134static cl::list<std::string> IncludeDirs("I", cl::desc("include search path"));
135
Adam Nemet3e426982017-01-25 23:55:59 +0000136static cl::opt<bool> PassRemarksWithHotness(
137 "pass-remarks-with-hotness",
138 cl::desc("With PGO, include profile count in optimization remarks"),
139 cl::Hidden);
140
Brian Gesiake3305282017-06-30 23:14:53 +0000141static cl::opt<unsigned> PassRemarksHotnessThreshold(
142 "pass-remarks-hotness-threshold",
143 cl::desc("Minimum profile count required for an optimization remark to be output"),
144 cl::Hidden);
145
Adam Nemetc8168e72017-01-26 00:39:51 +0000146static cl::opt<std::string>
147 RemarksFilename("pass-remarks-output",
148 cl::desc("YAML output filename for pass remarks"),
149 cl::value_desc("filename"));
150
Quentin Colombetaef5f642016-06-10 00:52:10 +0000151namespace {
152static ManagedStatic<std::vector<std::string>> RunPassNames;
153
154struct RunPassOption {
155 void operator=(const std::string &Val) const {
156 if (Val.empty())
157 return;
158 SmallVector<StringRef, 8> PassNames;
159 StringRef(Val).split(PassNames, ',', -1, false);
160 for (auto PassName : PassNames)
161 RunPassNames->push_back(PassName);
162 }
163};
164}
165
166static RunPassOption RunPassOpt;
167
168static cl::opt<RunPassOption, true, cl::parser<std::string>> RunPass(
169 "run-pass",
170 cl::desc("Run compiler only for specified passes (comma separated list)"),
171 cl::value_desc("pass-name"), cl::ZeroOrMore, cl::location(RunPassOpt));
172
Eric Christopherd1b5bda2014-05-21 21:05:09 +0000173static int compileModule(char **, LLVMContext &);
Jakob Stoklund Olesen88209282012-11-30 21:42:47 +0000174
Reid Kleckner97ca9642017-09-23 01:03:17 +0000175static std::unique_ptr<ToolOutputFile> GetOutputStream(const char *TargetName,
176 Triple::OSType OS,
177 const char *ProgName) {
Dan Gohman18cde6d2010-08-18 17:55:15 +0000178 // If we don't yet have an output filename, make one.
179 if (OutputFilename.empty()) {
180 if (InputFilename == "-")
181 OutputFilename = "-";
182 else {
Craig Topper847998f0d2014-08-30 16:48:22 +0000183 // If InputFilename ends in .bc or .ll, remove it.
184 StringRef IFN = InputFilename;
185 if (IFN.endswith(".bc") || IFN.endswith(".ll"))
186 OutputFilename = IFN.drop_back(3);
Alex Lorenz61aecc82015-05-27 18:02:19 +0000187 else if (IFN.endswith(".mir"))
188 OutputFilename = IFN.drop_back(4);
Craig Topper847998f0d2014-08-30 16:48:22 +0000189 else
190 OutputFilename = IFN;
Chris Lattner1911fd42006-09-04 04:14:57 +0000191
Dan Gohman18cde6d2010-08-18 17:55:15 +0000192 switch (FileType) {
Dan Gohman18cde6d2010-08-18 17:55:15 +0000193 case TargetMachine::CGFT_AssemblyFile:
194 if (TargetName[0] == 'c') {
195 if (TargetName[1] == 0)
196 OutputFilename += ".cbe.c";
197 else if (TargetName[1] == 'p' && TargetName[2] == 'p')
198 OutputFilename += ".cpp";
199 else
200 OutputFilename += ".s";
201 } else
202 OutputFilename += ".s";
203 break;
204 case TargetMachine::CGFT_ObjectFile:
205 if (OS == Triple::Win32)
206 OutputFilename += ".obj";
207 else
208 OutputFilename += ".o";
209 break;
210 case TargetMachine::CGFT_Null:
211 OutputFilename += ".null";
212 break;
213 }
Dan Gohmaned3e8b42008-08-21 15:33:45 +0000214 }
Chris Lattner1911fd42006-09-04 04:14:57 +0000215 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000216
Dan Gohman18cde6d2010-08-18 17:55:15 +0000217 // Decide if we need "binary" output.
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000218 bool Binary = false;
Chris Lattner1911fd42006-09-04 04:14:57 +0000219 switch (FileType) {
Chris Lattner211edae2010-02-02 21:06:45 +0000220 case TargetMachine::CGFT_AssemblyFile:
Chris Lattner1911fd42006-09-04 04:14:57 +0000221 break;
Chris Lattner211edae2010-02-02 21:06:45 +0000222 case TargetMachine::CGFT_ObjectFile:
Chris Lattner5669e302010-02-03 05:55:08 +0000223 case TargetMachine::CGFT_Null:
Daniel Dunbar0d9eb9b2008-11-13 05:01:07 +0000224 Binary = true;
Chris Lattner1911fd42006-09-04 04:14:57 +0000225 break;
226 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000227
Dan Gohman18cde6d2010-08-18 17:55:15 +0000228 // Open the file.
Rafael Espindola8c968622014-08-25 18:16:47 +0000229 std::error_code EC;
Rafael Espindolac1b49b52013-07-16 19:44:17 +0000230 sys::fs::OpenFlags OpenFlags = sys::fs::F_None;
Rafael Espindolaac694592014-02-24 18:20:12 +0000231 if (!Binary)
232 OpenFlags |= sys::fs::F_Text;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000233 auto FDOut = llvm::make_unique<ToolOutputFile>(OutputFilename, EC, OpenFlags);
Rafael Espindola8c968622014-08-25 18:16:47 +0000234 if (EC) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000235 WithColor::error() << EC.message() << '\n';
Craig Topper573faec2014-04-25 04:24:47 +0000236 return nullptr;
Chris Lattner1911fd42006-09-04 04:14:57 +0000237 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000238
Dan Gohmand4c45432010-09-01 14:20:41 +0000239 return FDOut;
Chris Lattner1911fd42006-09-04 04:14:57 +0000240}
Vikram S. Adve805eb962001-09-18 13:10:45 +0000241
Vivek Pandya18b4c372017-09-15 20:10:09 +0000242struct LLCDiagnosticHandler : public DiagnosticHandler {
243 bool *HasError;
244 LLCDiagnosticHandler(bool *HasErrorPtr) : HasError(HasErrorPtr) {}
245 bool handleDiagnostics(const DiagnosticInfo &DI) override {
246 if (DI.getSeverity() == DS_Error)
247 *HasError = true;
Renato Golin3b0d3772016-05-16 14:28:02 +0000248
Vivek Pandya18b4c372017-09-15 20:10:09 +0000249 if (auto *Remark = dyn_cast<DiagnosticInfoOptimizationBase>(&DI))
250 if (!Remark->isEnabled())
251 return true;
Adam Nemet19925fc2017-01-25 23:20:33 +0000252
Vivek Pandya18b4c372017-09-15 20:10:09 +0000253 DiagnosticPrinterRawOStream DP(errs());
254 errs() << LLVMContext::getDiagnosticMessagePrefix(DI.getSeverity()) << ": ";
255 DI.print(DP);
256 errs() << "\n";
257 return true;
258 }
259};
Renato Golin3b0d3772016-05-16 14:28:02 +0000260
Sanne Wouda5f9d8e22017-02-03 11:14:39 +0000261static void InlineAsmDiagHandler(const SMDiagnostic &SMD, void *Context,
Sanne Woudaff6c8c52017-02-28 10:34:48 +0000262 unsigned LocCookie) {
Sanne Wouda5f9d8e22017-02-03 11:14:39 +0000263 bool *HasError = static_cast<bool *>(Context);
264 if (SMD.getKind() == SourceMgr::DK_Error)
265 *HasError = true;
266
267 SMD.print(nullptr, errs());
Sanne Woudaff6c8c52017-02-28 10:34:48 +0000268
269 // For testing purposes, we print the LocCookie here.
270 if (LocCookie)
Jonas Devlieghere30429212018-06-23 16:51:10 +0000271 WithColor::note() << "!srcloc = " << LocCookie << "\n";
Sanne Wouda5f9d8e22017-02-03 11:14:39 +0000272}
273
Chris Lattner5b836c42003-06-20 15:49:04 +0000274// main - Entry point for the llc compiler.
275//
276int main(int argc, char **argv) {
Rui Ueyama0b9d56a2018-04-13 18:26:06 +0000277 InitLLVM X(argc, argv);
David Greenec58d01b2010-01-05 01:30:21 +0000278
279 // Enable debug stream buffering.
280 EnableDebugBuffering = true;
281
Mehdi Amini8be77072016-04-14 21:59:01 +0000282 LLVMContext Context;
Chris Lattner364d1202004-02-19 20:32:39 +0000283
Daniel Dunbar2b991bb2009-09-03 05:47:22 +0000284 // Initialize targets first, so that --version shows registered targets.
Chris Lattner2deb58f2009-06-17 16:42:19 +0000285 InitializeAllTargets();
Evan Chenge78085a2011-07-22 21:58:54 +0000286 InitializeAllTargetMCs();
Chris Lattner2deb58f2009-06-17 16:42:19 +0000287 InitializeAllAsmPrinters();
Chris Lattneraf632c92010-04-05 23:11:24 +0000288 InitializeAllAsmParsers();
Daniel Dunbar494d6632009-07-16 02:04:54 +0000289
Bob Wilson30a507a2012-07-02 19:48:45 +0000290 // Initialize codegen and IR passes used by llc so that the -print-after,
291 // -print-before, and -stop-after options work.
292 PassRegistry *Registry = PassRegistry::getPassRegistry();
293 initializeCore(*Registry);
294 initializeCodeGen(*Registry);
295 initializeLoopStrengthReducePass(*Registry);
296 initializeLowerIntrinsicsPass(*Registry);
Hans Wennborg5765d842017-11-14 21:09:45 +0000297 initializeEntryExitInstrumenterPass(*Registry);
298 initializePostInlineEntryExitInstrumenterPass(*Registry);
Wei Mi302c35d2016-07-08 03:32:49 +0000299 initializeUnreachableBlockElimLegacyPassPass(*Registry);
Davide Italiano1e151222016-12-06 23:49:58 +0000300 initializeConstantHoistingLegacyPassPass(*Registry);
Matt Arsenault878b0992017-01-17 05:11:25 +0000301 initializeScalarOpts(*Registry);
302 initializeVectorization(*Registry);
Ayman Musaeadb58f2017-05-15 11:30:54 +0000303 initializeScalarizeMaskedMemIntrinPass(*Registry);
Amara Emerson0dd30f82017-05-10 09:42:49 +0000304 initializeExpandReductionsPass(*Registry);
Rafael Espindola275c85f2012-06-26 21:33:36 +0000305
Matthias Braun3310b592017-06-02 23:01:42 +0000306 // Initialize debugging passes.
307 initializeScavengerTestPass(*Registry);
308
Chandler Carruth40393132011-07-22 07:50:48 +0000309 // Register the target printer for --version.
310 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
311
Daniel Dunbar494d6632009-07-16 02:04:54 +0000312 cl::ParseCommandLineOptions(argc, argv, "llvm system compiler\n");
Andrew Tricka41af7a2011-04-05 18:41:31 +0000313
Mehdi Amini2de99272016-03-10 01:28:54 +0000314 Context.setDiscardValueNames(DiscardValueNames);
315
Renato Golin3b0d3772016-05-16 14:28:02 +0000316 // Set a diagnostic handler that doesn't exit on the first error
317 bool HasError = false;
Vivek Pandya18b4c372017-09-15 20:10:09 +0000318 Context.setDiagnosticHandler(
319 llvm::make_unique<LLCDiagnosticHandler>(&HasError));
Sanne Wouda5f9d8e22017-02-03 11:14:39 +0000320 Context.setInlineAsmDiagnosticHandler(InlineAsmDiagHandler, &HasError);
321
Adam Nemet3e426982017-01-25 23:55:59 +0000322 if (PassRemarksWithHotness)
Brian Gesiak8e8ec782017-06-30 18:13:59 +0000323 Context.setDiagnosticsHotnessRequested(true);
Renato Golin3b0d3772016-05-16 14:28:02 +0000324
Brian Gesiake3305282017-06-30 23:14:53 +0000325 if (PassRemarksHotnessThreshold)
326 Context.setDiagnosticsHotnessThreshold(PassRemarksHotnessThreshold);
327
Reid Kleckner97ca9642017-09-23 01:03:17 +0000328 std::unique_ptr<ToolOutputFile> YamlFile;
Adam Nemetc8168e72017-01-26 00:39:51 +0000329 if (RemarksFilename != "") {
330 std::error_code EC;
Reid Kleckner97ca9642017-09-23 01:03:17 +0000331 YamlFile =
332 llvm::make_unique<ToolOutputFile>(RemarksFilename, EC, sys::fs::F_None);
Adam Nemetc8168e72017-01-26 00:39:51 +0000333 if (EC) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000334 WithColor::error(errs(), argv[0]) << EC.message() << '\n';
Adam Nemetc8168e72017-01-26 00:39:51 +0000335 return 1;
336 }
337 Context.setDiagnosticsOutputFile(
338 llvm::make_unique<yaml::Output>(YamlFile->os()));
339 }
340
Matthias Braunf6326272017-06-06 20:06:57 +0000341 if (InputLanguage != "" && InputLanguage != "ir" &&
342 InputLanguage != "mir") {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000343 WithColor::error(errs(), argv[0])
344 << "input language must be '', 'IR' or 'MIR'\n";
Matthias Braunf6326272017-06-06 20:06:57 +0000345 return 1;
346 }
347
Jakob Stoklund Olesen88209282012-11-30 21:42:47 +0000348 // Compile the module TimeCompilations times to give better compile time
349 // metrics.
350 for (unsigned I = TimeCompilations; I; --I)
351 if (int RetVal = compileModule(argv, Context))
352 return RetVal;
Adam Nemetc8168e72017-01-26 00:39:51 +0000353
354 if (YamlFile)
355 YamlFile->keep();
Jakob Stoklund Olesen88209282012-11-30 21:42:47 +0000356 return 0;
357}
358
Matthias Braun4bd6d7f2016-07-16 02:24:15 +0000359static bool addPass(PassManagerBase &PM, const char *argv0,
360 StringRef PassName, TargetPassConfig &TPC) {
Quentin Colombet2a400a72017-04-01 01:26:24 +0000361 if (PassName == "none")
Matthias Braun3346c152016-07-16 02:24:59 +0000362 return false;
363
Quentin Colombet2a400a72017-04-01 01:26:24 +0000364 const PassRegistry *PR = PassRegistry::getPassRegistry();
365 const PassInfo *PI = PR->getPassInfo(PassName);
366 if (!PI) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000367 WithColor::error(errs(), argv0)
368 << "run-pass " << PassName << " is not registered.\n";
Quentin Colombet2a400a72017-04-01 01:26:24 +0000369 return true;
370 }
Matthias Braun4bd6d7f2016-07-16 02:24:15 +0000371
372 Pass *P;
Francis Visoiu Mistrihae1c8532017-05-18 17:21:13 +0000373 if (PI->getNormalCtor())
Matthias Braun4bd6d7f2016-07-16 02:24:15 +0000374 P = PI->getNormalCtor()();
375 else {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000376 WithColor::error(errs(), argv0)
377 << "cannot create pass: " << PI->getPassName() << "\n";
Matthias Braun4bd6d7f2016-07-16 02:24:15 +0000378 return true;
379 }
380 std::string Banner = std::string("After ") + std::string(P->getPassName());
381 PM.add(P);
382 TPC.printAndVerify(Banner);
383
384 return false;
385}
386
Jakob Stoklund Olesen88209282012-11-30 21:42:47 +0000387static int compileModule(char **argv, LLVMContext &Context) {
Chris Lattner1a735402007-05-06 04:55:19 +0000388 // Load the module to be compiled...
Dan Gohman778b06b2009-09-02 19:35:19 +0000389 SMDiagnostic Err;
Ahmed Charlesf4ccd112014-03-06 05:51:42 +0000390 std::unique_ptr<Module> M;
Alex Lorenza15d8882015-06-15 20:30:22 +0000391 std::unique_ptr<MIRParser> MIR;
Duncan Sandsf6ce8ea2012-06-27 16:23:48 +0000392 Triple TheTriple;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000393
Duncan Sandsf6ce8ea2012-06-27 16:23:48 +0000394 bool SkipModule = MCPU == "help" ||
395 (!MAttrs.empty() && MAttrs.front() == "help");
396
397 // If user just wants to list available options, skip module loading
398 if (!SkipModule) {
Matthias Braunf6326272017-06-06 20:06:57 +0000399 if (InputLanguage == "mir" ||
400 (InputLanguage == "" && StringRef(InputFilename).endswith(".mir"))) {
Alex Lorenza15d8882015-06-15 20:30:22 +0000401 MIR = createMIRParserFromFile(InputFilename, Err, Context);
Diana Picus1063f932016-06-09 10:31:05 +0000402 if (MIR)
Matthias Braun2144c522017-06-06 00:44:35 +0000403 M = MIR->parseIRModule();
Alex Lorenza15d8882015-06-15 20:30:22 +0000404 } else
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000405 M = parseIRFile(InputFilename, Err, Context, false);
Craig Topper4fca0dd2014-12-11 07:04:52 +0000406 if (!M) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000407 Err.print(argv[0], WithColor::error(errs(), argv[0]));
Duncan Sandsf6ce8ea2012-06-27 16:23:48 +0000408 return 1;
409 }
410
411 // If we are supposed to override the target triple, do so now.
412 if (!TargetTriple.empty())
Craig Topper4fca0dd2014-12-11 07:04:52 +0000413 M->setTargetTriple(Triple::normalize(TargetTriple));
414 TheTriple = Triple(M->getTargetTriple());
Duncan Sandsf6ce8ea2012-06-27 16:23:48 +0000415 } else {
416 TheTriple = Triple(Triple::normalize(TargetTriple));
Chris Lattner1a735402007-05-06 04:55:19 +0000417 }
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000418
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000419 if (TheTriple.getTriple().empty())
Sebastian Pop01738642011-11-01 21:32:20 +0000420 TheTriple.setTriple(sys::getDefaultTargetTriple());
Daniel Dunbar3c2d4bf2009-08-03 04:03:51 +0000421
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000422 // Get the target specific parser.
423 std::string Error;
424 const Target *TheTarget = TargetRegistry::lookupTarget(MArch, TheTriple,
425 Error);
426 if (!TheTarget) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000427 WithColor::error(errs(), argv[0]) << Error;
Kevin Enderby9ed9e5d2012-05-08 23:38:45 +0000428 return 1;
Chris Lattner63342052002-10-29 21:12:46 +0000429 }
Chris Lattner1a735402007-05-06 04:55:19 +0000430
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000431 std::string CPUStr = getCPUStr(), FeaturesStr = getFeaturesStr();
Craig Topper9a7c0032015-03-31 05:52:57 +0000432
Evan Chengb95fc312011-11-16 08:38:26 +0000433 CodeGenOpt::Level OLvl = CodeGenOpt::Default;
434 switch (OptLevel) {
435 default:
Jonas Devlieghere30429212018-06-23 16:51:10 +0000436 WithColor::error(errs(), argv[0]) << "invalid optimization level.\n";
Evan Chengb95fc312011-11-16 08:38:26 +0000437 return 1;
438 case ' ': break;
439 case '0': OLvl = CodeGenOpt::None; break;
440 case '1': OLvl = CodeGenOpt::Less; break;
441 case '2': OLvl = CodeGenOpt::Default; break;
442 case '3': OLvl = CodeGenOpt::Aggressive; break;
443 }
444
Eli Benderskycf421742014-02-19 17:09:35 +0000445 TargetOptions Options = InitTargetOptionsFromCodeGenFlags();
Rafael Espindola9f5066c2014-02-21 03:13:54 +0000446 Options.DisableIntegratedAS = NoIntegratedAssembler;
Eric Christopherd1b5bda2014-05-21 21:05:09 +0000447 Options.MCOptions.ShowMCEncoding = ShowMCEncoding;
448 Options.MCOptions.MCUseDwarfDirectory = EnableDwarfDirectory;
449 Options.MCOptions.AsmVerbose = AsmVerbose;
Nirav Dave72d33ec2016-07-12 15:32:36 +0000450 Options.MCOptions.PreserveAsmComments = PreserveComments;
Saleem Abdulrasool50116a22017-01-05 05:56:39 +0000451 Options.MCOptions.IASSearchPaths = IncludeDirs;
David Blaikie9c1b0af2017-04-21 23:35:26 +0000452 Options.MCOptions.SplitDwarfFile = SplitDwarfFile;
Eric Christopher4f6d26d2014-05-20 23:59:50 +0000453
Rafael Espindola9aafb852017-08-03 02:16:21 +0000454 std::unique_ptr<TargetMachine> Target(TheTarget->createTargetMachine(
455 TheTriple.getTriple(), CPUStr, FeaturesStr, Options, getRelocModel(),
456 getCodeModel(), OLvl));
Akira Hatanaka4f28a762015-05-06 23:49:24 +0000457
Craig Toppere34c5782014-12-12 07:52:06 +0000458 assert(Target && "Could not allocate target machine!");
Eric Christopherbfc3f302014-05-06 16:29:50 +0000459
460 // If we don't have a module then just exit now. We do this down
461 // here since the CPU/Feature help is underneath the target machine
462 // creation.
463 if (SkipModule)
464 return 0;
465
Craig Topper4fca0dd2014-12-11 07:04:52 +0000466 assert(M && "Should have exited if we didn't have a module!");
Eric Christopher0552d512015-05-12 01:26:05 +0000467 if (FloatABIForCalls != FloatABI::Default)
468 Options.FloatABIType = FloatABIForCalls;
Nick Lewycky8a8d4792011-12-02 22:16:29 +0000469
Chad Rosier7a43e302012-07-19 00:11:45 +0000470 // Figure out where we are going to send the output.
Reid Kleckner97ca9642017-09-23 01:03:17 +0000471 std::unique_ptr<ToolOutputFile> Out =
Craig Topper2a4988e2014-12-12 07:52:00 +0000472 GetOutputStream(TheTarget->getName(), TheTriple.getOS(), argv[0]);
Dan Gohmand5826a32010-08-20 01:07:01 +0000473 if (!Out) return 1;
Mikhail Glushenkov5c1799b2009-01-16 06:53:46 +0000474
Peter Collingbourne9ffe0732018-05-21 20:16:41 +0000475 std::unique_ptr<ToolOutputFile> DwoOut;
476 if (!SplitDwarfOutputFile.empty()) {
477 std::error_code EC;
478 DwoOut = llvm::make_unique<ToolOutputFile>(SplitDwarfOutputFile, EC,
479 sys::fs::F_None);
480 if (EC) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000481 WithColor::error(errs(), argv[0]) << EC.message() << '\n';
Peter Collingbourne9ffe0732018-05-21 20:16:41 +0000482 return 1;
483 }
484 }
485
Dan Gohman99dca4f2010-05-11 19:57:55 +0000486 // Build up all of the passes that we want to do to the module.
Chandler Carruth417c5c12015-02-13 10:01:29 +0000487 legacy::PassManager PM;
Daniel Dunbar4e02eb02009-08-03 17:34:19 +0000488
Bob Wilson772af922012-08-03 21:26:18 +0000489 // Add an appropriate TargetLibraryInfo pass for the module's triple.
Chandler Carruth6f409cb2015-01-24 02:06:09 +0000490 TargetLibraryInfoImpl TLII(Triple(M->getTargetTriple()));
Chandler Carrutheeeec3c2015-01-15 10:41:28 +0000491
492 // The -disable-simplify-libcalls flag actually disables all builtin optzns.
Bob Wilson5f91a992012-08-08 20:31:37 +0000493 if (DisableSimplifyLibCalls)
Chandler Carruth6f409cb2015-01-24 02:06:09 +0000494 TLII.disableAllFunctions();
495 PM.add(new TargetLibraryInfoWrapperPass(TLII));
Bob Wilson772af922012-08-03 21:26:18 +0000496
Dan Gohman99dca4f2010-05-11 19:57:55 +0000497 // Add the target data from the target machine, if it exists, or the module.
Mehdi Amini15e1e7f2015-07-24 16:04:22 +0000498 M->setDataLayout(Target->createDataLayout());
Daniel Dunbar4e02eb02009-08-03 17:34:19 +0000499
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000500 // This needs to be done after setting datalayout since it calls verifier
501 // to check debug info whereas verifier relies on correct datalayout.
502 UpgradeDebugInfo(*M);
503
504 // Verify module immediately to catch problems before doInitialization() is
505 // called on any passes.
506 if (!NoVerify && verifyModule(*M, &errs())) {
Jonas Devlieghere7cde7d92018-06-23 19:04:10 +0000507 std::string Prefix =
Jonas Devlieghere30429212018-06-23 16:51:10 +0000508 (Twine(argv[0]) + Twine(": ") + Twine(InputFilename)).str();
509 WithColor::error(errs(), Prefix) << "input module is broken!\n";
Yaxun Liu7c2d0492018-01-30 22:32:39 +0000510 return 1;
511 }
512
Akira Hatanaka6f491352015-05-26 20:17:20 +0000513 // Override function attributes based on CPUStr, FeaturesStr, and command line
514 // flags.
515 setFunctionAttributes(CPUStr, FeaturesStr, *M);
Akira Hatanakae6f04942015-05-06 23:54:14 +0000516
Eric Christopher475ac5d2014-05-15 01:10:50 +0000517 if (RelaxAll.getNumOccurrences() > 0 &&
518 FileType != TargetMachine::CGFT_ObjectFile)
Jonas Devlieghere30429212018-06-23 16:51:10 +0000519 WithColor::warning(errs(), argv[0])
520 << ": warning: ignoring -mc-relax-all because filetype != obj";
Michael J. Spencer7c380ed2010-07-31 19:57:02 +0000521
Dan Gohmand4c45432010-09-01 14:20:41 +0000522 {
Rafael Espindolac98092e2015-04-14 22:14:34 +0000523 raw_pwrite_stream *OS = &Out->os();
Keno Fischer6f41c132015-12-04 21:56:46 +0000524
525 // Manually do the buffering rather than using buffer_ostream,
526 // so we can memcmp the contents in CompileTwice mode
527 SmallVector<char, 0> Buffer;
528 std::unique_ptr<raw_svector_ostream> BOS;
529 if ((FileType != TargetMachine::CGFT_AssemblyFile &&
530 !Out->os().supportsSeeking()) ||
531 CompileTwice) {
532 BOS = make_unique<raw_svector_ostream>(Buffer);
Rafael Espindolac98092e2015-04-14 22:14:34 +0000533 OS = BOS.get();
534 }
535
Matthias Braune6c9b7e2017-06-06 00:26:24 +0000536 const char *argv0 = argv[0];
Matthias Braun9385cf12017-10-12 22:57:28 +0000537 LLVMTargetMachine &LLVMTM = static_cast<LLVMTargetMachine&>(*Target);
538 MachineModuleInfo *MMI = new MachineModuleInfo(&LLVMTM);
Quentin Colombet6131fb52017-07-31 18:24:07 +0000539
540 // Construct a custom pass pipeline that starts after instruction
541 // selection.
542 if (!RunPassNames->empty()) {
543 if (!MIR) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000544 WithColor::warning(errs(), argv[0])
545 << "run-pass is for .mir file only.\n";
Quentin Colombet6131fb52017-07-31 18:24:07 +0000546 return 1;
547 }
Matthias Braun9385cf12017-10-12 22:57:28 +0000548 TargetPassConfig &TPC = *LLVMTM.createPassConfig(PM);
Quentin Colombet6131fb52017-07-31 18:24:07 +0000549 if (TPC.hasLimitedCodeGenPipeline()) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000550 WithColor::warning(errs(), argv[0])
551 << "run-pass cannot be used with "
552 << TPC.getLimitedCodeGenPipelineReason(" and ") << ".\n";
Quentin Colombet6131fb52017-07-31 18:24:07 +0000553 return 1;
554 }
555
556 TPC.setDisableVerify(NoVerify);
557 PM.add(&TPC);
558 PM.add(MMI);
559 TPC.printAndVerify("");
560 for (const std::string &RunPassName : *RunPassNames) {
561 if (addPass(PM, argv0, RunPassName, TPC))
562 return 1;
563 }
564 TPC.setInitialized();
565 PM.add(createPrintMIRPass(*OS));
566 PM.add(createFreeMachineFunctionPass());
Peter Collingbourne9ffe0732018-05-21 20:16:41 +0000567 } else if (Target->addPassesToEmitFile(PM, *OS,
568 DwoOut ? &DwoOut->os() : nullptr,
569 FileType, NoVerify, MMI)) {
Jonas Devlieghere30429212018-06-23 16:51:10 +0000570 WithColor::warning(errs(), argv[0])
571 << "target does not support generation of this"
572 << " file type!\n";
Matthias Braune6c9b7e2017-06-06 00:26:24 +0000573 return 1;
574 }
575
576 if (MIR) {
Quentin Colombetf514aa42017-07-31 18:31:04 +0000577 assert(MMI && "Forgot to create MMI?");
Matthias Braun2144c522017-06-06 00:44:35 +0000578 if (MIR->parseMachineFunctions(*M, *MMI))
579 return 1;
Dan Gohmand4c45432010-09-01 14:20:41 +0000580 }
581
Andrew Trickce969022011-04-05 18:54:36 +0000582 // Before executing passes, print the final values of the LLVM options.
583 cl::PrintOptionValues();
584
Keno Fischer6f41c132015-12-04 21:56:46 +0000585 // If requested, run the pass manager over the same module again,
586 // to catch any bugs due to persistent state in the passes. Note that
587 // opt has the same functionality, so it may be worth abstracting this out
588 // in the future.
589 SmallVector<char, 0> CompileTwiceBuffer;
590 if (CompileTwice) {
Rafael Espindola22b77242018-02-14 19:50:40 +0000591 std::unique_ptr<Module> M2(llvm::CloneModule(*M));
Keno Fischer6f41c132015-12-04 21:56:46 +0000592 PM.run(*M2);
593 CompileTwiceBuffer = Buffer;
594 Buffer.clear();
595 }
596
Craig Topper4fca0dd2014-12-11 07:04:52 +0000597 PM.run(*M);
Keno Fischer6f41c132015-12-04 21:56:46 +0000598
Vivek Pandya18b4c372017-09-15 20:10:09 +0000599 auto HasError =
600 ((const LLCDiagnosticHandler *)(Context.getDiagHandlerPtr()))->HasError;
601 if (*HasError)
Diana Picusc412e392016-06-23 09:49:56 +0000602 return 1;
Renato Golin3b0d3772016-05-16 14:28:02 +0000603
Keno Fischer6f41c132015-12-04 21:56:46 +0000604 // Compare the two outputs and make sure they're the same
605 if (CompileTwice) {
606 if (Buffer.size() != CompileTwiceBuffer.size() ||
607 (memcmp(Buffer.data(), CompileTwiceBuffer.data(), Buffer.size()) !=
608 0)) {
609 errs()
610 << "Running the pass manager twice changed the output.\n"
611 "Writing the result of the second run to the specified output\n"
612 "To generate the one-run comparison binary, just run without\n"
613 "the compile-twice option\n";
614 Out->os() << Buffer;
615 Out->keep();
616 return 1;
617 }
618 }
619
620 if (BOS) {
621 Out->os() << Buffer;
622 }
Dan Gohmand4c45432010-09-01 14:20:41 +0000623 }
Dan Gohman99dca4f2010-05-11 19:57:55 +0000624
Dan Gohmand5826a32010-08-20 01:07:01 +0000625 // Declare success.
626 Out->keep();
Peter Collingbourne9ffe0732018-05-21 20:16:41 +0000627 if (DwoOut)
628 DwoOut->keep();
Chris Lattner1a735402007-05-06 04:55:19 +0000629
630 return 0;
Vikram S. Adve2f64f9f2001-10-14 23:29:28 +0000631}