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