1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This utility is a simple driver that allows static performance analysis on
11 // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
13 // llvm-mca [options] <file-name>
18 // The target defaults to the host target.
19 // The cpu defaults to the 'native' host cpu.
20 // The output defaults to standard output.
22 //===----------------------------------------------------------------------===//
24 #include "CodeRegion.h"
25 #include "CodeRegionGenerator.h"
26 #include "PipelinePrinter.h"
27 #include "Views/DispatchStatistics.h"
28 #include "Views/InstructionInfoView.h"
29 #include "Views/RegisterFileStatistics.h"
30 #include "Views/ResourcePressureView.h"
31 #include "Views/RetireControlUnitStatistics.h"
32 #include "Views/SchedulerStatistics.h"
33 #include "Views/SummaryView.h"
34 #include "Views/TimelineView.h"
35 #include "llvm/MC/MCAsmInfo.h"
36 #include "llvm/MC/MCContext.h"
37 #include "llvm/MC/MCObjectFileInfo.h"
38 #include "llvm/MC/MCRegisterInfo.h"
39 #include "llvm/MCA/Context.h"
40 #include "llvm/MCA/Pipeline.h"
41 #include "llvm/MCA/Stages/EntryStage.h"
42 #include "llvm/MCA/Stages/InstructionTables.h"
43 #include "llvm/MCA/Support.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/InitLLVM.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/ToolOutputFile.h"
55 #include "llvm/Support/WithColor.h"
59 static cl::OptionCategory ToolOptions("Tool Options");
60 static cl::OptionCategory ViewOptions("View Options");
62 static cl::opt<std::string> InputFilename(cl::Positional,
63 cl::desc("<input file>"),
64 cl::cat(ToolOptions), cl::init("-"));
66 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
67 cl::init("-"), cl::cat(ToolOptions),
68 cl::value_desc("filename"));
70 static cl::opt<std::string>
71 ArchName("march", cl::desc("Target architecture. "
72 "See -version for available targets"),
73 cl::cat(ToolOptions));
75 static cl::opt<std::string>
77 cl::desc("Target triple. See -version for available targets"),
78 cl::cat(ToolOptions));
80 static cl::opt<std::string>
82 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
83 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
86 OutputAsmVariant("output-asm-variant",
87 cl::desc("Syntax variant to use for output printing"),
88 cl::cat(ToolOptions), cl::init(-1));
90 static cl::opt<unsigned> Iterations("iterations",
91 cl::desc("Number of iterations to run"),
92 cl::cat(ToolOptions), cl::init(0));
94 static cl::opt<unsigned>
95 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
96 cl::cat(ToolOptions), cl::init(0));
98 static cl::opt<unsigned>
99 RegisterFileSize("register-file-size",
100 cl::desc("Maximum number of physical registers which can "
101 "be used for register mappings"),
102 cl::cat(ToolOptions), cl::init(0));
105 PrintRegisterFileStats("register-file-stats",
106 cl::desc("Print register file statistics"),
107 cl::cat(ViewOptions), cl::init(false));
109 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
110 cl::desc("Print dispatch statistics"),
111 cl::cat(ViewOptions), cl::init(false));
114 PrintSummaryView("summary-view", cl::Hidden,
115 cl::desc("Print summary view (enabled by default)"),
116 cl::cat(ViewOptions), cl::init(true));
118 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
119 cl::desc("Print scheduler statistics"),
120 cl::cat(ViewOptions), cl::init(false));
123 PrintRetireStats("retire-stats",
124 cl::desc("Print retire control unit statistics"),
125 cl::cat(ViewOptions), cl::init(false));
127 static cl::opt<bool> PrintResourcePressureView(
129 cl::desc("Print the resource pressure view (enabled by default)"),
130 cl::cat(ViewOptions), cl::init(true));
132 static cl::opt<bool> PrintTimelineView("timeline",
133 cl::desc("Print the timeline view"),
134 cl::cat(ViewOptions), cl::init(false));
136 static cl::opt<unsigned> TimelineMaxIterations(
137 "timeline-max-iterations",
138 cl::desc("Maximum number of iterations to print in timeline view"),
139 cl::cat(ViewOptions), cl::init(0));
141 static cl::opt<unsigned> TimelineMaxCycles(
142 "timeline-max-cycles",
144 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
145 cl::cat(ViewOptions), cl::init(80));
148 AssumeNoAlias("noalias",
149 cl::desc("If set, assume that loads and stores do not alias"),
150 cl::cat(ToolOptions), cl::init(true));
152 static cl::opt<unsigned> LoadQueueSize("lqueue",
153 cl::desc("Size of the load queue"),
154 cl::cat(ToolOptions), cl::init(0));
156 static cl::opt<unsigned> StoreQueueSize("squeue",
157 cl::desc("Size of the store queue"),
158 cl::cat(ToolOptions), cl::init(0));
161 PrintInstructionTables("instruction-tables",
162 cl::desc("Print instruction tables"),
163 cl::cat(ToolOptions), cl::init(false));
165 static cl::opt<bool> PrintInstructionInfoView(
167 cl::desc("Print the instruction info view (enabled by default)"),
168 cl::cat(ViewOptions), cl::init(true));
170 static cl::opt<bool> EnableAllStats("all-stats",
171 cl::desc("Print all hardware statistics"),
172 cl::cat(ViewOptions), cl::init(false));
175 EnableAllViews("all-views",
176 cl::desc("Print all views including hardware statistics"),
177 cl::cat(ViewOptions), cl::init(false));
181 const Target *getTarget(const char *ProgName) {
182 if (TripleName.empty())
183 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
184 Triple TheTriple(TripleName);
186 // Get the target specific parser.
188 const Target *TheTarget =
189 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
191 errs() << ProgName << ": " << Error;
195 // Return the found target.
199 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
200 if (OutputFilename == "")
201 OutputFilename = "-";
204 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
206 return std::move(Out);
209 } // end of anonymous namespace
211 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
212 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
213 O = Default.getValue();
216 static void processViewOptions() {
217 if (!EnableAllViews.getNumOccurrences() &&
218 !EnableAllStats.getNumOccurrences())
221 if (EnableAllViews.getNumOccurrences()) {
222 processOptionImpl(PrintSummaryView, EnableAllViews);
223 processOptionImpl(PrintResourcePressureView, EnableAllViews);
224 processOptionImpl(PrintTimelineView, EnableAllViews);
225 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
228 const cl::opt<bool> &Default =
229 EnableAllViews.getPosition() < EnableAllStats.getPosition()
232 processOptionImpl(PrintRegisterFileStats, Default);
233 processOptionImpl(PrintDispatchStats, Default);
234 processOptionImpl(PrintSchedulerStats, Default);
235 processOptionImpl(PrintRetireStats, Default);
238 // Returns true on success.
239 static bool runPipeline(mca::Pipeline &P) {
240 // Handle pipeline errors here.
241 Expected<unsigned> Cycles = P.run();
243 WithColor::error() << toString(Cycles.takeError());
249 int main(int argc, char **argv) {
250 InitLLVM X(argc, argv);
252 // Initialize targets and assembly parsers.
253 InitializeAllTargetInfos();
254 InitializeAllTargetMCs();
255 InitializeAllAsmParsers();
257 // Enable printing of available targets when flag --version is specified.
258 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
260 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
262 // Parse flags and initialize target options.
263 cl::ParseCommandLineOptions(argc, argv,
264 "llvm machine code performance analyzer.\n");
266 // Get the target from the triple. If a triple is not specified, then select
267 // the default triple for the host. If the triple doesn't correspond to any
268 // registered target, then exit with an error message.
269 const char *ProgName = argv[0];
270 const Target *TheTarget = getTarget(ProgName);
274 // GetTarget() may replaced TripleName with a default triple.
275 // For safety, reconstruct the Triple object.
276 Triple TheTriple(TripleName);
278 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
279 MemoryBuffer::getFileOrSTDIN(InputFilename);
280 if (std::error_code EC = BufferPtr.getError()) {
281 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
285 // Apply overrides to llvm-mca specific options.
286 processViewOptions();
290 // Tell SrcMgr about this buffer, which is what the parser will pick up.
291 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
293 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
294 assert(MRI && "Unable to create target register info!");
296 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
297 assert(MAI && "Unable to create target asm info!");
299 MCObjectFileInfo MOFI;
300 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
301 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
303 std::unique_ptr<buffer_ostream> BOS;
305 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
307 std::unique_ptr<MCInstrAnalysis> MCIA(
308 TheTarget->createMCInstrAnalysis(MCII.get()));
310 if (!MCPU.compare("native"))
311 MCPU = llvm::sys::getHostCPUName();
313 std::unique_ptr<MCSubtargetInfo> STI(
314 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
315 if (!STI->isCPUStringValid(MCPU))
318 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
319 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
320 << "' is an in-order cpu.\n";
324 if (!STI->getSchedModel().hasInstrSchedModel()) {
326 << "unable to find instruction-level scheduling information for"
327 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
330 if (STI->getSchedModel().InstrItineraries)
332 << "cpu '" << MCPU << "' provides itineraries. However, "
333 << "instruction itineraries are currently unsupported.\n";
337 // Parse the input and create CodeRegions that llvm-mca can analyze.
338 mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
339 Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
342 handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
343 WithColor::error() << E.getMessage() << '\n';
346 WithColor::error() << toString(std::move(Err)) << '\n';
350 const mca::CodeRegions &Regions = *RegionsOrErr;
351 if (Regions.empty()) {
352 WithColor::error() << "no assembly instructions found.\n";
356 // Now initialize the output file.
357 auto OF = getOutputStream();
358 if (std::error_code EC = OF.getError()) {
359 WithColor::error() << EC.message() << '\n';
363 unsigned AssemblerDialect = CRG.getAssemblerDialect();
364 if (OutputAsmVariant >= 0)
365 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
366 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
367 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
370 << "unable to create instruction printer for target triple '"
371 << TheTriple.normalize() << "' with assembly variant "
372 << AssemblerDialect << ".\n";
376 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
378 const MCSchedModel &SM = STI->getSchedModel();
380 unsigned Width = SM.IssueWidth;
382 Width = DispatchWidth;
384 // Create an instruction builder.
385 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
387 // Create a context to control ownership of the pipeline hardware.
388 mca::Context MCA(*MRI, *STI);
390 mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
391 StoreQueueSize, AssumeNoAlias);
393 // Number each region in the sequence.
394 unsigned RegionIdx = 0;
396 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
397 // Skip empty code regions.
401 // Don't print the header of this region if it is the default region, and
402 // it doesn't have an end location.
403 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
404 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
405 StringRef Desc = Region->getDescription();
407 TOF->os() << " - " << Desc;
411 // Lower the MCInst sequence into an mca::Instruction sequence.
412 ArrayRef<MCInst> Insts = Region->getInstructions();
413 std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
414 for (const MCInst &MCI : Insts) {
415 Expected<std::unique_ptr<mca::Instruction>> Inst =
416 IB.createInstruction(MCI);
418 if (auto NewE = handleErrors(
420 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
421 std::string InstructionStr;
422 raw_string_ostream SS(InstructionStr);
423 WithColor::error() << IE.Message << '\n';
424 IP->printInst(&IE.Inst, SS, "", *STI);
426 WithColor::note() << "instruction: " << InstructionStr
430 WithColor::error() << toString(std::move(NewE));
435 LoweredSequence.emplace_back(std::move(Inst.get()));
438 mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
440 if (PrintInstructionTables) {
441 // Create a pipeline, stages, and a printer.
442 auto P = llvm::make_unique<mca::Pipeline>();
443 P->appendStage(llvm::make_unique<mca::EntryStage>(S));
444 P->appendStage(llvm::make_unique<mca::InstructionTables>(SM));
445 mca::PipelinePrinter Printer(*P);
447 // Create the views for this pipeline, execute, and emit a report.
448 if (PrintInstructionInfoView) {
449 Printer.addView(llvm::make_unique<mca::InstructionInfoView>(
450 *STI, *MCII, Insts, *IP));
453 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
455 if (!runPipeline(*P))
458 Printer.printReport(TOF->os());
462 // Create a basic pipeline simulating an out-of-order backend.
463 auto P = MCA.createDefaultPipeline(PO, IB, S);
464 mca::PipelinePrinter Printer(*P);
466 if (PrintSummaryView)
467 Printer.addView(llvm::make_unique<mca::SummaryView>(SM, Insts, Width));
469 if (PrintInstructionInfoView)
471 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP));
473 if (PrintDispatchStats)
474 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
476 if (PrintSchedulerStats)
477 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
479 if (PrintRetireStats)
480 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM));
482 if (PrintRegisterFileStats)
483 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
485 if (PrintResourcePressureView)
487 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
489 if (PrintTimelineView) {
490 unsigned TimelineIterations =
491 TimelineMaxIterations ? TimelineMaxIterations : 10;
492 Printer.addView(llvm::make_unique<mca::TimelineView>(
493 *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
497 if (!runPipeline(*P))
500 Printer.printReport(TOF->os());
502 // Clear the InstrBuilder internal state in preparation for another round.