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.
11 //
12 //   llvm-mca [options] <file-name>
13 //      -march <type>
14 //      -mcpu <cpu>
15 //      -o <file>
16 //
17 // The target defaults to the host target.
18 // The cpu defaults to the 'native' host cpu.
19 // The output defaults to standard output.
20 //
21 //===----------------------------------------------------------------------===//
22 
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/MCAsmBackend.h"
36 #include "llvm/MC/MCAsmInfo.h"
37 #include "llvm/MC/MCCodeEmitter.h"
38 #include "llvm/MC/MCContext.h"
39 #include "llvm/MC/MCObjectFileInfo.h"
40 #include "llvm/MC/MCRegisterInfo.h"
41 #include "llvm/MC/MCSubtargetInfo.h"
42 #include "llvm/MC/MCTargetOptionsCommandFlags.h"
43 #include "llvm/MCA/CodeEmitter.h"
44 #include "llvm/MCA/Context.h"
45 #include "llvm/MCA/InstrBuilder.h"
46 #include "llvm/MCA/Pipeline.h"
47 #include "llvm/MCA/Stages/EntryStage.h"
48 #include "llvm/MCA/Stages/InstructionTables.h"
49 #include "llvm/MCA/Support.h"
50 #include "llvm/Support/CommandLine.h"
51 #include "llvm/Support/ErrorHandling.h"
52 #include "llvm/Support/ErrorOr.h"
53 #include "llvm/Support/FileSystem.h"
54 #include "llvm/Support/Host.h"
55 #include "llvm/Support/InitLLVM.h"
56 #include "llvm/Support/MemoryBuffer.h"
57 #include "llvm/Support/SourceMgr.h"
58 #include "llvm/Support/TargetRegistry.h"
59 #include "llvm/Support/TargetSelect.h"
60 #include "llvm/Support/ToolOutputFile.h"
61 #include "llvm/Support/WithColor.h"
62 
63 using namespace llvm;
64 
65 static mc::RegisterMCTargetOptionsFlags MOF;
66 
67 static cl::OptionCategory ToolOptions("Tool Options");
68 static cl::OptionCategory ViewOptions("View Options");
69 
70 static cl::opt<std::string> InputFilename(cl::Positional,
71                                           cl::desc("<input file>"),
72                                           cl::cat(ToolOptions), cl::init("-"));
73 
74 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
75                                            cl::init("-"), cl::cat(ToolOptions),
76                                            cl::value_desc("filename"));
77 
78 static cl::opt<std::string>
79     ArchName("march",
80              cl::desc("Target architecture. "
81                       "See -version for available targets"),
82              cl::cat(ToolOptions));
83 
84 static cl::opt<std::string>
85     TripleName("mtriple",
86                cl::desc("Target triple. See -version for available targets"),
87                cl::cat(ToolOptions));
88 
89 static cl::opt<std::string>
90     MCPU("mcpu",
91          cl::desc("Target a specific cpu type (-mcpu=help for details)"),
92          cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
93 
94 static cl::opt<std::string>
95     MATTR("mattr",
96           cl::desc("Additional target features."),
97           cl::cat(ToolOptions));
98 
99 static cl::opt<bool>
100     PrintJson("json",
101           cl::desc("Print the output in json format"),
102           cl::cat(ToolOptions), cl::init(false));
103 
104 static cl::opt<int>
105     OutputAsmVariant("output-asm-variant",
106                      cl::desc("Syntax variant to use for output printing"),
107                      cl::cat(ToolOptions), cl::init(-1));
108 
109 static cl::opt<bool>
110     PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),
111                 cl::desc("Prefer hex format when printing immediate values"));
112 
113 static cl::opt<unsigned> Iterations("iterations",
114                                     cl::desc("Number of iterations to run"),
115                                     cl::cat(ToolOptions), cl::init(0));
116 
117 static cl::opt<unsigned>
118     DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
119                   cl::cat(ToolOptions), cl::init(0));
120 
121 static cl::opt<unsigned>
122     RegisterFileSize("register-file-size",
123                      cl::desc("Maximum number of physical registers which can "
124                               "be used for register mappings"),
125                      cl::cat(ToolOptions), cl::init(0));
126 
127 static cl::opt<unsigned>
128     MicroOpQueue("micro-op-queue-size", cl::Hidden,
129                  cl::desc("Number of entries in the micro-op queue"),
130                  cl::cat(ToolOptions), cl::init(0));
131 
132 static cl::opt<unsigned>
133     DecoderThroughput("decoder-throughput", cl::Hidden,
134                       cl::desc("Maximum throughput from the decoders "
135                                "(instructions per cycle)"),
136                       cl::cat(ToolOptions), cl::init(0));
137 
138 static cl::opt<bool>
139     PrintRegisterFileStats("register-file-stats",
140                            cl::desc("Print register file statistics"),
141                            cl::cat(ViewOptions), cl::init(false));
142 
143 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
144                                         cl::desc("Print dispatch statistics"),
145                                         cl::cat(ViewOptions), cl::init(false));
146 
147 static cl::opt<bool>
148     PrintSummaryView("summary-view", cl::Hidden,
149                      cl::desc("Print summary view (enabled by default)"),
150                      cl::cat(ViewOptions), cl::init(true));
151 
152 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
153                                          cl::desc("Print scheduler statistics"),
154                                          cl::cat(ViewOptions), cl::init(false));
155 
156 static cl::opt<bool>
157     PrintRetireStats("retire-stats",
158                      cl::desc("Print retire control unit statistics"),
159                      cl::cat(ViewOptions), cl::init(false));
160 
161 static cl::opt<bool> PrintResourcePressureView(
162     "resource-pressure",
163     cl::desc("Print the resource pressure view (enabled by default)"),
164     cl::cat(ViewOptions), cl::init(true));
165 
166 static cl::opt<bool> PrintTimelineView("timeline",
167                                        cl::desc("Print the timeline view"),
168                                        cl::cat(ViewOptions), cl::init(false));
169 
170 static cl::opt<unsigned> TimelineMaxIterations(
171     "timeline-max-iterations",
172     cl::desc("Maximum number of iterations to print in timeline view"),
173     cl::cat(ViewOptions), cl::init(0));
174 
175 static cl::opt<unsigned> TimelineMaxCycles(
176     "timeline-max-cycles",
177     cl::desc(
178         "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
179     cl::cat(ViewOptions), cl::init(80));
180 
181 static cl::opt<bool>
182     AssumeNoAlias("noalias",
183                   cl::desc("If set, assume that loads and stores do not alias"),
184                   cl::cat(ToolOptions), cl::init(true));
185 
186 static cl::opt<unsigned> LoadQueueSize("lqueue",
187                                        cl::desc("Size of the load queue"),
188                                        cl::cat(ToolOptions), cl::init(0));
189 
190 static cl::opt<unsigned> StoreQueueSize("squeue",
191                                         cl::desc("Size of the store queue"),
192                                         cl::cat(ToolOptions), cl::init(0));
193 
194 static cl::opt<bool>
195     PrintInstructionTables("instruction-tables",
196                            cl::desc("Print instruction tables"),
197                            cl::cat(ToolOptions), cl::init(false));
198 
199 static cl::opt<bool> PrintInstructionInfoView(
200     "instruction-info",
201     cl::desc("Print the instruction info view (enabled by default)"),
202     cl::cat(ViewOptions), cl::init(true));
203 
204 static cl::opt<bool> EnableAllStats("all-stats",
205                                     cl::desc("Print all hardware statistics"),
206                                     cl::cat(ViewOptions), cl::init(false));
207 
208 static cl::opt<bool>
209     EnableAllViews("all-views",
210                    cl::desc("Print all views including hardware statistics"),
211                    cl::cat(ViewOptions), cl::init(false));
212 
213 static cl::opt<bool> EnableBottleneckAnalysis(
214     "bottleneck-analysis",
215     cl::desc("Enable bottleneck analysis (disabled by default)"),
216     cl::cat(ViewOptions), cl::init(false));
217 
218 static cl::opt<bool> ShowEncoding(
219     "show-encoding",
220     cl::desc("Print encoding information in the instruction info view"),
221     cl::cat(ViewOptions), cl::init(false));
222 
223 namespace {
224 
225 const Target *getTarget(const char *ProgName) {
226   if (TripleName.empty())
227     TripleName = Triple::normalize(sys::getDefaultTargetTriple());
228   Triple TheTriple(TripleName);
229 
230   // Get the target specific parser.
231   std::string Error;
232   const Target *TheTarget =
233       TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
234   if (!TheTarget) {
235     errs() << ProgName << ": " << Error;
236     return nullptr;
237   }
238 
239   // Return the found target.
240   return TheTarget;
241 }
242 
243 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
244   if (OutputFilename == "")
245     OutputFilename = "-";
246   std::error_code EC;
247   auto Out =
248       std::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::OF_Text);
249   if (!EC)
250     return std::move(Out);
251   return EC;
252 }
253 } // end of anonymous namespace
254 
255 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
256   if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
257     O = Default.getValue();
258 }
259 
260 static void processViewOptions(bool IsOutOfOrder) {
261   if (!EnableAllViews.getNumOccurrences() &&
262       !EnableAllStats.getNumOccurrences())
263     return;
264 
265   if (EnableAllViews.getNumOccurrences()) {
266     processOptionImpl(PrintSummaryView, EnableAllViews);
267     if (IsOutOfOrder)
268       processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);
269     processOptionImpl(PrintResourcePressureView, EnableAllViews);
270     processOptionImpl(PrintTimelineView, EnableAllViews);
271     processOptionImpl(PrintInstructionInfoView, EnableAllViews);
272   }
273 
274   const cl::opt<bool> &Default =
275       EnableAllViews.getPosition() < EnableAllStats.getPosition()
276           ? EnableAllStats
277           : EnableAllViews;
278   processOptionImpl(PrintRegisterFileStats, Default);
279   processOptionImpl(PrintDispatchStats, Default);
280   processOptionImpl(PrintSchedulerStats, Default);
281   processOptionImpl(PrintRetireStats, Default);
282 }
283 
284 // Returns true on success.
285 static bool runPipeline(mca::Pipeline &P) {
286   // Handle pipeline errors here.
287   Expected<unsigned> Cycles = P.run();
288   if (!Cycles) {
289     WithColor::error() << toString(Cycles.takeError());
290     return false;
291   }
292   return true;
293 }
294 
295 int main(int argc, char **argv) {
296   InitLLVM X(argc, argv);
297 
298   // Initialize targets and assembly parsers.
299   InitializeAllTargetInfos();
300   InitializeAllTargetMCs();
301   InitializeAllAsmParsers();
302 
303   // Enable printing of available targets when flag --version is specified.
304   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
305 
306   cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
307 
308   // Parse flags and initialize target options.
309   cl::ParseCommandLineOptions(argc, argv,
310                               "llvm machine code performance analyzer.\n");
311 
312   // Get the target from the triple. If a triple is not specified, then select
313   // the default triple for the host. If the triple doesn't correspond to any
314   // registered target, then exit with an error message.
315   const char *ProgName = argv[0];
316   const Target *TheTarget = getTarget(ProgName);
317   if (!TheTarget)
318     return 1;
319 
320   // GetTarget() may replaced TripleName with a default triple.
321   // For safety, reconstruct the Triple object.
322   Triple TheTriple(TripleName);
323 
324   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
325       MemoryBuffer::getFileOrSTDIN(InputFilename);
326   if (std::error_code EC = BufferPtr.getError()) {
327     WithColor::error() << InputFilename << ": " << EC.message() << '\n';
328     return 1;
329   }
330 
331   if (MCPU == "native")
332     MCPU = std::string(llvm::sys::getHostCPUName());
333 
334   std::unique_ptr<MCSubtargetInfo> STI(
335       TheTarget->createMCSubtargetInfo(TripleName, MCPU, MATTR));
336   assert(STI && "Unable to create subtarget info!");
337   if (!STI->isCPUStringValid(MCPU))
338     return 1;
339 
340   bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
341   if (!PrintInstructionTables && !IsOutOfOrder) {
342     WithColor::warning() << "support for in-order CPU '" << MCPU
343                          << "' is experimental.\n";
344   }
345 
346   if (!STI->getSchedModel().hasInstrSchedModel()) {
347     WithColor::error()
348         << "unable to find instruction-level scheduling information for"
349         << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
350         << "'.\n";
351 
352     if (STI->getSchedModel().InstrItineraries)
353       WithColor::note()
354           << "cpu '" << MCPU << "' provides itineraries. However, "
355           << "instruction itineraries are currently unsupported.\n";
356     return 1;
357   }
358 
359   // Apply overrides to llvm-mca specific options.
360   processViewOptions(IsOutOfOrder);
361 
362   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
363   assert(MRI && "Unable to create target register info!");
364 
365   MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
366   std::unique_ptr<MCAsmInfo> MAI(
367       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
368   assert(MAI && "Unable to create target asm info!");
369 
370   MCObjectFileInfo MOFI;
371   SourceMgr SrcMgr;
372 
373   // Tell SrcMgr about this buffer, which is what the parser will pick up.
374   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
375 
376   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
377 
378   MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
379 
380   std::unique_ptr<buffer_ostream> BOS;
381 
382   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
383   assert(MCII && "Unable to create instruction info!");
384 
385   std::unique_ptr<MCInstrAnalysis> MCIA(
386       TheTarget->createMCInstrAnalysis(MCII.get()));
387 
388   // Parse the input and create CodeRegions that llvm-mca can analyze.
389   mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
390   Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
391   if (!RegionsOrErr) {
392     if (auto Err =
393             handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
394               WithColor::error() << E.getMessage() << '\n';
395             })) {
396       // Default case.
397       WithColor::error() << toString(std::move(Err)) << '\n';
398     }
399     return 1;
400   }
401   const mca::CodeRegions &Regions = *RegionsOrErr;
402 
403   // Early exit if errors were found by the code region parsing logic.
404   if (!Regions.isValid())
405     return 1;
406 
407   if (Regions.empty()) {
408     WithColor::error() << "no assembly instructions found.\n";
409     return 1;
410   }
411 
412   // Now initialize the output file.
413   auto OF = getOutputStream();
414   if (std::error_code EC = OF.getError()) {
415     WithColor::error() << EC.message() << '\n';
416     return 1;
417   }
418 
419   unsigned AssemblerDialect = CRG.getAssemblerDialect();
420   if (OutputAsmVariant >= 0)
421     AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
422   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
423       Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
424   if (!IP) {
425     WithColor::error()
426         << "unable to create instruction printer for target triple '"
427         << TheTriple.normalize() << "' with assembly variant "
428         << AssemblerDialect << ".\n";
429     return 1;
430   }
431 
432   // Set the display preference for hex vs. decimal immediates.
433   IP->setPrintImmHex(PrintImmHex);
434 
435   std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
436 
437   const MCSchedModel &SM = STI->getSchedModel();
438 
439   // Create an instruction builder.
440   mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
441 
442   // Create a context to control ownership of the pipeline hardware.
443   mca::Context MCA(*MRI, *STI);
444 
445   mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
446                           RegisterFileSize, LoadQueueSize, StoreQueueSize,
447                           AssumeNoAlias, EnableBottleneckAnalysis);
448 
449   // Number each region in the sequence.
450   unsigned RegionIdx = 0;
451 
452   std::unique_ptr<MCCodeEmitter> MCE(
453       TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
454   assert(MCE && "Unable to create code emitter!");
455 
456   std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
457       *STI, *MRI, mc::InitMCTargetOptionsFromFlags()));
458   assert(MAB && "Unable to create asm backend!");
459 
460   for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
461     // Skip empty code regions.
462     if (Region->empty())
463       continue;
464 
465     // Don't print the header of this region if it is the default region, and
466     // it doesn't have an end location.
467     if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
468       TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
469       StringRef Desc = Region->getDescription();
470       if (!Desc.empty())
471         TOF->os() << " - " << Desc;
472       TOF->os() << "\n\n";
473     }
474 
475     // Lower the MCInst sequence into an mca::Instruction sequence.
476     ArrayRef<MCInst> Insts = Region->getInstructions();
477     mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
478     std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
479     for (const MCInst &MCI : Insts) {
480       Expected<std::unique_ptr<mca::Instruction>> Inst =
481           IB.createInstruction(MCI);
482       if (!Inst) {
483         if (auto NewE = handleErrors(
484                 Inst.takeError(),
485                 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
486                   std::string InstructionStr;
487                   raw_string_ostream SS(InstructionStr);
488                   WithColor::error() << IE.Message << '\n';
489                   IP->printInst(&IE.Inst, 0, "", *STI, SS);
490                   SS.flush();
491                   WithColor::note()
492                       << "instruction: " << InstructionStr << '\n';
493                 })) {
494           // Default case.
495           WithColor::error() << toString(std::move(NewE));
496         }
497         return 1;
498       }
499 
500       LoweredSequence.emplace_back(std::move(Inst.get()));
501     }
502 
503     mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
504 
505     if (PrintInstructionTables) {
506       //  Create a pipeline, stages, and a printer.
507       auto P = std::make_unique<mca::Pipeline>();
508       P->appendStage(std::make_unique<mca::EntryStage>(S));
509       P->appendStage(std::make_unique<mca::InstructionTables>(SM));
510       mca::PipelinePrinter Printer(*P, mca::View::OK_READABLE);
511 
512       // Create the views for this pipeline, execute, and emit a report.
513       if (PrintInstructionInfoView) {
514         Printer.addView(std::make_unique<mca::InstructionInfoView>(
515             *STI, *MCII, CE, ShowEncoding, Insts, *IP));
516       }
517       Printer.addView(
518           std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
519 
520       if (!runPipeline(*P))
521         return 1;
522 
523       Printer.printReport(TOF->os());
524       continue;
525     }
526 
527     // Create a basic pipeline simulating an out-of-order backend.
528     auto P = MCA.createDefaultPipeline(PO, S);
529     mca::PipelinePrinter Printer(*P, PrintJson ? mca::View::OK_JSON
530                                                : mca::View::OK_READABLE);
531 
532     // When we output JSON, we add a view that contains the instructions
533     // and CPU resource information.
534     if (PrintJson)
535       Printer.addView(
536           std::make_unique<mca::InstructionView>(*STI, *IP, Insts, MCPU));
537 
538     if (PrintSummaryView)
539       Printer.addView(
540           std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
541 
542     if (EnableBottleneckAnalysis) {
543       if (!IsOutOfOrder) {
544         WithColor::warning()
545             << "bottleneck analysis is not supported for in-order CPU '" << MCPU
546             << "'.\n";
547       }
548       Printer.addView(std::make_unique<mca::BottleneckAnalysis>(
549           *STI, *IP, Insts, S.getNumIterations()));
550     }
551 
552     if (PrintInstructionInfoView)
553       Printer.addView(std::make_unique<mca::InstructionInfoView>(
554           *STI, *MCII, CE, ShowEncoding, Insts, *IP));
555 
556     if (PrintDispatchStats)
557       Printer.addView(std::make_unique<mca::DispatchStatistics>());
558 
559     if (PrintSchedulerStats)
560       Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));
561 
562     if (PrintRetireStats)
563       Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));
564 
565     if (PrintRegisterFileStats)
566       Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));
567 
568     if (PrintResourcePressureView)
569       Printer.addView(
570           std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
571 
572     if (PrintTimelineView) {
573       unsigned TimelineIterations =
574           TimelineMaxIterations ? TimelineMaxIterations : 10;
575       Printer.addView(std::make_unique<mca::TimelineView>(
576           *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
577           TimelineMaxCycles));
578     }
579 
580     if (!runPipeline(*P))
581       return 1;
582 
583     Printer.printReport(TOF->os());
584 
585     // Clear the InstrBuilder internal state in preparation for another round.
586     IB.clear();
587   }
588 
589   TOF->keep();
590   return 0;
591 }
592