Revert r354244 "[DAGCombiner] Eliminate dead stores to stack."
[llvm-complete.git] / tools / llvm-mca / llvm-mca.cpp
blob704a7b40efd7cac569f8149fc1eb15194fa844b1
1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This utility is a simple driver that allows static performance analysis on
10 // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
12 // llvm-mca [options] <file-name>
13 // -march <type>
14 // -mcpu <cpu>
15 // -o <file>
17 // The target defaults to the host target.
18 // The cpu defaults to the 'native' host cpu.
19 // The output defaults to standard output.
21 //===----------------------------------------------------------------------===//
23 #include "CodeRegion.h"
24 #include "CodeRegionGenerator.h"
25 #include "PipelinePrinter.h"
26 #include "Views/DispatchStatistics.h"
27 #include "Views/InstructionInfoView.h"
28 #include "Views/RegisterFileStatistics.h"
29 #include "Views/ResourcePressureView.h"
30 #include "Views/RetireControlUnitStatistics.h"
31 #include "Views/SchedulerStatistics.h"
32 #include "Views/SummaryView.h"
33 #include "Views/TimelineView.h"
34 #include "llvm/MC/MCAsmInfo.h"
35 #include "llvm/MC/MCContext.h"
36 #include "llvm/MC/MCObjectFileInfo.h"
37 #include "llvm/MC/MCRegisterInfo.h"
38 #include "llvm/MCA/Context.h"
39 #include "llvm/MCA/Pipeline.h"
40 #include "llvm/MCA/Stages/EntryStage.h"
41 #include "llvm/MCA/Stages/InstructionTables.h"
42 #include "llvm/MCA/Support.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/ErrorHandling.h"
45 #include "llvm/Support/ErrorOr.h"
46 #include "llvm/Support/FileSystem.h"
47 #include "llvm/Support/Host.h"
48 #include "llvm/Support/InitLLVM.h"
49 #include "llvm/Support/MemoryBuffer.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/ToolOutputFile.h"
54 #include "llvm/Support/WithColor.h"
56 using namespace llvm;
58 static cl::OptionCategory ToolOptions("Tool Options");
59 static cl::OptionCategory ViewOptions("View Options");
61 static cl::opt<std::string> InputFilename(cl::Positional,
62 cl::desc("<input file>"),
63 cl::cat(ToolOptions), cl::init("-"));
65 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
66 cl::init("-"), cl::cat(ToolOptions),
67 cl::value_desc("filename"));
69 static cl::opt<std::string>
70 ArchName("march", cl::desc("Target architecture. "
71 "See -version for available targets"),
72 cl::cat(ToolOptions));
74 static cl::opt<std::string>
75 TripleName("mtriple",
76 cl::desc("Target triple. See -version for available targets"),
77 cl::cat(ToolOptions));
79 static cl::opt<std::string>
80 MCPU("mcpu",
81 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
82 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
84 static cl::opt<int>
85 OutputAsmVariant("output-asm-variant",
86 cl::desc("Syntax variant to use for output printing"),
87 cl::cat(ToolOptions), cl::init(-1));
89 static cl::opt<unsigned> Iterations("iterations",
90 cl::desc("Number of iterations to run"),
91 cl::cat(ToolOptions), cl::init(0));
93 static cl::opt<unsigned>
94 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
95 cl::cat(ToolOptions), cl::init(0));
97 static cl::opt<unsigned>
98 RegisterFileSize("register-file-size",
99 cl::desc("Maximum number of physical registers which can "
100 "be used for register mappings"),
101 cl::cat(ToolOptions), cl::init(0));
103 static cl::opt<bool>
104 PrintRegisterFileStats("register-file-stats",
105 cl::desc("Print register file statistics"),
106 cl::cat(ViewOptions), cl::init(false));
108 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
109 cl::desc("Print dispatch statistics"),
110 cl::cat(ViewOptions), cl::init(false));
112 static cl::opt<bool>
113 PrintSummaryView("summary-view", cl::Hidden,
114 cl::desc("Print summary view (enabled by default)"),
115 cl::cat(ViewOptions), cl::init(true));
117 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
118 cl::desc("Print scheduler statistics"),
119 cl::cat(ViewOptions), cl::init(false));
121 static cl::opt<bool>
122 PrintRetireStats("retire-stats",
123 cl::desc("Print retire control unit statistics"),
124 cl::cat(ViewOptions), cl::init(false));
126 static cl::opt<bool> PrintResourcePressureView(
127 "resource-pressure",
128 cl::desc("Print the resource pressure view (enabled by default)"),
129 cl::cat(ViewOptions), cl::init(true));
131 static cl::opt<bool> PrintTimelineView("timeline",
132 cl::desc("Print the timeline view"),
133 cl::cat(ViewOptions), cl::init(false));
135 static cl::opt<unsigned> TimelineMaxIterations(
136 "timeline-max-iterations",
137 cl::desc("Maximum number of iterations to print in timeline view"),
138 cl::cat(ViewOptions), cl::init(0));
140 static cl::opt<unsigned> TimelineMaxCycles(
141 "timeline-max-cycles",
142 cl::desc(
143 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
144 cl::cat(ViewOptions), cl::init(80));
146 static cl::opt<bool>
147 AssumeNoAlias("noalias",
148 cl::desc("If set, assume that loads and stores do not alias"),
149 cl::cat(ToolOptions), cl::init(true));
151 static cl::opt<unsigned> LoadQueueSize("lqueue",
152 cl::desc("Size of the load queue"),
153 cl::cat(ToolOptions), cl::init(0));
155 static cl::opt<unsigned> StoreQueueSize("squeue",
156 cl::desc("Size of the store queue"),
157 cl::cat(ToolOptions), cl::init(0));
159 static cl::opt<bool>
160 PrintInstructionTables("instruction-tables",
161 cl::desc("Print instruction tables"),
162 cl::cat(ToolOptions), cl::init(false));
164 static cl::opt<bool> PrintInstructionInfoView(
165 "instruction-info",
166 cl::desc("Print the instruction info view (enabled by default)"),
167 cl::cat(ViewOptions), cl::init(true));
169 static cl::opt<bool> EnableAllStats("all-stats",
170 cl::desc("Print all hardware statistics"),
171 cl::cat(ViewOptions), cl::init(false));
173 static cl::opt<bool>
174 EnableAllViews("all-views",
175 cl::desc("Print all views including hardware statistics"),
176 cl::cat(ViewOptions), cl::init(false));
178 namespace {
180 const Target *getTarget(const char *ProgName) {
181 if (TripleName.empty())
182 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
183 Triple TheTriple(TripleName);
185 // Get the target specific parser.
186 std::string Error;
187 const Target *TheTarget =
188 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
189 if (!TheTarget) {
190 errs() << ProgName << ": " << Error;
191 return nullptr;
194 // Return the found target.
195 return TheTarget;
198 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
199 if (OutputFilename == "")
200 OutputFilename = "-";
201 std::error_code EC;
202 auto Out =
203 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
204 if (!EC)
205 return std::move(Out);
206 return EC;
208 } // end of anonymous namespace
210 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
211 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
212 O = Default.getValue();
215 static void processViewOptions() {
216 if (!EnableAllViews.getNumOccurrences() &&
217 !EnableAllStats.getNumOccurrences())
218 return;
220 if (EnableAllViews.getNumOccurrences()) {
221 processOptionImpl(PrintSummaryView, EnableAllViews);
222 processOptionImpl(PrintResourcePressureView, EnableAllViews);
223 processOptionImpl(PrintTimelineView, EnableAllViews);
224 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
227 const cl::opt<bool> &Default =
228 EnableAllViews.getPosition() < EnableAllStats.getPosition()
229 ? EnableAllStats
230 : EnableAllViews;
231 processOptionImpl(PrintRegisterFileStats, Default);
232 processOptionImpl(PrintDispatchStats, Default);
233 processOptionImpl(PrintSchedulerStats, Default);
234 processOptionImpl(PrintRetireStats, Default);
237 // Returns true on success.
238 static bool runPipeline(mca::Pipeline &P) {
239 // Handle pipeline errors here.
240 Expected<unsigned> Cycles = P.run();
241 if (!Cycles) {
242 WithColor::error() << toString(Cycles.takeError());
243 return false;
245 return true;
248 int main(int argc, char **argv) {
249 InitLLVM X(argc, argv);
251 // Initialize targets and assembly parsers.
252 InitializeAllTargetInfos();
253 InitializeAllTargetMCs();
254 InitializeAllAsmParsers();
256 // Enable printing of available targets when flag --version is specified.
257 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
259 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
261 // Parse flags and initialize target options.
262 cl::ParseCommandLineOptions(argc, argv,
263 "llvm machine code performance analyzer.\n");
265 // Get the target from the triple. If a triple is not specified, then select
266 // the default triple for the host. If the triple doesn't correspond to any
267 // registered target, then exit with an error message.
268 const char *ProgName = argv[0];
269 const Target *TheTarget = getTarget(ProgName);
270 if (!TheTarget)
271 return 1;
273 // GetTarget() may replaced TripleName with a default triple.
274 // For safety, reconstruct the Triple object.
275 Triple TheTriple(TripleName);
277 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
278 MemoryBuffer::getFileOrSTDIN(InputFilename);
279 if (std::error_code EC = BufferPtr.getError()) {
280 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
281 return 1;
284 // Apply overrides to llvm-mca specific options.
285 processViewOptions();
287 SourceMgr SrcMgr;
289 // Tell SrcMgr about this buffer, which is what the parser will pick up.
290 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
292 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
293 assert(MRI && "Unable to create target register info!");
295 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
296 assert(MAI && "Unable to create target asm info!");
298 MCObjectFileInfo MOFI;
299 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
300 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
302 std::unique_ptr<buffer_ostream> BOS;
304 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
306 std::unique_ptr<MCInstrAnalysis> MCIA(
307 TheTarget->createMCInstrAnalysis(MCII.get()));
309 if (!MCPU.compare("native"))
310 MCPU = llvm::sys::getHostCPUName();
312 std::unique_ptr<MCSubtargetInfo> STI(
313 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
314 if (!STI->isCPUStringValid(MCPU))
315 return 1;
317 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
318 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
319 << "' is an in-order cpu.\n";
320 return 1;
323 if (!STI->getSchedModel().hasInstrSchedModel()) {
324 WithColor::error()
325 << "unable to find instruction-level scheduling information for"
326 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
327 << "'.\n";
329 if (STI->getSchedModel().InstrItineraries)
330 WithColor::note()
331 << "cpu '" << MCPU << "' provides itineraries. However, "
332 << "instruction itineraries are currently unsupported.\n";
333 return 1;
336 // Parse the input and create CodeRegions that llvm-mca can analyze.
337 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
338 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
339 if (!RegionsOrErr) {
340 if (auto Err =
341 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
342 WithColor::error() << E.getMessage() << '\n';
343 })) {
344 // Default case.
345 WithColor::error() << toString(std::move(Err)) << '\n';
347 return 1;
349 const mca::CodeRegions &Regions = *RegionsOrErr;
350 if (Regions.empty()) {
351 WithColor::error() << "no assembly instructions found.\n";
352 return 1;
355 // Now initialize the output file.
356 auto OF = getOutputStream();
357 if (std::error_code EC = OF.getError()) {
358 WithColor::error() << EC.message() << '\n';
359 return 1;
362 unsigned AssemblerDialect = CRG.getAssemblerDialect();
363 if (OutputAsmVariant >= 0)
364 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
365 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
366 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
367 if (!IP) {
368 WithColor::error()
369 << "unable to create instruction printer for target triple '"
370 << TheTriple.normalize() << "' with assembly variant "
371 << AssemblerDialect << ".\n";
372 return 1;
375 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
377 const MCSchedModel &SM = STI->getSchedModel();
379 unsigned Width = SM.IssueWidth;
380 if (DispatchWidth)
381 Width = DispatchWidth;
383 // Create an instruction builder.
384 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
386 // Create a context to control ownership of the pipeline hardware.
387 mca::Context MCA(*MRI, *STI);
389 mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
390 StoreQueueSize, AssumeNoAlias);
392 // Number each region in the sequence.
393 unsigned RegionIdx = 0;
395 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
396 // Skip empty code regions.
397 if (Region->empty())
398 continue;
400 // Don't print the header of this region if it is the default region, and
401 // it doesn't have an end location.
402 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
403 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
404 StringRef Desc = Region->getDescription();
405 if (!Desc.empty())
406 TOF->os() << " - " << Desc;
407 TOF->os() << "\n\n";
410 // Lower the MCInst sequence into an mca::Instruction sequence.
411 ArrayRef<MCInst> Insts = Region->getInstructions();
412 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
413 for (const MCInst &MCI : Insts) {
414 Expected<std::unique_ptr<mca::Instruction>> Inst =
415 IB.createInstruction(MCI);
416 if (!Inst) {
417 if (auto NewE = handleErrors(
418 Inst.takeError(),
419 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
420 std::string InstructionStr;
421 raw_string_ostream SS(InstructionStr);
422 WithColor::error() << IE.Message << '\n';
423 IP->printInst(&IE.Inst, SS, "", *STI);
424 SS.flush();
425 WithColor::note() << "instruction: " << InstructionStr
426 << '\n';
427 })) {
428 // Default case.
429 WithColor::error() << toString(std::move(NewE));
431 return 1;
434 LoweredSequence.emplace_back(std::move(Inst.get()));
437 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
439 if (PrintInstructionTables) {
440 // Create a pipeline, stages, and a printer.
441 auto P = llvm::make_unique<mca::Pipeline>();
442 P->appendStage(llvm::make_unique<mca::EntryStage>(S));
443 P->appendStage(llvm::make_unique<mca::InstructionTables>(SM));
444 mca::PipelinePrinter Printer(*P);
446 // Create the views for this pipeline, execute, and emit a report.
447 if (PrintInstructionInfoView) {
448 Printer.addView(llvm::make_unique<mca::InstructionInfoView>(
449 *STI, *MCII, Insts, *IP));
451 Printer.addView(
452 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
454 if (!runPipeline(*P))
455 return 1;
457 Printer.printReport(TOF->os());
458 continue;
461 // Create a basic pipeline simulating an out-of-order backend.
462 auto P = MCA.createDefaultPipeline(PO, IB, S);
463 mca::PipelinePrinter Printer(*P);
465 if (PrintSummaryView)
466 Printer.addView(llvm::make_unique<mca::SummaryView>(SM, Insts, Width));
468 if (PrintInstructionInfoView)
469 Printer.addView(
470 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP));
472 if (PrintDispatchStats)
473 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
475 if (PrintSchedulerStats)
476 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
478 if (PrintRetireStats)
479 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM));
481 if (PrintRegisterFileStats)
482 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
484 if (PrintResourcePressureView)
485 Printer.addView(
486 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
488 if (PrintTimelineView) {
489 unsigned TimelineIterations =
490 TimelineMaxIterations ? TimelineMaxIterations : 10;
491 Printer.addView(llvm::make_unique<mca::TimelineView>(
492 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
493 TimelineMaxCycles));
496 if (!runPipeline(*P))
497 return 1;
499 Printer.printReport(TOF->os());
501 // Clear the InstrBuilder internal state in preparation for another round.
502 IB.clear();
505 TOF->keep();
506 return 0;