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   if (IsOutOfOrder)
282     processOptionImpl(PrintRetireStats, Default);
283 }
284 
285 // Returns true on success.
286 static bool runPipeline(mca::Pipeline &P) {
287   // Handle pipeline errors here.
288   Expected<unsigned> Cycles = P.run();
289   if (!Cycles) {
290     WithColor::error() << toString(Cycles.takeError());
291     return false;
292   }
293   return true;
294 }
295 
296 int main(int argc, char **argv) {
297   InitLLVM X(argc, argv);
298 
299   // Initialize targets and assembly parsers.
300   InitializeAllTargetInfos();
301   InitializeAllTargetMCs();
302   InitializeAllAsmParsers();
303 
304   // Enable printing of available targets when flag --version is specified.
305   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
306 
307   cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
308 
309   // Parse flags and initialize target options.
310   cl::ParseCommandLineOptions(argc, argv,
311                               "llvm machine code performance analyzer.\n");
312 
313   // Get the target from the triple. If a triple is not specified, then select
314   // the default triple for the host. If the triple doesn't correspond to any
315   // registered target, then exit with an error message.
316   const char *ProgName = argv[0];
317   const Target *TheTarget = getTarget(ProgName);
318   if (!TheTarget)
319     return 1;
320 
321   // GetTarget() may replaced TripleName with a default triple.
322   // For safety, reconstruct the Triple object.
323   Triple TheTriple(TripleName);
324 
325   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
326       MemoryBuffer::getFileOrSTDIN(InputFilename);
327   if (std::error_code EC = BufferPtr.getError()) {
328     WithColor::error() << InputFilename << ": " << EC.message() << '\n';
329     return 1;
330   }
331 
332   if (MCPU == "native")
333     MCPU = std::string(llvm::sys::getHostCPUName());
334 
335   std::unique_ptr<MCSubtargetInfo> STI(
336       TheTarget->createMCSubtargetInfo(TripleName, MCPU, MATTR));
337   assert(STI && "Unable to create subtarget info!");
338   if (!STI->isCPUStringValid(MCPU))
339     return 1;
340 
341   bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
342   if (!PrintInstructionTables && !IsOutOfOrder) {
343     WithColor::warning() << "support for in-order CPU '" << MCPU
344                          << "' is experimental.\n";
345   }
346 
347   if (!STI->getSchedModel().hasInstrSchedModel()) {
348     WithColor::error()
349         << "unable to find instruction-level scheduling information for"
350         << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
351         << "'.\n";
352 
353     if (STI->getSchedModel().InstrItineraries)
354       WithColor::note()
355           << "cpu '" << MCPU << "' provides itineraries. However, "
356           << "instruction itineraries are currently unsupported.\n";
357     return 1;
358   }
359 
360   // Apply overrides to llvm-mca specific options.
361   processViewOptions(IsOutOfOrder);
362 
363   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
364   assert(MRI && "Unable to create target register info!");
365 
366   MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
367   std::unique_ptr<MCAsmInfo> MAI(
368       TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));
369   assert(MAI && "Unable to create target asm info!");
370 
371   MCObjectFileInfo MOFI;
372   SourceMgr SrcMgr;
373 
374   // Tell SrcMgr about this buffer, which is what the parser will pick up.
375   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
376 
377   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
378 
379   MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
380 
381   std::unique_ptr<buffer_ostream> BOS;
382 
383   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
384   assert(MCII && "Unable to create instruction info!");
385 
386   std::unique_ptr<MCInstrAnalysis> MCIA(
387       TheTarget->createMCInstrAnalysis(MCII.get()));
388 
389   // Parse the input and create CodeRegions that llvm-mca can analyze.
390   mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
391   Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
392   if (!RegionsOrErr) {
393     if (auto Err =
394             handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
395               WithColor::error() << E.getMessage() << '\n';
396             })) {
397       // Default case.
398       WithColor::error() << toString(std::move(Err)) << '\n';
399     }
400     return 1;
401   }
402   const mca::CodeRegions &Regions = *RegionsOrErr;
403 
404   // Early exit if errors were found by the code region parsing logic.
405   if (!Regions.isValid())
406     return 1;
407 
408   if (Regions.empty()) {
409     WithColor::error() << "no assembly instructions found.\n";
410     return 1;
411   }
412 
413   // Now initialize the output file.
414   auto OF = getOutputStream();
415   if (std::error_code EC = OF.getError()) {
416     WithColor::error() << EC.message() << '\n';
417     return 1;
418   }
419 
420   unsigned AssemblerDialect = CRG.getAssemblerDialect();
421   if (OutputAsmVariant >= 0)
422     AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
423   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
424       Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
425   if (!IP) {
426     WithColor::error()
427         << "unable to create instruction printer for target triple '"
428         << TheTriple.normalize() << "' with assembly variant "
429         << AssemblerDialect << ".\n";
430     return 1;
431   }
432 
433   // Set the display preference for hex vs. decimal immediates.
434   IP->setPrintImmHex(PrintImmHex);
435 
436   std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
437 
438   const MCSchedModel &SM = STI->getSchedModel();
439 
440   // Create an instruction builder.
441   mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
442 
443   // Create a context to control ownership of the pipeline hardware.
444   mca::Context MCA(*MRI, *STI);
445 
446   mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
447                           RegisterFileSize, LoadQueueSize, StoreQueueSize,
448                           AssumeNoAlias, EnableBottleneckAnalysis);
449 
450   // Number each region in the sequence.
451   unsigned RegionIdx = 0;
452 
453   std::unique_ptr<MCCodeEmitter> MCE(
454       TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx));
455   assert(MCE && "Unable to create code emitter!");
456 
457   std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
458       *STI, *MRI, mc::InitMCTargetOptionsFromFlags()));
459   assert(MAB && "Unable to create asm backend!");
460 
461   for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
462     // Skip empty code regions.
463     if (Region->empty())
464       continue;
465 
466     // Don't print the header of this region if it is the default region, and
467     // it doesn't have an end location.
468     if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
469       TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
470       StringRef Desc = Region->getDescription();
471       if (!Desc.empty())
472         TOF->os() << " - " << Desc;
473       TOF->os() << "\n\n";
474     }
475 
476     // Lower the MCInst sequence into an mca::Instruction sequence.
477     ArrayRef<MCInst> Insts = Region->getInstructions();
478     mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
479     std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
480     for (const MCInst &MCI : Insts) {
481       Expected<std::unique_ptr<mca::Instruction>> Inst =
482           IB.createInstruction(MCI);
483       if (!Inst) {
484         if (auto NewE = handleErrors(
485                 Inst.takeError(),
486                 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
487                   std::string InstructionStr;
488                   raw_string_ostream SS(InstructionStr);
489                   WithColor::error() << IE.Message << '\n';
490                   IP->printInst(&IE.Inst, 0, "", *STI, SS);
491                   SS.flush();
492                   WithColor::note()
493                       << "instruction: " << InstructionStr << '\n';
494                 })) {
495           // Default case.
496           WithColor::error() << toString(std::move(NewE));
497         }
498         return 1;
499       }
500 
501       LoweredSequence.emplace_back(std::move(Inst.get()));
502     }
503 
504     mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
505 
506     if (PrintInstructionTables) {
507       //  Create a pipeline, stages, and a printer.
508       auto P = std::make_unique<mca::Pipeline>();
509       P->appendStage(std::make_unique<mca::EntryStage>(S));
510       P->appendStage(std::make_unique<mca::InstructionTables>(SM));
511       mca::PipelinePrinter Printer(*P, mca::View::OK_READABLE);
512 
513       // Create the views for this pipeline, execute, and emit a report.
514       if (PrintInstructionInfoView) {
515         Printer.addView(std::make_unique<mca::InstructionInfoView>(
516             *STI, *MCII, CE, ShowEncoding, Insts, *IP));
517       }
518       Printer.addView(
519           std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
520 
521       if (!runPipeline(*P))
522         return 1;
523 
524       Printer.printReport(TOF->os());
525       continue;
526     }
527 
528     // Create a basic pipeline simulating an out-of-order backend.
529     auto P = MCA.createDefaultPipeline(PO, S);
530     mca::PipelinePrinter Printer(*P, PrintJson ? mca::View::OK_JSON
531                                                : mca::View::OK_READABLE);
532 
533     // When we output JSON, we add a view that contains the instructions
534     // and CPU resource information.
535     if (PrintJson)
536       Printer.addView(
537           std::make_unique<mca::InstructionView>(*STI, *IP, Insts, MCPU));
538 
539     if (PrintSummaryView)
540       Printer.addView(
541           std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));
542 
543     if (EnableBottleneckAnalysis) {
544       if (!IsOutOfOrder) {
545         WithColor::warning()
546             << "bottleneck analysis is not supported for in-order CPU '" << MCPU
547             << "'.\n";
548       }
549       Printer.addView(std::make_unique<mca::BottleneckAnalysis>(
550           *STI, *IP, Insts, S.getNumIterations()));
551     }
552 
553     if (PrintInstructionInfoView)
554       Printer.addView(std::make_unique<mca::InstructionInfoView>(
555           *STI, *MCII, CE, ShowEncoding, Insts, *IP));
556 
557     if (PrintDispatchStats)
558       Printer.addView(std::make_unique<mca::DispatchStatistics>());
559 
560     if (PrintSchedulerStats)
561       Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));
562 
563     if (PrintRetireStats)
564       Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));
565 
566     if (PrintRegisterFileStats)
567       Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));
568 
569     if (PrintResourcePressureView)
570       Printer.addView(
571           std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
572 
573     if (PrintTimelineView) {
574       unsigned TimelineIterations =
575           TimelineMaxIterations ? TimelineMaxIterations : 10;
576       Printer.addView(std::make_unique<mca::TimelineView>(
577           *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
578           TimelineMaxCycles));
579     }
580 
581     if (!runPipeline(*P))
582       return 1;
583 
584     Printer.printReport(TOF->os());
585 
586     // Clear the InstrBuilder internal state in preparation for another round.
587     IB.clear();
588   }
589 
590   TOF->keep();
591   return 0;
592 }
593