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