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