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 is derived from the triple if not specified; pass -mcpu=native to
19// select the 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/BottleneckAnalysis.h"
28#include "Views/DispatchStatistics.h"
29#include "Views/InstructionInfoView.h"
30#include "Views/RegisterFileStatistics.h"
31#include "Views/ResourcePressureView.h"
32#include "Views/RetireControlUnitStatistics.h"
33#include "Views/SchedulerStatistics.h"
34#include "Views/SummaryView.h"
35#include "Views/TimelineView.h"
36#include "llvm/MC/MCAsmBackend.h"
37#include "llvm/MC/MCAsmInfo.h"
38#include "llvm/MC/MCCodeEmitter.h"
39#include "llvm/MC/MCContext.h"
40#include "llvm/MC/MCObjectFileInfo.h"
41#include "llvm/MC/MCRegisterInfo.h"
42#include "llvm/MC/MCSchedule.h"
43#include "llvm/MC/MCSubtargetInfo.h"
44#include "llvm/MC/MCTargetOptionsCommandFlags.h"
45#include "llvm/MC/TargetRegistry.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/InitLLVM.h"
59#include "llvm/Support/LibraryOptionsContext.h"
60#include "llvm/Support/MemoryBuffer.h"
61#include "llvm/Support/SourceMgr.h"
62#include "llvm/Support/TargetSelect.h"
63#include "llvm/Support/ToolOutputFile.h"
64#include "llvm/Support/WithColor.h"
65#include "llvm/TargetParser/Host.h"
66
67using namespace llvm;
68
69static cl::OptionCategory ToolOptions("Tool Options");
70static cl::OptionCategory ViewOptions("View Options");
71
72static cl::opt<std::string> InputFilename(cl::Positional,
73 cl::desc("<input file>"),
74 cl::cat(ToolOptions), cl::init(Val: "-"));
75
76static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
77 cl::init(Val: "-"), cl::cat(ToolOptions),
78 cl::value_desc("filename"));
79
80static cl::opt<std::string>
81 ArchName("march",
82 cl::desc("Target architecture. "
83 "See -version for available targets"),
84 cl::cat(ToolOptions));
85
86static cl::opt<std::string>
87 TripleNameOpt("mtriple",
88 cl::desc("Target triple. See -version for available targets"),
89 cl::cat(ToolOptions));
90
91static cl::opt<std::string>
92 MCPU("mcpu",
93 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
94 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init(Val: ""));
95
96static cl::list<std::string>
97 MATTRS("mattr", cl::CommaSeparated,
98 cl::desc("Target specific attributes (-mattr=help for details)"),
99 cl::value_desc("a1,+a2,-a3,..."), cl::cat(ToolOptions));
100
101static cl::opt<bool> PrintJson("json",
102 cl::desc("Print the output in json format"),
103 cl::cat(ToolOptions), cl::init(Val: false));
104
105static cl::opt<int>
106 OutputAsmVariant("output-asm-variant",
107 cl::desc("Syntax variant to use for output printing"),
108 cl::cat(ToolOptions), cl::init(Val: -1));
109
110static cl::opt<bool>
111 PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(Val: false),
112 cl::desc("Prefer hex format when printing immediate values"));
113
114static cl::opt<unsigned> Iterations("iterations",
115 cl::desc("Number of iterations to run"),
116 cl::cat(ToolOptions), cl::init(Val: 0));
117
118static cl::opt<unsigned>
119 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
120 cl::cat(ToolOptions), cl::init(Val: 0));
121
122static cl::opt<unsigned>
123 RegisterFileSize("register-file-size",
124 cl::desc("Maximum number of physical registers which can "
125 "be used for register mappings"),
126 cl::cat(ToolOptions), cl::init(Val: 0));
127
128static cl::opt<unsigned>
129 MicroOpQueue("micro-op-queue-size", cl::Hidden,
130 cl::desc("Number of entries in the micro-op queue"),
131 cl::cat(ToolOptions), cl::init(Val: 0));
132
133static cl::opt<unsigned>
134 DecoderThroughput("decoder-throughput", cl::Hidden,
135 cl::desc("Maximum throughput from the decoders "
136 "(instructions per cycle)"),
137 cl::cat(ToolOptions), cl::init(Val: 0));
138
139static cl::opt<unsigned>
140 CallLatency("call-latency", cl::Hidden,
141 cl::desc("Number of cycles to assume for a call instruction"),
142 cl::cat(ToolOptions), cl::init(Val: 100U));
143
144enum class SkipType { NONE, LACK_SCHED, PARSE_FAILURE, ANY_FAILURE };
145
146static cl::opt<enum SkipType> SkipUnsupportedInstructions(
147 "skip-unsupported-instructions",
148 cl::desc("Force analysis to continue in the presence of unsupported "
149 "instructions"),
150 cl::values(
151 clEnumValN(SkipType::NONE, "none",
152 "Exit with an error when an instruction is unsupported for "
153 "any reason (default)"),
154 clEnumValN(
155 SkipType::LACK_SCHED, "lack-sched",
156 "Skip instructions on input which lack scheduling information"),
157 clEnumValN(
158 SkipType::PARSE_FAILURE, "parse-failure",
159 "Skip lines on the input which fail to parse for any reason"),
160 clEnumValN(SkipType::ANY_FAILURE, "any",
161 "Skip instructions or lines on input which are unsupported "
162 "for any reason")),
163 cl::init(Val: SkipType::NONE), cl::cat(ViewOptions));
164
165bool shouldSkip(enum SkipType skipType) {
166 if (SkipUnsupportedInstructions == SkipType::NONE)
167 return false;
168 if (SkipUnsupportedInstructions == SkipType::ANY_FAILURE)
169 return true;
170 return skipType == SkipUnsupportedInstructions;
171}
172
173static cl::opt<bool>
174 PrintRegisterFileStats("register-file-stats",
175 cl::desc("Print register file statistics"),
176 cl::cat(ViewOptions), cl::init(Val: false));
177
178static cl::opt<bool> PrintDispatchStats("dispatch-stats",
179 cl::desc("Print dispatch statistics"),
180 cl::cat(ViewOptions), cl::init(Val: false));
181
182static cl::opt<bool>
183 PrintSummaryView("summary-view", cl::Hidden,
184 cl::desc("Print summary view (enabled by default)"),
185 cl::cat(ViewOptions), cl::init(Val: true));
186
187static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
188 cl::desc("Print scheduler statistics"),
189 cl::cat(ViewOptions), cl::init(Val: false));
190
191static cl::opt<bool>
192 PrintRetireStats("retire-stats",
193 cl::desc("Print retire control unit statistics"),
194 cl::cat(ViewOptions), cl::init(Val: false));
195
196static cl::opt<bool> PrintResourcePressureView(
197 "resource-pressure",
198 cl::desc("Print the resource pressure view (enabled by default)"),
199 cl::cat(ViewOptions), cl::init(Val: true));
200
201static cl::opt<bool> PrintTimelineView("timeline",
202 cl::desc("Print the timeline view"),
203 cl::cat(ViewOptions), cl::init(Val: false));
204
205static cl::opt<unsigned> TimelineMaxIterations(
206 "timeline-max-iterations",
207 cl::desc("Maximum number of iterations to print in timeline view"),
208 cl::cat(ViewOptions), cl::init(Val: 0));
209
210static cl::opt<unsigned>
211 TimelineMaxCycles("timeline-max-cycles",
212 cl::desc("Maximum number of cycles in the timeline view, "
213 "or 0 for unlimited. Defaults to 80 cycles"),
214 cl::cat(ViewOptions), cl::init(Val: 80));
215
216static cl::opt<bool>
217 AssumeNoAlias("noalias",
218 cl::desc("If set, assume that loads and stores do not alias"),
219 cl::cat(ToolOptions), cl::init(Val: true));
220
221static cl::opt<unsigned> LoadQueueSize("lqueue",
222 cl::desc("Size of the load queue"),
223 cl::cat(ToolOptions), cl::init(Val: 0));
224
225static cl::opt<unsigned> StoreQueueSize("squeue",
226 cl::desc("Size of the store queue"),
227 cl::cat(ToolOptions), cl::init(Val: 0));
228
229enum class InstructionTablesType { NONE, NORMAL, FULL };
230
231static cl::opt<enum InstructionTablesType> InstructionTablesOption(
232 "instruction-tables", cl::desc("Print instruction tables"),
233 cl::values(clEnumValN(InstructionTablesType::NONE, "none",
234 "Do not print instruction tables"),
235 clEnumValN(InstructionTablesType::NORMAL, "normal",
236 "Print instruction tables"),
237 clEnumValN(InstructionTablesType::NORMAL, "", ""),
238 clEnumValN(InstructionTablesType::FULL, "full",
239 "Print instruction tables with additional"
240 " information: bypass latency, LLVM opcode,"
241 " used resources")),
242 cl::cat(ToolOptions), cl::init(Val: InstructionTablesType::NONE),
243 cl::ValueOptional);
244
245static bool shouldPrintInstructionTables(enum InstructionTablesType ITType) {
246 return InstructionTablesOption == ITType;
247}
248
249static bool shouldPrintInstructionTables() {
250 return !shouldPrintInstructionTables(ITType: InstructionTablesType::NONE);
251}
252
253static cl::opt<bool> PrintInstructionInfoView(
254 "instruction-info",
255 cl::desc("Print the instruction info view (enabled by default)"),
256 cl::cat(ViewOptions), cl::init(Val: true));
257
258static cl::opt<bool> EnableAllStats("all-stats",
259 cl::desc("Print all hardware statistics"),
260 cl::cat(ViewOptions), cl::init(Val: false));
261
262static cl::opt<bool>
263 EnableAllViews("all-views",
264 cl::desc("Print all views including hardware statistics"),
265 cl::cat(ViewOptions), cl::init(Val: false));
266
267static cl::opt<bool> EnableBottleneckAnalysis(
268 "bottleneck-analysis",
269 cl::desc("Enable bottleneck analysis (disabled by default)"),
270 cl::cat(ViewOptions), cl::init(Val: false));
271
272static cl::opt<bool> ShowEncoding(
273 "show-encoding",
274 cl::desc("Print encoding information in the instruction info view"),
275 cl::cat(ViewOptions), cl::init(Val: false));
276
277static cl::opt<bool> ShowBarriers(
278 "show-barriers",
279 cl::desc("Print memory barrier information in the instruction info view"),
280 cl::cat(ViewOptions), cl::init(Val: false));
281
282static cl::opt<bool> DisableCustomBehaviour(
283 "disable-cb",
284 cl::desc(
285 "Disable custom behaviour (use the default class which does nothing)."),
286 cl::cat(ViewOptions), cl::init(Val: false));
287
288static cl::opt<bool> DisableInstrumentManager(
289 "disable-im",
290 cl::desc("Disable instrumentation manager (use the default class which "
291 "ignores instruments.)."),
292 cl::cat(ViewOptions), cl::init(Val: false));
293
294namespace {
295
296const Target *getTarget(Triple &TheTriple, const char *ProgName) {
297 // Get the target specific parser.
298 std::string Error;
299 const Target *TheTarget =
300 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
301 if (!TheTarget) {
302 errs() << ProgName << ": " << Error;
303 return nullptr;
304 }
305
306 // Return the found target.
307 return TheTarget;
308}
309
310ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
311 if (OutputFilename == "")
312 OutputFilename = "-";
313 std::error_code EC;
314 auto Out = std::make_unique<ToolOutputFile>(args&: OutputFilename, args&: EC,
315 args: sys::fs::OF_TextWithCRLF);
316 if (!EC)
317 return std::move(Out);
318 return EC;
319}
320} // end of anonymous namespace
321
322static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
323 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
324 O = Default.getValue();
325}
326
327static void processViewOptions(bool IsOutOfOrder) {
328 if (!EnableAllViews.getNumOccurrences() &&
329 !EnableAllStats.getNumOccurrences())
330 return;
331
332 if (EnableAllViews.getNumOccurrences()) {
333 processOptionImpl(O&: PrintSummaryView, Default: EnableAllViews);
334 if (IsOutOfOrder)
335 processOptionImpl(O&: EnableBottleneckAnalysis, Default: EnableAllViews);
336 processOptionImpl(O&: PrintResourcePressureView, Default: EnableAllViews);
337 processOptionImpl(O&: PrintTimelineView, Default: EnableAllViews);
338 processOptionImpl(O&: PrintInstructionInfoView, Default: EnableAllViews);
339 }
340
341 const cl::opt<bool> &Default =
342 EnableAllViews.getPosition() < EnableAllStats.getPosition()
343 ? EnableAllStats
344 : EnableAllViews;
345 processOptionImpl(O&: PrintRegisterFileStats, Default);
346 processOptionImpl(O&: PrintDispatchStats, Default);
347 processOptionImpl(O&: PrintSchedulerStats, Default);
348 if (IsOutOfOrder)
349 processOptionImpl(O&: PrintRetireStats, Default);
350}
351
352// Returns true on success.
353static bool runPipeline(mca::Pipeline &P) {
354 // Handle pipeline errors here.
355 Expected<unsigned> Cycles = P.run();
356 if (!Cycles) {
357 WithColor::error() << toString(E: Cycles.takeError());
358 return false;
359 }
360 return true;
361}
362
363int main(int argc, char **argv) {
364 InitLLVM X(argc, argv);
365
366 // Initialize targets and assembly parsers.
367 InitializeAllTargetInfos();
368 InitializeAllTargetMCs();
369 InitializeAllAsmParsers();
370 InitializeAllTargetMCAs();
371
372 // Register the Target and CPU printer for --version.
373 cl::AddExtraVersionPrinter(func: sys::printDefaultTargetAndDetectedCPU);
374
375 // Enable printing of available targets when flag --version is specified.
376 cl::AddExtraVersionPrinter(func: TargetRegistry::printRegisteredTargetsForVersion);
377
378 cl::HideUnrelatedOptions(Categories: {&ToolOptions, &ViewOptions});
379
380 // Parse flags and initialize target options.
381 cl::LibraryOptionsContext LibraryOptions;
382 cl::parseCommandLineOptions(Context&: LibraryOptions, ToolOptions: mc::getToolOptions(),
383 Args: ArrayRef(argv, argc),
384 Overview: "llvm machine code performance analyzer.\n");
385
386 Triple TheTriple(TripleNameOpt.empty()
387 ? Triple::normalize(Str: sys::getDefaultTargetTriple())
388 : TripleNameOpt);
389
390 // Get the target from the triple. If a triple is not specified, then select
391 // the default triple for the host. If the triple doesn't correspond to any
392 // registered target, then exit with an error message.
393 const char *ProgName = argv[0];
394 const Target *TheTarget = getTarget(TheTriple, ProgName);
395 if (!TheTarget)
396 return 1;
397
398 const bool WantsCPUHelp = MCPU == "help";
399
400 std::unique_ptr<MemoryBuffer> InputBuffer;
401 if (!WantsCPUHelp) {
402 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
403 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename);
404 if (!BufferOrErr) {
405 std::error_code EC = BufferOrErr.getError();
406 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
407 return 1;
408 }
409 InputBuffer = std::move(*BufferOrErr);
410 }
411
412 if (MCPU == "native")
413 MCPU = std::string(llvm::sys::getHostCPUName());
414
415 // Package up features to be passed to target/subtarget
416 std::string FeaturesStr;
417 if (MATTRS.size()) {
418 SubtargetFeatures Features;
419 for (std::string &MAttr : MATTRS)
420 Features.AddFeature(String: MAttr);
421 FeaturesStr = Features.getString();
422 }
423
424 std::unique_ptr<MCSubtargetInfo> STI(
425 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: FeaturesStr));
426 if (!STI) {
427 WithColor::error() << "unable to create subtarget info\n";
428 return 1;
429 }
430
431 if (TheTriple.isAArch64() && STI->checkFeatures(FS: "+mca-streaming-sched"))
432 WithColor::warning()
433 << "AArch64 streaming SVE scheduling is enabled via "
434 "'-mattr=+mca-streaming-sched'; llvm-mca results are approximate.\n";
435
436 if (WantsCPUHelp)
437 return 0;
438
439 if (!STI->getSchedModel().hasInstrSchedModel()) {
440 WithColor::error()
441 << "unable to find instruction-level scheduling information for"
442 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
443 << "'.\n";
444
445 if (STI->getSchedModel().InstrItineraries)
446 WithColor::note()
447 << "cpu '" << MCPU << "' provides itineraries. However, "
448 << "instruction itineraries are currently unsupported.\n";
449 return 1;
450 }
451
452 // Apply overrides to llvm-mca specific options.
453 bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
454 processViewOptions(IsOutOfOrder);
455
456 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TheTriple));
457 assert(MRI && "Unable to create target register info!");
458
459 MCTargetOptions MCOptions = mc::getMCTargetOptions(C: LibraryOptions);
460 std::unique_ptr<MCAsmInfo> MAI(
461 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
462 assert(MAI && "Unable to create target asm info!");
463
464 SourceMgr SrcMgr;
465
466 // Tell SrcMgr about this buffer, which is what the parser will pick up.
467 SrcMgr.AddNewSourceBuffer(F: std::move(InputBuffer), IncludeLoc: SMLoc());
468
469 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
470 assert(MCII && "Unable to create instruction info!");
471
472 std::unique_ptr<MCInstrAnalysis> MCIA(
473 TheTarget->createMCInstrAnalysis(Info: MCII.get()));
474
475 // Need to initialize an MCInstPrinter as it is
476 // required for initializing the MCTargetStreamer
477 // which needs to happen within the CRG.parseAnalysisRegions() call below.
478 // Without an MCTargetStreamer, certain assembly directives can trigger a
479 // segfault. (For example, the .cv_fpo_proc directive on x86 will segfault if
480 // we don't initialize the MCTargetStreamer.)
481 unsigned IPtempOutputAsmVariant =
482 OutputAsmVariant == -1 ? 0 : OutputAsmVariant;
483 std::unique_ptr<MCInstPrinter> IPtemp(TheTarget->createMCInstPrinter(
484 T: TheTriple, SyntaxVariant: IPtempOutputAsmVariant, MAI: *MAI, MII: *MCII, MRI: *MRI));
485 if (!IPtemp) {
486 WithColor::error()
487 << "unable to create instruction printer for target triple '"
488 << TheTriple.normalize() << "' with assembly variant "
489 << IPtempOutputAsmVariant << ".\n";
490 return 1;
491 }
492
493 // Parse the input and create CodeRegions that llvm-mca can analyze.
494 MCContext ACtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
495 std::unique_ptr<MCObjectFileInfo> AMOFI(
496 TheTarget->createMCObjectFileInfo(Ctx&: ACtx, /*PIC=*/false));
497 ACtx.setObjectFileInfo(AMOFI.get());
498 mca::AsmAnalysisRegionGenerator CRG(*TheTarget, SrcMgr, ACtx, *MAI, *STI,
499 *MCII);
500 Expected<const mca::AnalysisRegions &> RegionsOrErr =
501 CRG.parseAnalysisRegions(IP: std::move(IPtemp),
502 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
503 if (!RegionsOrErr) {
504 if (auto Err =
505 handleErrors(E: RegionsOrErr.takeError(), Hs: [](const StringError &E) {
506 WithColor::error() << E.getMessage() << '\n';
507 })) {
508 // Default case.
509 WithColor::error() << toString(E: std::move(Err)) << '\n';
510 }
511 return 1;
512 }
513 const mca::AnalysisRegions &Regions = *RegionsOrErr;
514
515 // Early exit if errors were found by the code region parsing logic.
516 if (!Regions.isValid())
517 return 1;
518
519 if (Regions.empty()) {
520 WithColor::error() << "no assembly instructions found.\n";
521 return 1;
522 }
523
524 std::unique_ptr<mca::InstrumentManager> IM;
525 if (!DisableInstrumentManager) {
526 IM = std::unique_ptr<mca::InstrumentManager>(
527 TheTarget->createInstrumentManager(STI: *STI, MCII: *MCII));
528 if (!IM) {
529 // If the target doesn't have its own IM implemented we use base class
530 // with instruments enabled.
531 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII);
532 }
533 } else {
534 // If the -disable-im flag is set then we use the default base class
535 // implementation and disable the instruments.
536 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII,
537 /*EnableInstruments=*/args: false);
538 }
539
540 // Parse the input and create InstrumentRegion that llvm-mca
541 // can use to improve analysis.
542 MCContext ICtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
543 std::unique_ptr<MCObjectFileInfo> IMOFI(
544 TheTarget->createMCObjectFileInfo(Ctx&: ICtx, /*PIC=*/false));
545 ICtx.setObjectFileInfo(IMOFI.get());
546 mca::AsmInstrumentRegionGenerator IRG(*TheTarget, SrcMgr, ICtx, *MAI, *STI,
547 *MCII, *IM);
548 Expected<const mca::InstrumentRegions &> InstrumentRegionsOrErr =
549 IRG.parseInstrumentRegions(IP: std::move(IPtemp),
550 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
551 if (!InstrumentRegionsOrErr) {
552 if (auto Err = handleErrors(E: InstrumentRegionsOrErr.takeError(),
553 Hs: [](const StringError &E) {
554 WithColor::error() << E.getMessage() << '\n';
555 })) {
556 // Default case.
557 WithColor::error() << toString(E: std::move(Err)) << '\n';
558 }
559 return 1;
560 }
561 const mca::InstrumentRegions &InstrumentRegions = *InstrumentRegionsOrErr;
562
563 // Early exit if errors were found by the instrumentation parsing logic.
564 if (!InstrumentRegions.isValid())
565 return 1;
566
567 // Now initialize the output file.
568 auto OF = getOutputStream();
569 if (std::error_code EC = OF.getError()) {
570 WithColor::error() << EC.message() << '\n';
571 return 1;
572 }
573
574 unsigned AssemblerDialect = CRG.getAssemblerDialect();
575 if (OutputAsmVariant >= 0)
576 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
577 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
578 T: TheTriple, SyntaxVariant: AssemblerDialect, MAI: *MAI, MII: *MCII, MRI: *MRI));
579 if (!IP) {
580 WithColor::error()
581 << "unable to create instruction printer for target triple '"
582 << TheTriple.normalize() << "' with assembly variant "
583 << AssemblerDialect << ".\n";
584 return 1;
585 }
586
587 // Set the display preference for hex vs. decimal immediates.
588 IP->setPrintImmHex(PrintImmHex);
589
590 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
591
592 const MCSchedModel &SM = STI->getSchedModel();
593
594 std::unique_ptr<mca::InstrPostProcess> IPP;
595 if (!DisableCustomBehaviour) {
596 // TODO: It may be a good idea to separate CB and IPP so that they can
597 // be used independently of each other. What I mean by this is to add
598 // an extra command-line arg --disable-ipp so that CB and IPP can be
599 // toggled without needing to toggle both of them together.
600 IPP = std::unique_ptr<mca::InstrPostProcess>(
601 TheTarget->createInstrPostProcess(STI: *STI, MCII: *MCII));
602 }
603 if (!IPP) {
604 // If the target doesn't have its own IPP implemented (or the -disable-cb
605 // flag is set) then we use the base class (which does nothing).
606 IPP = std::make_unique<mca::InstrPostProcess>(args&: *STI, args&: *MCII);
607 }
608
609 // Create an instruction builder.
610 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get(), *IM, CallLatency);
611
612 // Create a context to control ownership of the pipeline hardware.
613 mca::Context MCA(*MRI, *STI);
614
615 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
616 RegisterFileSize, LoadQueueSize, StoreQueueSize,
617 AssumeNoAlias, EnableBottleneckAnalysis);
618 PO.ReservationStationScaleFactor =
619 MCSchedModel::getReservationStationScaleFactor(Options: MCOptions);
620
621 // Number each region in the sequence.
622 unsigned RegionIdx = 0;
623
624 std::unique_ptr<MCCodeEmitter> MCE(
625 TheTarget->createMCCodeEmitter(II: *MCII, Ctx&: ACtx));
626 assert(MCE && "Unable to create code emitter!");
627
628 std::unique_ptr<MCAsmBackend> MAB(
629 TheTarget->createMCAsmBackend(STI: *STI, MRI: *MRI, Options: MCOptions));
630 assert(MAB && "Unable to create asm backend!");
631
632 json::Object JSONOutput;
633 int NonEmptyRegions = 0;
634 for (const std::unique_ptr<mca::AnalysisRegion> &Region : Regions) {
635 // Skip empty code regions.
636 if (Region->empty())
637 continue;
638
639 IB.clear();
640
641 // Lower the MCInst sequence into an mca::Instruction sequence.
642 ArrayRef<MCInst> Insts = Region->getInstructions();
643 mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
644
645 IPP->resetState();
646
647 DenseMap<const MCInst *, SmallVector<mca::Instrument *>> InstToInstruments;
648 SmallVector<std::unique_ptr<mca::Instruction>> LoweredSequence;
649 SmallPtrSet<const MCInst *, 16> DroppedInsts;
650 for (const MCInst &MCI : Insts) {
651 SMLoc Loc = MCI.getLoc();
652 const SmallVector<mca::Instrument *> Instruments =
653 InstrumentRegions.getActiveInstruments(Loc);
654
655 Expected<std::unique_ptr<mca::Instruction>> Inst =
656 IB.createInstruction(MCI, IVec: Instruments);
657 if (!Inst) {
658 if (auto NewE = handleErrors(
659 E: Inst.takeError(),
660 Hs: [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
661 std::string InstructionStr;
662 raw_string_ostream SS(InstructionStr);
663 if (shouldSkip(skipType: SkipType::LACK_SCHED))
664 WithColor::warning()
665 << IE.Message
666 << ", skipping with -skip-unsupported-instructions, "
667 "note accuracy will be impacted:\n";
668 else
669 WithColor::error()
670 << IE.Message
671 << ", use -skip-unsupported-instructions=lack-sched to "
672 "ignore these on the input.\n";
673 IP->printInst(MI: &IE.Inst, Address: 0, Annot: "", STI: *STI, OS&: SS);
674 WithColor::note()
675 << "instruction: " << InstructionStr << '\n';
676 })) {
677 // Default case.
678 WithColor::error() << toString(E: std::move(NewE));
679 }
680 if (shouldSkip(skipType: SkipType::LACK_SCHED)) {
681 DroppedInsts.insert(Ptr: &MCI);
682 continue;
683 }
684 return 1;
685 }
686
687 IPP->postProcessInstruction(Inst&: *Inst.get(), MCI);
688 InstToInstruments.insert(KV: {&MCI, Instruments});
689 LoweredSequence.emplace_back(Args: std::move(Inst.get()));
690 }
691
692 Insts = Region->dropInstructions(Insts: DroppedInsts);
693
694 // Skip empty regions.
695 if (Insts.empty())
696 continue;
697 NonEmptyRegions++;
698
699 mca::CircularSourceMgr S(LoweredSequence,
700 shouldPrintInstructionTables() ? 1 : Iterations);
701
702 if (shouldPrintInstructionTables()) {
703 // Create a pipeline, stages, and a printer.
704 auto P = std::make_unique<mca::Pipeline>();
705 P->appendStage(S: std::make_unique<mca::EntryStage>(args&: S));
706 P->appendStage(S: std::make_unique<mca::InstructionTables>(args: SM));
707
708 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
709 if (PrintJson) {
710 Printer.addView(
711 V: std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts));
712 }
713
714 // Create the views for this pipeline, execute, and emit a report.
715 if (PrintInstructionInfoView) {
716 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
717 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
718 args&: ShowBarriers,
719 args: shouldPrintInstructionTables(ITType: InstructionTablesType::FULL), args&: *IM,
720 args&: InstToInstruments));
721 }
722
723 if (PrintResourcePressureView)
724 Printer.addView(
725 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
726
727 if (!runPipeline(P&: *P))
728 return 1;
729
730 if (PrintJson) {
731 Printer.printReport(JO&: JSONOutput);
732 } else {
733 Printer.printReport(OS&: TOF->os());
734 }
735
736 ++RegionIdx;
737 continue;
738 }
739
740 // Create the CustomBehaviour object for enforcing Target Specific
741 // behaviours and dependencies that aren't expressed well enough
742 // in the tablegen. CB cannot depend on the list of MCInst or
743 // the source code (but it can depend on the list of
744 // mca::Instruction or any objects that can be reconstructed
745 // from the target information).
746 std::unique_ptr<mca::CustomBehaviour> CB;
747 if (!DisableCustomBehaviour)
748 CB = std::unique_ptr<mca::CustomBehaviour>(
749 TheTarget->createCustomBehaviour(STI: *STI, SrcMgr: S, MCII: *MCII));
750 if (!CB)
751 // If the target doesn't have its own CB implemented (or the -disable-cb
752 // flag is set) then we use the base class (which does nothing).
753 CB = std::make_unique<mca::CustomBehaviour>(args&: *STI, args&: S, args&: *MCII);
754
755 // Create a basic pipeline simulating an out-of-order backend.
756 auto P = MCA.createDefaultPipeline(Opts: PO, SrcMgr&: S, CB&: *CB);
757
758 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
759
760 // Targets can define their own custom Views that exist within their
761 // /lib/Target/ directory so that the View can utilize their CustomBehaviour
762 // or other backend symbols / functionality that are not already exposed
763 // through one of the MC-layer classes. These Views will be initialized
764 // using the CustomBehaviour::getViews() variants.
765 // If a target makes a custom View that does not depend on their target
766 // CB or their backend, they should put the View within
767 // /tools/llvm-mca/Views/ instead.
768 if (!DisableCustomBehaviour) {
769 std::vector<std::unique_ptr<mca::View>> CBViews =
770 CB->getStartViews(IP&: *IP, Insts);
771 for (auto &CBView : CBViews)
772 Printer.addView(V: std::move(CBView));
773 }
774
775 // When we output JSON, we add a view that contains the instructions
776 // and CPU resource information.
777 if (PrintJson) {
778 auto IV = std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts);
779 Printer.addView(V: std::move(IV));
780 }
781
782 if (PrintSummaryView)
783 Printer.addView(
784 V: std::make_unique<mca::SummaryView>(args: SM, args&: Insts, args&: DispatchWidth));
785
786 if (EnableBottleneckAnalysis) {
787 if (!IsOutOfOrder) {
788 WithColor::warning()
789 << "bottleneck analysis is not supported for in-order CPU '" << MCPU
790 << "'.\n";
791 }
792 Printer.addView(V: std::make_unique<mca::BottleneckAnalysis>(
793 args&: *STI, args&: *IP, args&: Insts, args: S.getNumIterations()));
794 }
795
796 if (PrintInstructionInfoView)
797 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
798 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
799 args&: ShowBarriers, /*ShouldPrintFullInfo=*/args: false, args&: *IM, args&: InstToInstruments));
800
801 // Fetch custom Views that are to be placed after the InstructionInfoView.
802 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
803 // for more info.
804 if (!DisableCustomBehaviour) {
805 std::vector<std::unique_ptr<mca::View>> CBViews =
806 CB->getPostInstrInfoViews(IP&: *IP, Insts);
807 for (auto &CBView : CBViews)
808 Printer.addView(V: std::move(CBView));
809 }
810
811 if (PrintDispatchStats)
812 Printer.addView(V: std::make_unique<mca::DispatchStatistics>());
813
814 if (PrintSchedulerStats)
815 Printer.addView(V: std::make_unique<mca::SchedulerStatistics>(
816 args&: *STI, args&: PO.ReservationStationScaleFactor));
817
818 if (PrintRetireStats)
819 Printer.addView(V: std::make_unique<mca::RetireControlUnitStatistics>(args: SM));
820
821 if (PrintRegisterFileStats)
822 Printer.addView(V: std::make_unique<mca::RegisterFileStatistics>(args&: *STI));
823
824 if (PrintResourcePressureView)
825 Printer.addView(
826 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
827
828 if (PrintTimelineView) {
829 unsigned TimelineIterations =
830 TimelineMaxIterations ? TimelineMaxIterations : 10;
831 Printer.addView(V: std::make_unique<mca::TimelineView>(
832 args&: *STI, args&: *IP, args&: Insts, args: std::min(a: TimelineIterations, b: S.getNumIterations()),
833 args&: TimelineMaxCycles, args&: PO.ReservationStationScaleFactor));
834 }
835
836 // Fetch custom Views that are to be placed after all other Views.
837 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
838 // for more info.
839 if (!DisableCustomBehaviour) {
840 std::vector<std::unique_ptr<mca::View>> CBViews =
841 CB->getEndViews(IP&: *IP, Insts);
842 for (auto &CBView : CBViews)
843 Printer.addView(V: std::move(CBView));
844 }
845
846 if (!runPipeline(P&: *P))
847 return 1;
848
849 if (PrintJson) {
850 Printer.printReport(JO&: JSONOutput);
851 } else {
852 Printer.printReport(OS&: TOF->os());
853 }
854
855 ++RegionIdx;
856 }
857
858 if (NonEmptyRegions == 0) {
859 WithColor::error() << "no assembly instructions found.\n";
860 return 1;
861 }
862
863 if (PrintJson)
864 TOF->os() << formatv(Fmt: "{0:2}", Vals: json::Value(std::move(JSONOutput))) << "\n";
865
866 TOF->keep();
867 return 0;
868}
869