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