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/MCSchedule.h"
42#include "llvm/MC/MCSubtargetInfo.h"
43#include "llvm/MC/MCTargetOptionsCommandFlags.h"
44#include "llvm/MC/TargetRegistry.h"
45#include "llvm/MCA/CodeEmitter.h"
46#include "llvm/MCA/Context.h"
47#include "llvm/MCA/CustomBehaviour.h"
48#include "llvm/MCA/InstrBuilder.h"
49#include "llvm/MCA/Pipeline.h"
50#include "llvm/MCA/Stages/EntryStage.h"
51#include "llvm/MCA/Stages/InstructionTables.h"
52#include "llvm/MCA/Support.h"
53#include "llvm/Support/CommandLine.h"
54#include "llvm/Support/ErrorHandling.h"
55#include "llvm/Support/ErrorOr.h"
56#include "llvm/Support/FileSystem.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#include "llvm/TargetParser/Host.h"
64
65using namespace llvm;
66
67static mc::RegisterMCTargetOptionsFlags MOF;
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: "native"));
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, &MCScheduleOptions});
379
380 // Parse flags and initialize target options.
381 cl::ParseCommandLineOptions(argc, argv,
382 Overview: "llvm machine code performance analyzer.\n");
383
384 Triple TheTriple(TripleNameOpt.empty()
385 ? Triple::normalize(Str: sys::getDefaultTargetTriple())
386 : TripleNameOpt);
387
388 // Get the target from the triple. If a triple is not specified, then select
389 // the default triple for the host. If the triple doesn't correspond to any
390 // registered target, then exit with an error message.
391 const char *ProgName = argv[0];
392 const Target *TheTarget = getTarget(TheTriple, ProgName);
393 if (!TheTarget)
394 return 1;
395
396 const bool WantsCPUHelp = MCPU == "help";
397
398 std::unique_ptr<MemoryBuffer> InputBuffer;
399 if (!WantsCPUHelp) {
400 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferOrErr =
401 MemoryBuffer::getFileOrSTDIN(Filename: InputFilename);
402 if (!BufferOrErr) {
403 std::error_code EC = BufferOrErr.getError();
404 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
405 return 1;
406 }
407 InputBuffer = std::move(*BufferOrErr);
408 }
409
410 if (MCPU == "native")
411 MCPU = std::string(llvm::sys::getHostCPUName());
412
413 // Package up features to be passed to target/subtarget
414 std::string FeaturesStr;
415 if (MATTRS.size()) {
416 SubtargetFeatures Features;
417 for (std::string &MAttr : MATTRS)
418 Features.AddFeature(String: MAttr);
419 FeaturesStr = Features.getString();
420 }
421
422 std::unique_ptr<MCSubtargetInfo> STI(
423 TheTarget->createMCSubtargetInfo(TheTriple, CPU: MCPU, Features: FeaturesStr));
424 if (!STI) {
425 WithColor::error() << "unable to create subtarget info\n";
426 return 1;
427 }
428
429 if (TheTriple.isAArch64() && STI->checkFeatures(FS: "+mca-streaming-sched"))
430 WithColor::warning()
431 << "AArch64 streaming SVE scheduling is enabled via "
432 "'-mattr=+mca-streaming-sched'; llvm-mca results are approximate.\n";
433
434 if (WantsCPUHelp)
435 return 0;
436
437 if (!STI->isCPUStringValid(CPU: MCPU))
438 return 1;
439
440 if (!STI->getSchedModel().hasInstrSchedModel()) {
441 WithColor::error()
442 << "unable to find instruction-level scheduling information for"
443 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
444 << "'.\n";
445
446 if (STI->getSchedModel().InstrItineraries)
447 WithColor::note()
448 << "cpu '" << MCPU << "' provides itineraries. However, "
449 << "instruction itineraries are currently unsupported.\n";
450 return 1;
451 }
452
453 // Apply overrides to llvm-mca specific options.
454 bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();
455 processViewOptions(IsOutOfOrder);
456
457 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT: TheTriple));
458 assert(MRI && "Unable to create target register info!");
459
460 MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();
461 std::unique_ptr<MCAsmInfo> MAI(
462 TheTarget->createMCAsmInfo(MRI: *MRI, TheTriple, Options: MCOptions));
463 assert(MAI && "Unable to create target asm info!");
464
465 SourceMgr SrcMgr;
466
467 // Tell SrcMgr about this buffer, which is what the parser will pick up.
468 SrcMgr.AddNewSourceBuffer(F: std::move(InputBuffer), IncludeLoc: SMLoc());
469
470 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
471 assert(MCII && "Unable to create instruction info!");
472
473 std::unique_ptr<MCInstrAnalysis> MCIA(
474 TheTarget->createMCInstrAnalysis(Info: MCII.get()));
475
476 // Need to initialize an MCInstPrinter as it is
477 // required for initializing the MCTargetStreamer
478 // which needs to happen within the CRG.parseAnalysisRegions() call below.
479 // Without an MCTargetStreamer, certain assembly directives can trigger a
480 // segfault. (For example, the .cv_fpo_proc directive on x86 will segfault if
481 // we don't initialize the MCTargetStreamer.)
482 unsigned IPtempOutputAsmVariant =
483 OutputAsmVariant == -1 ? 0 : OutputAsmVariant;
484 std::unique_ptr<MCInstPrinter> IPtemp(TheTarget->createMCInstPrinter(
485 T: TheTriple, SyntaxVariant: IPtempOutputAsmVariant, MAI: *MAI, MII: *MCII, MRI: *MRI));
486 if (!IPtemp) {
487 WithColor::error()
488 << "unable to create instruction printer for target triple '"
489 << TheTriple.normalize() << "' with assembly variant "
490 << IPtempOutputAsmVariant << ".\n";
491 return 1;
492 }
493
494 // Parse the input and create CodeRegions that llvm-mca can analyze.
495 MCContext ACtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
496 std::unique_ptr<MCObjectFileInfo> AMOFI(
497 TheTarget->createMCObjectFileInfo(Ctx&: ACtx, /*PIC=*/false));
498 ACtx.setObjectFileInfo(AMOFI.get());
499 mca::AsmAnalysisRegionGenerator CRG(*TheTarget, SrcMgr, ACtx, *MAI, *STI,
500 *MCII);
501 Expected<const mca::AnalysisRegions &> RegionsOrErr =
502 CRG.parseAnalysisRegions(IP: std::move(IPtemp),
503 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
504 if (!RegionsOrErr) {
505 if (auto Err =
506 handleErrors(E: RegionsOrErr.takeError(), Hs: [](const StringError &E) {
507 WithColor::error() << E.getMessage() << '\n';
508 })) {
509 // Default case.
510 WithColor::error() << toString(E: std::move(Err)) << '\n';
511 }
512 return 1;
513 }
514 const mca::AnalysisRegions &Regions = *RegionsOrErr;
515
516 // Early exit if errors were found by the code region parsing logic.
517 if (!Regions.isValid())
518 return 1;
519
520 if (Regions.empty()) {
521 WithColor::error() << "no assembly instructions found.\n";
522 return 1;
523 }
524
525 std::unique_ptr<mca::InstrumentManager> IM;
526 if (!DisableInstrumentManager) {
527 IM = std::unique_ptr<mca::InstrumentManager>(
528 TheTarget->createInstrumentManager(STI: *STI, MCII: *MCII));
529 if (!IM) {
530 // If the target doesn't have its own IM implemented we use base class
531 // with instruments enabled.
532 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII);
533 }
534 } else {
535 // If the -disable-im flag is set then we use the default base class
536 // implementation and disable the instruments.
537 IM = std::make_unique<mca::InstrumentManager>(args&: *STI, args&: *MCII,
538 /*EnableInstruments=*/args: false);
539 }
540
541 // Parse the input and create InstrumentRegion that llvm-mca
542 // can use to improve analysis.
543 MCContext ICtx(TheTriple, *MAI, *MRI, *STI, &SrcMgr);
544 std::unique_ptr<MCObjectFileInfo> IMOFI(
545 TheTarget->createMCObjectFileInfo(Ctx&: ICtx, /*PIC=*/false));
546 ICtx.setObjectFileInfo(IMOFI.get());
547 mca::AsmInstrumentRegionGenerator IRG(*TheTarget, SrcMgr, ICtx, *MAI, *STI,
548 *MCII, *IM);
549 Expected<const mca::InstrumentRegions &> InstrumentRegionsOrErr =
550 IRG.parseInstrumentRegions(IP: std::move(IPtemp),
551 SkipFailures: shouldSkip(skipType: SkipType::PARSE_FAILURE));
552 if (!InstrumentRegionsOrErr) {
553 if (auto Err = handleErrors(E: InstrumentRegionsOrErr.takeError(),
554 Hs: [](const StringError &E) {
555 WithColor::error() << E.getMessage() << '\n';
556 })) {
557 // Default case.
558 WithColor::error() << toString(E: std::move(Err)) << '\n';
559 }
560 return 1;
561 }
562 const mca::InstrumentRegions &InstrumentRegions = *InstrumentRegionsOrErr;
563
564 // Early exit if errors were found by the instrumentation parsing logic.
565 if (!InstrumentRegions.isValid())
566 return 1;
567
568 // Now initialize the output file.
569 auto OF = getOutputStream();
570 if (std::error_code EC = OF.getError()) {
571 WithColor::error() << EC.message() << '\n';
572 return 1;
573 }
574
575 unsigned AssemblerDialect = CRG.getAssemblerDialect();
576 if (OutputAsmVariant >= 0)
577 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
578 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
579 T: TheTriple, SyntaxVariant: AssemblerDialect, MAI: *MAI, MII: *MCII, MRI: *MRI));
580 if (!IP) {
581 WithColor::error()
582 << "unable to create instruction printer for target triple '"
583 << TheTriple.normalize() << "' with assembly variant "
584 << AssemblerDialect << ".\n";
585 return 1;
586 }
587
588 // Set the display preference for hex vs. decimal immediates.
589 IP->setPrintImmHex(PrintImmHex);
590
591 std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);
592
593 const MCSchedModel &SM = STI->getSchedModel();
594
595 std::unique_ptr<mca::InstrPostProcess> IPP;
596 if (!DisableCustomBehaviour) {
597 // TODO: It may be a good idea to separate CB and IPP so that they can
598 // be used independently of each other. What I mean by this is to add
599 // an extra command-line arg --disable-ipp so that CB and IPP can be
600 // toggled without needing to toggle both of them together.
601 IPP = std::unique_ptr<mca::InstrPostProcess>(
602 TheTarget->createInstrPostProcess(STI: *STI, MCII: *MCII));
603 }
604 if (!IPP) {
605 // If the target doesn't have its own IPP implemented (or the -disable-cb
606 // flag is set) then we use the base class (which does nothing).
607 IPP = std::make_unique<mca::InstrPostProcess>(args&: *STI, args&: *MCII);
608 }
609
610 // Create an instruction builder.
611 mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get(), *IM, CallLatency);
612
613 // Create a context to control ownership of the pipeline hardware.
614 mca::Context MCA(*MRI, *STI);
615
616 mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,
617 RegisterFileSize, LoadQueueSize, StoreQueueSize,
618 AssumeNoAlias, EnableBottleneckAnalysis);
619
620 // Number each region in the sequence.
621 unsigned RegionIdx = 0;
622
623 std::unique_ptr<MCCodeEmitter> MCE(
624 TheTarget->createMCCodeEmitter(II: *MCII, Ctx&: ACtx));
625 assert(MCE && "Unable to create code emitter!");
626
627 std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(
628 STI: *STI, MRI: *MRI, Options: mc::InitMCTargetOptionsFromFlags()));
629 assert(MAB && "Unable to create asm backend!");
630
631 json::Object JSONOutput;
632 int NonEmptyRegions = 0;
633 for (const std::unique_ptr<mca::AnalysisRegion> &Region : Regions) {
634 // Skip empty code regions.
635 if (Region->empty())
636 continue;
637
638 IB.clear();
639
640 // Lower the MCInst sequence into an mca::Instruction sequence.
641 ArrayRef<MCInst> Insts = Region->getInstructions();
642 mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);
643
644 IPP->resetState();
645
646 DenseMap<const MCInst *, SmallVector<mca::Instrument *>> InstToInstruments;
647 SmallVector<std::unique_ptr<mca::Instruction>> LoweredSequence;
648 SmallPtrSet<const MCInst *, 16> DroppedInsts;
649 for (const MCInst &MCI : Insts) {
650 SMLoc Loc = MCI.getLoc();
651 const SmallVector<mca::Instrument *> Instruments =
652 InstrumentRegions.getActiveInstruments(Loc);
653
654 Expected<std::unique_ptr<mca::Instruction>> Inst =
655 IB.createInstruction(MCI, IVec: Instruments);
656 if (!Inst) {
657 if (auto NewE = handleErrors(
658 E: Inst.takeError(),
659 Hs: [&IP, &STI](const mca::InstructionError<MCInst> &IE) {
660 std::string InstructionStr;
661 raw_string_ostream SS(InstructionStr);
662 if (shouldSkip(skipType: SkipType::LACK_SCHED))
663 WithColor::warning()
664 << IE.Message
665 << ", skipping with -skip-unsupported-instructions, "
666 "note accuracy will be impacted:\n";
667 else
668 WithColor::error()
669 << IE.Message
670 << ", use -skip-unsupported-instructions=lack-sched to "
671 "ignore these on the input.\n";
672 IP->printInst(MI: &IE.Inst, Address: 0, Annot: "", STI: *STI, OS&: SS);
673 WithColor::note()
674 << "instruction: " << InstructionStr << '\n';
675 })) {
676 // Default case.
677 WithColor::error() << toString(E: std::move(NewE));
678 }
679 if (shouldSkip(skipType: SkipType::LACK_SCHED)) {
680 DroppedInsts.insert(Ptr: &MCI);
681 continue;
682 }
683 return 1;
684 }
685
686 IPP->postProcessInstruction(Inst&: *Inst.get(), MCI);
687 InstToInstruments.insert(KV: {&MCI, Instruments});
688 LoweredSequence.emplace_back(Args: std::move(Inst.get()));
689 }
690
691 Insts = Region->dropInstructions(Insts: DroppedInsts);
692
693 // Skip empty regions.
694 if (Insts.empty())
695 continue;
696 NonEmptyRegions++;
697
698 mca::CircularSourceMgr S(LoweredSequence,
699 shouldPrintInstructionTables() ? 1 : Iterations);
700
701 if (shouldPrintInstructionTables()) {
702 // Create a pipeline, stages, and a printer.
703 auto P = std::make_unique<mca::Pipeline>();
704 P->appendStage(S: std::make_unique<mca::EntryStage>(args&: S));
705 P->appendStage(S: std::make_unique<mca::InstructionTables>(args: SM));
706
707 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
708 if (PrintJson) {
709 Printer.addView(
710 V: std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts));
711 }
712
713 // Create the views for this pipeline, execute, and emit a report.
714 if (PrintInstructionInfoView) {
715 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
716 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
717 args&: ShowBarriers,
718 args: shouldPrintInstructionTables(ITType: InstructionTablesType::FULL), args&: *IM,
719 args&: InstToInstruments));
720 }
721
722 if (PrintResourcePressureView)
723 Printer.addView(
724 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
725
726 if (!runPipeline(P&: *P))
727 return 1;
728
729 if (PrintJson) {
730 Printer.printReport(JO&: JSONOutput);
731 } else {
732 Printer.printReport(OS&: TOF->os());
733 }
734
735 ++RegionIdx;
736 continue;
737 }
738
739 // Create the CustomBehaviour object for enforcing Target Specific
740 // behaviours and dependencies that aren't expressed well enough
741 // in the tablegen. CB cannot depend on the list of MCInst or
742 // the source code (but it can depend on the list of
743 // mca::Instruction or any objects that can be reconstructed
744 // from the target information).
745 std::unique_ptr<mca::CustomBehaviour> CB;
746 if (!DisableCustomBehaviour)
747 CB = std::unique_ptr<mca::CustomBehaviour>(
748 TheTarget->createCustomBehaviour(STI: *STI, SrcMgr: S, MCII: *MCII));
749 if (!CB)
750 // If the target doesn't have its own CB implemented (or the -disable-cb
751 // flag is set) then we use the base class (which does nothing).
752 CB = std::make_unique<mca::CustomBehaviour>(args&: *STI, args&: S, args&: *MCII);
753
754 // Create a basic pipeline simulating an out-of-order backend.
755 auto P = MCA.createDefaultPipeline(Opts: PO, SrcMgr&: S, CB&: *CB);
756
757 mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);
758
759 // Targets can define their own custom Views that exist within their
760 // /lib/Target/ directory so that the View can utilize their CustomBehaviour
761 // or other backend symbols / functionality that are not already exposed
762 // through one of the MC-layer classes. These Views will be initialized
763 // using the CustomBehaviour::getViews() variants.
764 // If a target makes a custom View that does not depend on their target
765 // CB or their backend, they should put the View within
766 // /tools/llvm-mca/Views/ instead.
767 if (!DisableCustomBehaviour) {
768 std::vector<std::unique_ptr<mca::View>> CBViews =
769 CB->getStartViews(IP&: *IP, Insts);
770 for (auto &CBView : CBViews)
771 Printer.addView(V: std::move(CBView));
772 }
773
774 // When we output JSON, we add a view that contains the instructions
775 // and CPU resource information.
776 if (PrintJson) {
777 auto IV = std::make_unique<mca::InstructionView>(args&: *STI, args&: *IP, args&: Insts);
778 Printer.addView(V: std::move(IV));
779 }
780
781 if (PrintSummaryView)
782 Printer.addView(
783 V: std::make_unique<mca::SummaryView>(args: SM, args&: Insts, args&: DispatchWidth));
784
785 if (EnableBottleneckAnalysis) {
786 if (!IsOutOfOrder) {
787 WithColor::warning()
788 << "bottleneck analysis is not supported for in-order CPU '" << MCPU
789 << "'.\n";
790 }
791 Printer.addView(V: std::make_unique<mca::BottleneckAnalysis>(
792 args&: *STI, args&: *IP, args&: Insts, args: S.getNumIterations()));
793 }
794
795 if (PrintInstructionInfoView)
796 Printer.addView(V: std::make_unique<mca::InstructionInfoView>(
797 args&: *STI, args&: *MCII, args&: CE, args&: ShowEncoding, args&: Insts, args&: *IP, args&: LoweredSequence,
798 args&: ShowBarriers, /*ShouldPrintFullInfo=*/args: false, args&: *IM, args&: InstToInstruments));
799
800 // Fetch custom Views that are to be placed after the InstructionInfoView.
801 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
802 // for more info.
803 if (!DisableCustomBehaviour) {
804 std::vector<std::unique_ptr<mca::View>> CBViews =
805 CB->getPostInstrInfoViews(IP&: *IP, Insts);
806 for (auto &CBView : CBViews)
807 Printer.addView(V: std::move(CBView));
808 }
809
810 if (PrintDispatchStats)
811 Printer.addView(V: std::make_unique<mca::DispatchStatistics>());
812
813 if (PrintSchedulerStats)
814 Printer.addView(V: std::make_unique<mca::SchedulerStatistics>(args&: *STI));
815
816 if (PrintRetireStats)
817 Printer.addView(V: std::make_unique<mca::RetireControlUnitStatistics>(args: SM));
818
819 if (PrintRegisterFileStats)
820 Printer.addView(V: std::make_unique<mca::RegisterFileStatistics>(args&: *STI));
821
822 if (PrintResourcePressureView)
823 Printer.addView(
824 V: std::make_unique<mca::ResourcePressureView>(args&: *STI, args&: *IP, args&: Insts));
825
826 if (PrintTimelineView) {
827 unsigned TimelineIterations =
828 TimelineMaxIterations ? TimelineMaxIterations : 10;
829 Printer.addView(V: std::make_unique<mca::TimelineView>(
830 args&: *STI, args&: *IP, args&: Insts, args: std::min(a: TimelineIterations, b: S.getNumIterations()),
831 args&: TimelineMaxCycles));
832 }
833
834 // Fetch custom Views that are to be placed after all other Views.
835 // Refer to the comment paired with the CB->getStartViews(*IP, Insts); line
836 // for more info.
837 if (!DisableCustomBehaviour) {
838 std::vector<std::unique_ptr<mca::View>> CBViews =
839 CB->getEndViews(IP&: *IP, Insts);
840 for (auto &CBView : CBViews)
841 Printer.addView(V: std::move(CBView));
842 }
843
844 if (!runPipeline(P&: *P))
845 return 1;
846
847 if (PrintJson) {
848 Printer.printReport(JO&: JSONOutput);
849 } else {
850 Printer.printReport(OS&: TOF->os());
851 }
852
853 ++RegionIdx;
854 }
855
856 if (NonEmptyRegions == 0) {
857 WithColor::error() << "no assembly instructions found.\n";
858 return 1;
859 }
860
861 if (PrintJson)
862 TOF->os() << formatv(Fmt: "{0:2}", Vals: json::Value(std::move(JSONOutput))) << "\n";
863
864 TOF->keep();
865 return 0;
866}
867