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