1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
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
7 //===----------------------------------------------------------------------===//
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>
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/BottleneckAnalysis.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
>
72 cl::desc("Target architecture. "
73 "See -version for available targets"),
74 cl::cat(ToolOptions
));
76 static cl::opt
<std::string
>
78 cl::desc("Target triple. See -version for available targets"),
79 cl::cat(ToolOptions
));
81 static cl::opt
<std::string
>
83 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
84 cl::value_desc("cpu-name"), cl::cat(ToolOptions
), cl::init("native"));
87 OutputAsmVariant("output-asm-variant",
88 cl::desc("Syntax variant to use for output printing"),
89 cl::cat(ToolOptions
), cl::init(-1));
92 PrintImmHex("print-imm-hex", cl::cat(ToolOptions
), cl::init(false),
93 cl::desc("Prefer hex format when printing immediate values"));
95 static cl::opt
<unsigned> Iterations("iterations",
96 cl::desc("Number of iterations to run"),
97 cl::cat(ToolOptions
), cl::init(0));
99 static cl::opt
<unsigned>
100 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
101 cl::cat(ToolOptions
), cl::init(0));
103 static cl::opt
<unsigned>
104 RegisterFileSize("register-file-size",
105 cl::desc("Maximum number of physical registers which can "
106 "be used for register mappings"),
107 cl::cat(ToolOptions
), cl::init(0));
109 static cl::opt
<unsigned>
110 MicroOpQueue("micro-op-queue-size", cl::Hidden
,
111 cl::desc("Number of entries in the micro-op queue"),
112 cl::cat(ToolOptions
), cl::init(0));
114 static cl::opt
<unsigned>
115 DecoderThroughput("decoder-throughput", cl::Hidden
,
116 cl::desc("Maximum throughput from the decoders "
117 "(instructions per cycle)"),
118 cl::cat(ToolOptions
), cl::init(0));
121 PrintRegisterFileStats("register-file-stats",
122 cl::desc("Print register file statistics"),
123 cl::cat(ViewOptions
), cl::init(false));
125 static cl::opt
<bool> PrintDispatchStats("dispatch-stats",
126 cl::desc("Print dispatch statistics"),
127 cl::cat(ViewOptions
), cl::init(false));
130 PrintSummaryView("summary-view", cl::Hidden
,
131 cl::desc("Print summary view (enabled by default)"),
132 cl::cat(ViewOptions
), cl::init(true));
134 static cl::opt
<bool> PrintSchedulerStats("scheduler-stats",
135 cl::desc("Print scheduler statistics"),
136 cl::cat(ViewOptions
), cl::init(false));
139 PrintRetireStats("retire-stats",
140 cl::desc("Print retire control unit statistics"),
141 cl::cat(ViewOptions
), cl::init(false));
143 static cl::opt
<bool> PrintResourcePressureView(
145 cl::desc("Print the resource pressure view (enabled by default)"),
146 cl::cat(ViewOptions
), cl::init(true));
148 static cl::opt
<bool> PrintTimelineView("timeline",
149 cl::desc("Print the timeline view"),
150 cl::cat(ViewOptions
), cl::init(false));
152 static cl::opt
<unsigned> TimelineMaxIterations(
153 "timeline-max-iterations",
154 cl::desc("Maximum number of iterations to print in timeline view"),
155 cl::cat(ViewOptions
), cl::init(0));
157 static cl::opt
<unsigned> TimelineMaxCycles(
158 "timeline-max-cycles",
160 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
161 cl::cat(ViewOptions
), cl::init(80));
164 AssumeNoAlias("noalias",
165 cl::desc("If set, assume that loads and stores do not alias"),
166 cl::cat(ToolOptions
), cl::init(true));
168 static cl::opt
<unsigned> LoadQueueSize("lqueue",
169 cl::desc("Size of the load queue"),
170 cl::cat(ToolOptions
), cl::init(0));
172 static cl::opt
<unsigned> StoreQueueSize("squeue",
173 cl::desc("Size of the store queue"),
174 cl::cat(ToolOptions
), cl::init(0));
177 PrintInstructionTables("instruction-tables",
178 cl::desc("Print instruction tables"),
179 cl::cat(ToolOptions
), cl::init(false));
181 static cl::opt
<bool> PrintInstructionInfoView(
183 cl::desc("Print the instruction info view (enabled by default)"),
184 cl::cat(ViewOptions
), cl::init(true));
186 static cl::opt
<bool> EnableAllStats("all-stats",
187 cl::desc("Print all hardware statistics"),
188 cl::cat(ViewOptions
), cl::init(false));
191 EnableAllViews("all-views",
192 cl::desc("Print all views including hardware statistics"),
193 cl::cat(ViewOptions
), cl::init(false));
195 static cl::opt
<bool> EnableBottleneckAnalysis(
196 "bottleneck-analysis",
197 cl::desc("Enable bottleneck analysis (disabled by default)"),
198 cl::cat(ViewOptions
), cl::init(false));
202 const Target
*getTarget(const char *ProgName
) {
203 if (TripleName
.empty())
204 TripleName
= Triple::normalize(sys::getDefaultTargetTriple());
205 Triple
TheTriple(TripleName
);
207 // Get the target specific parser.
209 const Target
*TheTarget
=
210 TargetRegistry::lookupTarget(ArchName
, TheTriple
, Error
);
212 errs() << ProgName
<< ": " << Error
;
216 // Return the found target.
220 ErrorOr
<std::unique_ptr
<ToolOutputFile
>> getOutputStream() {
221 if (OutputFilename
== "")
222 OutputFilename
= "-";
225 llvm::make_unique
<ToolOutputFile
>(OutputFilename
, EC
, sys::fs::OF_None
);
227 return std::move(Out
);
230 } // end of anonymous namespace
232 static void processOptionImpl(cl::opt
<bool> &O
, const cl::opt
<bool> &Default
) {
233 if (!O
.getNumOccurrences() || O
.getPosition() < Default
.getPosition())
234 O
= Default
.getValue();
237 static void processViewOptions() {
238 if (!EnableAllViews
.getNumOccurrences() &&
239 !EnableAllStats
.getNumOccurrences())
242 if (EnableAllViews
.getNumOccurrences()) {
243 processOptionImpl(PrintSummaryView
, EnableAllViews
);
244 processOptionImpl(EnableBottleneckAnalysis
, EnableAllViews
);
245 processOptionImpl(PrintResourcePressureView
, EnableAllViews
);
246 processOptionImpl(PrintTimelineView
, EnableAllViews
);
247 processOptionImpl(PrintInstructionInfoView
, EnableAllViews
);
250 const cl::opt
<bool> &Default
=
251 EnableAllViews
.getPosition() < EnableAllStats
.getPosition()
254 processOptionImpl(PrintRegisterFileStats
, Default
);
255 processOptionImpl(PrintDispatchStats
, Default
);
256 processOptionImpl(PrintSchedulerStats
, Default
);
257 processOptionImpl(PrintRetireStats
, Default
);
260 // Returns true on success.
261 static bool runPipeline(mca::Pipeline
&P
) {
262 // Handle pipeline errors here.
263 Expected
<unsigned> Cycles
= P
.run();
265 WithColor::error() << toString(Cycles
.takeError());
271 int main(int argc
, char **argv
) {
272 InitLLVM
X(argc
, argv
);
274 // Initialize targets and assembly parsers.
275 InitializeAllTargetInfos();
276 InitializeAllTargetMCs();
277 InitializeAllAsmParsers();
279 // Enable printing of available targets when flag --version is specified.
280 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
282 cl::HideUnrelatedOptions({&ToolOptions
, &ViewOptions
});
284 // Parse flags and initialize target options.
285 cl::ParseCommandLineOptions(argc
, argv
,
286 "llvm machine code performance analyzer.\n");
288 // Get the target from the triple. If a triple is not specified, then select
289 // the default triple for the host. If the triple doesn't correspond to any
290 // registered target, then exit with an error message.
291 const char *ProgName
= argv
[0];
292 const Target
*TheTarget
= getTarget(ProgName
);
296 // GetTarget() may replaced TripleName with a default triple.
297 // For safety, reconstruct the Triple object.
298 Triple
TheTriple(TripleName
);
300 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> BufferPtr
=
301 MemoryBuffer::getFileOrSTDIN(InputFilename
);
302 if (std::error_code EC
= BufferPtr
.getError()) {
303 WithColor::error() << InputFilename
<< ": " << EC
.message() << '\n';
307 // Apply overrides to llvm-mca specific options.
308 processViewOptions();
312 // Tell SrcMgr about this buffer, which is what the parser will pick up.
313 SrcMgr
.AddNewSourceBuffer(std::move(*BufferPtr
), SMLoc());
315 std::unique_ptr
<MCRegisterInfo
> MRI(TheTarget
->createMCRegInfo(TripleName
));
316 assert(MRI
&& "Unable to create target register info!");
318 std::unique_ptr
<MCAsmInfo
> MAI(TheTarget
->createMCAsmInfo(*MRI
, TripleName
));
319 assert(MAI
&& "Unable to create target asm info!");
321 MCObjectFileInfo MOFI
;
322 MCContext
Ctx(MAI
.get(), MRI
.get(), &MOFI
, &SrcMgr
);
323 MOFI
.InitMCObjectFileInfo(TheTriple
, /* PIC= */ false, Ctx
);
325 std::unique_ptr
<buffer_ostream
> BOS
;
327 std::unique_ptr
<MCInstrInfo
> MCII(TheTarget
->createMCInstrInfo());
329 std::unique_ptr
<MCInstrAnalysis
> MCIA(
330 TheTarget
->createMCInstrAnalysis(MCII
.get()));
332 if (!MCPU
.compare("native"))
333 MCPU
= llvm::sys::getHostCPUName();
335 std::unique_ptr
<MCSubtargetInfo
> STI(
336 TheTarget
->createMCSubtargetInfo(TripleName
, MCPU
, /* FeaturesStr */ ""));
337 if (!STI
->isCPUStringValid(MCPU
))
340 if (!PrintInstructionTables
&& !STI
->getSchedModel().isOutOfOrder()) {
341 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
342 << "' is an in-order cpu.\n";
346 if (!STI
->getSchedModel().hasInstrSchedModel()) {
348 << "unable to find instruction-level scheduling information for"
349 << " target triple '" << TheTriple
.normalize() << "' and cpu '" << MCPU
352 if (STI
->getSchedModel().InstrItineraries
)
354 << "cpu '" << MCPU
<< "' provides itineraries. However, "
355 << "instruction itineraries are currently unsupported.\n";
359 // Parse the input and create CodeRegions that llvm-mca can analyze.
360 mca::AsmCodeRegionGenerator
CRG(*TheTarget
, SrcMgr
, Ctx
, *MAI
, *STI
, *MCII
);
361 Expected
<const mca::CodeRegions
&> RegionsOrErr
= CRG
.parseCodeRegions();
364 handleErrors(RegionsOrErr
.takeError(), [](const StringError
&E
) {
365 WithColor::error() << E
.getMessage() << '\n';
368 WithColor::error() << toString(std::move(Err
)) << '\n';
372 const mca::CodeRegions
&Regions
= *RegionsOrErr
;
374 // Early exit if errors were found by the code region parsing logic.
375 if (!Regions
.isValid())
378 if (Regions
.empty()) {
379 WithColor::error() << "no assembly instructions found.\n";
383 // Now initialize the output file.
384 auto OF
= getOutputStream();
385 if (std::error_code EC
= OF
.getError()) {
386 WithColor::error() << EC
.message() << '\n';
390 unsigned AssemblerDialect
= CRG
.getAssemblerDialect();
391 if (OutputAsmVariant
>= 0)
392 AssemblerDialect
= static_cast<unsigned>(OutputAsmVariant
);
393 std::unique_ptr
<MCInstPrinter
> IP(TheTarget
->createMCInstPrinter(
394 Triple(TripleName
), AssemblerDialect
, *MAI
, *MCII
, *MRI
));
397 << "unable to create instruction printer for target triple '"
398 << TheTriple
.normalize() << "' with assembly variant "
399 << AssemblerDialect
<< ".\n";
403 // Set the display preference for hex vs. decimal immediates.
404 IP
->setPrintImmHex(PrintImmHex
);
406 std::unique_ptr
<ToolOutputFile
> TOF
= std::move(*OF
);
408 const MCSchedModel
&SM
= STI
->getSchedModel();
410 // Create an instruction builder.
411 mca::InstrBuilder
IB(*STI
, *MCII
, *MRI
, MCIA
.get());
413 // Create a context to control ownership of the pipeline hardware.
414 mca::Context
MCA(*MRI
, *STI
);
416 mca::PipelineOptions
PO(MicroOpQueue
, DecoderThroughput
, DispatchWidth
,
417 RegisterFileSize
, LoadQueueSize
, StoreQueueSize
,
418 AssumeNoAlias
, EnableBottleneckAnalysis
);
420 // Number each region in the sequence.
421 unsigned RegionIdx
= 0;
423 for (const std::unique_ptr
<mca::CodeRegion
> &Region
: Regions
) {
424 // Skip empty code regions.
428 // Don't print the header of this region if it is the default region, and
429 // it doesn't have an end location.
430 if (Region
->startLoc().isValid() || Region
->endLoc().isValid()) {
431 TOF
->os() << "\n[" << RegionIdx
++ << "] Code Region";
432 StringRef Desc
= Region
->getDescription();
434 TOF
->os() << " - " << Desc
;
438 // Lower the MCInst sequence into an mca::Instruction sequence.
439 ArrayRef
<MCInst
> Insts
= Region
->getInstructions();
440 std::vector
<std::unique_ptr
<mca::Instruction
>> LoweredSequence
;
441 for (const MCInst
&MCI
: Insts
) {
442 Expected
<std::unique_ptr
<mca::Instruction
>> Inst
=
443 IB
.createInstruction(MCI
);
445 if (auto NewE
= handleErrors(
447 [&IP
, &STI
](const mca::InstructionError
<MCInst
> &IE
) {
448 std::string InstructionStr
;
449 raw_string_ostream
SS(InstructionStr
);
450 WithColor::error() << IE
.Message
<< '\n';
451 IP
->printInst(&IE
.Inst
, SS
, "", *STI
);
454 << "instruction: " << InstructionStr
<< '\n';
457 WithColor::error() << toString(std::move(NewE
));
462 LoweredSequence
.emplace_back(std::move(Inst
.get()));
465 mca::SourceMgr
S(LoweredSequence
, PrintInstructionTables
? 1 : Iterations
);
467 if (PrintInstructionTables
) {
468 // Create a pipeline, stages, and a printer.
469 auto P
= llvm::make_unique
<mca::Pipeline
>();
470 P
->appendStage(llvm::make_unique
<mca::EntryStage
>(S
));
471 P
->appendStage(llvm::make_unique
<mca::InstructionTables
>(SM
));
472 mca::PipelinePrinter
Printer(*P
);
474 // Create the views for this pipeline, execute, and emit a report.
475 if (PrintInstructionInfoView
) {
476 Printer
.addView(llvm::make_unique
<mca::InstructionInfoView
>(
477 *STI
, *MCII
, Insts
, *IP
));
480 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
482 if (!runPipeline(*P
))
485 Printer
.printReport(TOF
->os());
489 // Create a basic pipeline simulating an out-of-order backend.
490 auto P
= MCA
.createDefaultPipeline(PO
, IB
, S
);
491 mca::PipelinePrinter
Printer(*P
);
493 if (PrintSummaryView
)
495 llvm::make_unique
<mca::SummaryView
>(SM
, Insts
, DispatchWidth
));
497 if (EnableBottleneckAnalysis
) {
498 Printer
.addView(llvm::make_unique
<mca::BottleneckAnalysis
>(
499 *STI
, *IP
, Insts
, S
.getNumIterations()));
502 if (PrintInstructionInfoView
)
504 llvm::make_unique
<mca::InstructionInfoView
>(*STI
, *MCII
, Insts
, *IP
));
506 if (PrintDispatchStats
)
507 Printer
.addView(llvm::make_unique
<mca::DispatchStatistics
>());
509 if (PrintSchedulerStats
)
510 Printer
.addView(llvm::make_unique
<mca::SchedulerStatistics
>(*STI
));
512 if (PrintRetireStats
)
513 Printer
.addView(llvm::make_unique
<mca::RetireControlUnitStatistics
>(SM
));
515 if (PrintRegisterFileStats
)
516 Printer
.addView(llvm::make_unique
<mca::RegisterFileStatistics
>(*STI
));
518 if (PrintResourcePressureView
)
520 llvm::make_unique
<mca::ResourcePressureView
>(*STI
, *IP
, Insts
));
522 if (PrintTimelineView
) {
523 unsigned TimelineIterations
=
524 TimelineMaxIterations
? TimelineMaxIterations
: 10;
525 Printer
.addView(llvm::make_unique
<mca::TimelineView
>(
526 *STI
, *IP
, Insts
, std::min(TimelineIterations
, S
.getNumIterations()),
530 if (!runPipeline(*P
))
533 Printer
.printReport(TOF
->os());
535 // Clear the InstrBuilder internal state in preparation for another round.