]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/llvm-mca/llvm-mca.cpp
Merge ^/head r343571 through r343711.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / llvm-mca / llvm-mca.cpp
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 "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"
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> LoadQueueSize("lqueue",
153                                        cl::desc("Size of the load queue"),
154                                        cl::cat(ToolOptions), cl::init(0));
155
156 static cl::opt<unsigned> StoreQueueSize("squeue",
157                                         cl::desc("Size of the store queue"),
158                                         cl::cat(ToolOptions), cl::init(0));
159
160 static cl::opt<bool>
161     PrintInstructionTables("instruction-tables",
162                            cl::desc("Print instruction tables"),
163                            cl::cat(ToolOptions), cl::init(false));
164
165 static cl::opt<bool> PrintInstructionInfoView(
166     "instruction-info",
167     cl::desc("Print the instruction info view (enabled by default)"),
168     cl::cat(ViewOptions), cl::init(true));
169
170 static cl::opt<bool> EnableAllStats("all-stats",
171                                     cl::desc("Print all hardware statistics"),
172                                     cl::cat(ViewOptions), cl::init(false));
173
174 static cl::opt<bool>
175     EnableAllViews("all-views",
176                    cl::desc("Print all views including hardware statistics"),
177                    cl::cat(ViewOptions), cl::init(false));
178
179 namespace {
180
181 const Target *getTarget(const char *ProgName) {
182   if (TripleName.empty())
183     TripleName = Triple::normalize(sys::getDefaultTargetTriple());
184   Triple TheTriple(TripleName);
185
186   // Get the target specific parser.
187   std::string Error;
188   const Target *TheTarget =
189       TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
190   if (!TheTarget) {
191     errs() << ProgName << ": " << Error;
192     return nullptr;
193   }
194
195   // Return the found target.
196   return TheTarget;
197 }
198
199 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
200   if (OutputFilename == "")
201     OutputFilename = "-";
202   std::error_code EC;
203   auto Out =
204       llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
205   if (!EC)
206     return std::move(Out);
207   return EC;
208 }
209 } // end of anonymous namespace
210
211 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
212   if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
213     O = Default.getValue();
214 }
215
216 static void processViewOptions() {
217   if (!EnableAllViews.getNumOccurrences() &&
218       !EnableAllStats.getNumOccurrences())
219     return;
220
221   if (EnableAllViews.getNumOccurrences()) {
222     processOptionImpl(PrintSummaryView, EnableAllViews);
223     processOptionImpl(PrintResourcePressureView, EnableAllViews);
224     processOptionImpl(PrintTimelineView, EnableAllViews);
225     processOptionImpl(PrintInstructionInfoView, EnableAllViews);
226   }
227
228   const cl::opt<bool> &Default =
229       EnableAllViews.getPosition() < EnableAllStats.getPosition()
230           ? EnableAllStats
231           : EnableAllViews;
232   processOptionImpl(PrintRegisterFileStats, Default);
233   processOptionImpl(PrintDispatchStats, Default);
234   processOptionImpl(PrintSchedulerStats, Default);
235   processOptionImpl(PrintRetireStats, Default);
236 }
237
238 // Returns true on success.
239 static bool runPipeline(mca::Pipeline &P) {
240   // Handle pipeline errors here.
241   Expected<unsigned> Cycles = P.run();
242   if (!Cycles) {
243     WithColor::error() << toString(Cycles.takeError());
244     return false;
245   }
246   return true;
247 }
248
249 int main(int argc, char **argv) {
250   InitLLVM X(argc, argv);
251
252   // Initialize targets and assembly parsers.
253   InitializeAllTargetInfos();
254   InitializeAllTargetMCs();
255   InitializeAllAsmParsers();
256
257   // Enable printing of available targets when flag --version is specified.
258   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
259
260   cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
261
262   // Parse flags and initialize target options.
263   cl::ParseCommandLineOptions(argc, argv,
264                               "llvm machine code performance analyzer.\n");
265
266   // Get the target from the triple. If a triple is not specified, then select
267   // the default triple for the host. If the triple doesn't correspond to any
268   // registered target, then exit with an error message.
269   const char *ProgName = argv[0];
270   const Target *TheTarget = getTarget(ProgName);
271   if (!TheTarget)
272     return 1;
273
274   // GetTarget() may replaced TripleName with a default triple.
275   // For safety, reconstruct the Triple object.
276   Triple TheTriple(TripleName);
277
278   ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
279       MemoryBuffer::getFileOrSTDIN(InputFilename);
280   if (std::error_code EC = BufferPtr.getError()) {
281     WithColor::error() << InputFilename << ": " << EC.message() << '\n';
282     return 1;
283   }
284
285   // Apply overrides to llvm-mca specific options.
286   processViewOptions();
287
288   SourceMgr SrcMgr;
289
290   // Tell SrcMgr about this buffer, which is what the parser will pick up.
291   SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
292
293   std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
294   assert(MRI && "Unable to create target register info!");
295
296   std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
297   assert(MAI && "Unable to create target asm info!");
298
299   MCObjectFileInfo MOFI;
300   MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
301   MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
302
303   std::unique_ptr<buffer_ostream> BOS;
304
305   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
306
307   std::unique_ptr<MCInstrAnalysis> MCIA(
308       TheTarget->createMCInstrAnalysis(MCII.get()));
309
310   if (!MCPU.compare("native"))
311     MCPU = llvm::sys::getHostCPUName();
312
313   std::unique_ptr<MCSubtargetInfo> STI(
314       TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
315   if (!STI->isCPUStringValid(MCPU))
316     return 1;
317
318   if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
319     WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
320                        << "' is an in-order cpu.\n";
321     return 1;
322   }
323
324   if (!STI->getSchedModel().hasInstrSchedModel()) {
325     WithColor::error()
326         << "unable to find instruction-level scheduling information for"
327         << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
328         << "'.\n";
329
330     if (STI->getSchedModel().InstrItineraries)
331       WithColor::note()
332           << "cpu '" << MCPU << "' provides itineraries. However, "
333           << "instruction itineraries are currently unsupported.\n";
334     return 1;
335   }
336
337   // Parse the input and create CodeRegions that llvm-mca can analyze.
338   mca::AsmCodeRegionGenerator CRG(*TheTarget, SrcMgr, Ctx, *MAI, *STI, *MCII);
339   Expected<const mca::CodeRegions &> RegionsOrErr = CRG.parseCodeRegions();
340   if (!RegionsOrErr) {
341     if (auto Err =
342             handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {
343               WithColor::error() << E.getMessage() << '\n';
344             })) {
345       // Default case.
346       WithColor::error() << toString(std::move(Err)) << '\n';
347     }
348     return 1;
349   }
350   const mca::CodeRegions &Regions = *RegionsOrErr;
351   if (Regions.empty()) {
352     WithColor::error() << "no assembly instructions found.\n";
353     return 1;
354   }
355
356   // Now initialize the output file.
357   auto OF = getOutputStream();
358   if (std::error_code EC = OF.getError()) {
359     WithColor::error() << EC.message() << '\n';
360     return 1;
361   }
362
363   unsigned AssemblerDialect = CRG.getAssemblerDialect();
364   if (OutputAsmVariant >= 0)
365     AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
366   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
367       Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
368   if (!IP) {
369     WithColor::error()
370         << "unable to create instruction printer for target triple '"
371         << TheTriple.normalize() << "' with assembly variant "
372         << AssemblerDialect << ".\n";
373     return 1;
374   }
375
376   std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
377
378   const MCSchedModel &SM = STI->getSchedModel();
379
380   unsigned Width = SM.IssueWidth;
381   if (DispatchWidth)
382     Width = DispatchWidth;
383
384   // Create an instruction builder.
385   mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get());
386
387   // Create a context to control ownership of the pipeline hardware.
388   mca::Context MCA(*MRI, *STI);
389
390   mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
391                           StoreQueueSize, AssumeNoAlias);
392
393   // Number each region in the sequence.
394   unsigned RegionIdx = 0;
395
396   for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
397     // Skip empty code regions.
398     if (Region->empty())
399       continue;
400
401     // Don't print the header of this region if it is the default region, and
402     // it doesn't have an end location.
403     if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
404       TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
405       StringRef Desc = Region->getDescription();
406       if (!Desc.empty())
407         TOF->os() << " - " << Desc;
408       TOF->os() << "\n\n";
409     }
410
411     // Lower the MCInst sequence into an mca::Instruction sequence.
412     ArrayRef<MCInst> Insts = Region->getInstructions();
413     std::vector<std::unique_ptr<mca::Instruction>> LoweredSequence;
414     for (const MCInst &MCI : Insts) {
415       Expected<std::unique_ptr<mca::Instruction>> Inst =
416           IB.createInstruction(MCI);
417       if (!Inst) {
418         if (auto NewE = handleErrors(
419                 Inst.takeError(),
420                 [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
421                   std::string InstructionStr;
422                   raw_string_ostream SS(InstructionStr);
423                   WithColor::error() << IE.Message << '\n';
424                   IP->printInst(&IE.Inst, SS, "", *STI);
425                   SS.flush();
426                   WithColor::note() << "instruction: " << InstructionStr
427                                     << '\n';
428                 })) {
429           // Default case.
430           WithColor::error() << toString(std::move(NewE));
431         }
432         return 1;
433       }
434
435       LoweredSequence.emplace_back(std::move(Inst.get()));
436     }
437
438     mca::SourceMgr S(LoweredSequence, PrintInstructionTables ? 1 : Iterations);
439
440     if (PrintInstructionTables) {
441       //  Create a pipeline, stages, and a printer.
442       auto P = llvm::make_unique<mca::Pipeline>();
443       P->appendStage(llvm::make_unique<mca::EntryStage>(S));
444       P->appendStage(llvm::make_unique<mca::InstructionTables>(SM));
445       mca::PipelinePrinter Printer(*P);
446
447       // Create the views for this pipeline, execute, and emit a report.
448       if (PrintInstructionInfoView) {
449         Printer.addView(llvm::make_unique<mca::InstructionInfoView>(
450             *STI, *MCII, Insts, *IP));
451       }
452       Printer.addView(
453           llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
454
455       if (!runPipeline(*P))
456         return 1;
457
458       Printer.printReport(TOF->os());
459       continue;
460     }
461
462     // Create a basic pipeline simulating an out-of-order backend.
463     auto P = MCA.createDefaultPipeline(PO, IB, S);
464     mca::PipelinePrinter Printer(*P);
465
466     if (PrintSummaryView)
467       Printer.addView(llvm::make_unique<mca::SummaryView>(SM, Insts, Width));
468
469     if (PrintInstructionInfoView)
470       Printer.addView(
471           llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, Insts, *IP));
472
473     if (PrintDispatchStats)
474       Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
475
476     if (PrintSchedulerStats)
477       Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
478
479     if (PrintRetireStats)
480       Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>(SM));
481
482     if (PrintRegisterFileStats)
483       Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
484
485     if (PrintResourcePressureView)
486       Printer.addView(
487           llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));
488
489     if (PrintTimelineView) {
490       unsigned TimelineIterations =
491           TimelineMaxIterations ? TimelineMaxIterations : 10;
492       Printer.addView(llvm::make_unique<mca::TimelineView>(
493           *STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),
494           TimelineMaxCycles));
495     }
496
497     if (!runPipeline(*P))
498       return 1;
499
500     Printer.printReport(TOF->os());
501
502     // Clear the InstrBuilder internal state in preparation for another round.
503     IB.clear();
504   }
505
506   TOF->keep();
507   return 0;
508 }