llvm-mca.cpp 25 KB

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