Path: blob/main/contrib/llvm-project/llvm/tools/llvm-mca/llvm-mca.cpp
35258 views
//===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//7//8// This utility is a simple driver that allows static performance analysis on9// machine code similarly to how IACA (Intel Architecture Code Analyzer) works.10//11// llvm-mca [options] <file-name>12// -march <type>13// -mcpu <cpu>14// -o <file>15//16// The target defaults to the host target.17// The cpu defaults to the 'native' host cpu.18// The output defaults to standard output.19//20//===----------------------------------------------------------------------===//2122#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/InitLLVM.h"56#include "llvm/Support/MemoryBuffer.h"57#include "llvm/Support/SourceMgr.h"58#include "llvm/Support/TargetSelect.h"59#include "llvm/Support/ToolOutputFile.h"60#include "llvm/Support/WithColor.h"61#include "llvm/TargetParser/Host.h"6263using namespace llvm;6465static mc::RegisterMCTargetOptionsFlags MOF;6667static cl::OptionCategory ToolOptions("Tool Options");68static cl::OptionCategory ViewOptions("View Options");6970static cl::opt<std::string> InputFilename(cl::Positional,71cl::desc("<input file>"),72cl::cat(ToolOptions), cl::init("-"));7374static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),75cl::init("-"), cl::cat(ToolOptions),76cl::value_desc("filename"));7778static cl::opt<std::string>79ArchName("march",80cl::desc("Target architecture. "81"See -version for available targets"),82cl::cat(ToolOptions));8384static cl::opt<std::string>85TripleName("mtriple",86cl::desc("Target triple. See -version for available targets"),87cl::cat(ToolOptions));8889static cl::opt<std::string>90MCPU("mcpu",91cl::desc("Target a specific cpu type (-mcpu=help for details)"),92cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));9394static cl::list<std::string>95MATTRS("mattr", cl::CommaSeparated,96cl::desc("Target specific attributes (-mattr=help for details)"),97cl::value_desc("a1,+a2,-a3,..."), cl::cat(ToolOptions));9899static cl::opt<bool> PrintJson("json",100cl::desc("Print the output in json format"),101cl::cat(ToolOptions), cl::init(false));102103static cl::opt<int>104OutputAsmVariant("output-asm-variant",105cl::desc("Syntax variant to use for output printing"),106cl::cat(ToolOptions), cl::init(-1));107108static cl::opt<bool>109PrintImmHex("print-imm-hex", cl::cat(ToolOptions), cl::init(false),110cl::desc("Prefer hex format when printing immediate values"));111112static cl::opt<unsigned> Iterations("iterations",113cl::desc("Number of iterations to run"),114cl::cat(ToolOptions), cl::init(0));115116static cl::opt<unsigned>117DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),118cl::cat(ToolOptions), cl::init(0));119120static cl::opt<unsigned>121RegisterFileSize("register-file-size",122cl::desc("Maximum number of physical registers which can "123"be used for register mappings"),124cl::cat(ToolOptions), cl::init(0));125126static cl::opt<unsigned>127MicroOpQueue("micro-op-queue-size", cl::Hidden,128cl::desc("Number of entries in the micro-op queue"),129cl::cat(ToolOptions), cl::init(0));130131static cl::opt<unsigned>132DecoderThroughput("decoder-throughput", cl::Hidden,133cl::desc("Maximum throughput from the decoders "134"(instructions per cycle)"),135cl::cat(ToolOptions), cl::init(0));136137static cl::opt<unsigned>138CallLatency("call-latency", cl::Hidden,139cl::desc("Number of cycles to assume for a call instruction"),140cl::cat(ToolOptions), cl::init(100U));141142enum class SkipType { NONE, LACK_SCHED, PARSE_FAILURE, ANY_FAILURE };143144static cl::opt<enum SkipType> SkipUnsupportedInstructions(145"skip-unsupported-instructions",146cl::desc("Force analysis to continue in the presence of unsupported "147"instructions"),148cl::values(149clEnumValN(SkipType::NONE, "none",150"Exit with an error when an instruction is unsupported for "151"any reason (default)"),152clEnumValN(153SkipType::LACK_SCHED, "lack-sched",154"Skip instructions on input which lack scheduling information"),155clEnumValN(156SkipType::PARSE_FAILURE, "parse-failure",157"Skip lines on the input which fail to parse for any reason"),158clEnumValN(SkipType::ANY_FAILURE, "any",159"Skip instructions or lines on input which are unsupported "160"for any reason")),161cl::init(SkipType::NONE), cl::cat(ViewOptions));162163bool shouldSkip(enum SkipType skipType) {164if (SkipUnsupportedInstructions == SkipType::NONE)165return false;166if (SkipUnsupportedInstructions == SkipType::ANY_FAILURE)167return true;168return skipType == SkipUnsupportedInstructions;169}170171static cl::opt<bool>172PrintRegisterFileStats("register-file-stats",173cl::desc("Print register file statistics"),174cl::cat(ViewOptions), cl::init(false));175176static cl::opt<bool> PrintDispatchStats("dispatch-stats",177cl::desc("Print dispatch statistics"),178cl::cat(ViewOptions), cl::init(false));179180static cl::opt<bool>181PrintSummaryView("summary-view", cl::Hidden,182cl::desc("Print summary view (enabled by default)"),183cl::cat(ViewOptions), cl::init(true));184185static cl::opt<bool> PrintSchedulerStats("scheduler-stats",186cl::desc("Print scheduler statistics"),187cl::cat(ViewOptions), cl::init(false));188189static cl::opt<bool>190PrintRetireStats("retire-stats",191cl::desc("Print retire control unit statistics"),192cl::cat(ViewOptions), cl::init(false));193194static cl::opt<bool> PrintResourcePressureView(195"resource-pressure",196cl::desc("Print the resource pressure view (enabled by default)"),197cl::cat(ViewOptions), cl::init(true));198199static cl::opt<bool> PrintTimelineView("timeline",200cl::desc("Print the timeline view"),201cl::cat(ViewOptions), cl::init(false));202203static cl::opt<unsigned> TimelineMaxIterations(204"timeline-max-iterations",205cl::desc("Maximum number of iterations to print in timeline view"),206cl::cat(ViewOptions), cl::init(0));207208static cl::opt<unsigned>209TimelineMaxCycles("timeline-max-cycles",210cl::desc("Maximum number of cycles in the timeline view, "211"or 0 for unlimited. Defaults to 80 cycles"),212cl::cat(ViewOptions), cl::init(80));213214static cl::opt<bool>215AssumeNoAlias("noalias",216cl::desc("If set, assume that loads and stores do not alias"),217cl::cat(ToolOptions), cl::init(true));218219static cl::opt<unsigned> LoadQueueSize("lqueue",220cl::desc("Size of the load queue"),221cl::cat(ToolOptions), cl::init(0));222223static cl::opt<unsigned> StoreQueueSize("squeue",224cl::desc("Size of the store queue"),225cl::cat(ToolOptions), cl::init(0));226227static cl::opt<bool>228PrintInstructionTables("instruction-tables",229cl::desc("Print instruction tables"),230cl::cat(ToolOptions), cl::init(false));231232static cl::opt<bool> PrintInstructionInfoView(233"instruction-info",234cl::desc("Print the instruction info view (enabled by default)"),235cl::cat(ViewOptions), cl::init(true));236237static cl::opt<bool> EnableAllStats("all-stats",238cl::desc("Print all hardware statistics"),239cl::cat(ViewOptions), cl::init(false));240241static cl::opt<bool>242EnableAllViews("all-views",243cl::desc("Print all views including hardware statistics"),244cl::cat(ViewOptions), cl::init(false));245246static cl::opt<bool> EnableBottleneckAnalysis(247"bottleneck-analysis",248cl::desc("Enable bottleneck analysis (disabled by default)"),249cl::cat(ViewOptions), cl::init(false));250251static cl::opt<bool> ShowEncoding(252"show-encoding",253cl::desc("Print encoding information in the instruction info view"),254cl::cat(ViewOptions), cl::init(false));255256static cl::opt<bool> ShowBarriers(257"show-barriers",258cl::desc("Print memory barrier information in the instruction info view"),259cl::cat(ViewOptions), cl::init(false));260261static cl::opt<bool> DisableCustomBehaviour(262"disable-cb",263cl::desc(264"Disable custom behaviour (use the default class which does nothing)."),265cl::cat(ViewOptions), cl::init(false));266267static cl::opt<bool> DisableInstrumentManager(268"disable-im",269cl::desc("Disable instrumentation manager (use the default class which "270"ignores instruments.)."),271cl::cat(ViewOptions), cl::init(false));272273namespace {274275const Target *getTarget(const char *ProgName) {276if (TripleName.empty())277TripleName = Triple::normalize(sys::getDefaultTargetTriple());278Triple TheTriple(TripleName);279280// Get the target specific parser.281std::string Error;282const Target *TheTarget =283TargetRegistry::lookupTarget(ArchName, TheTriple, Error);284if (!TheTarget) {285errs() << ProgName << ": " << Error;286return nullptr;287}288289// Update TripleName with the updated triple from the target lookup.290TripleName = TheTriple.str();291292// Return the found target.293return TheTarget;294}295296ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {297if (OutputFilename == "")298OutputFilename = "-";299std::error_code EC;300auto Out = std::make_unique<ToolOutputFile>(OutputFilename, EC,301sys::fs::OF_TextWithCRLF);302if (!EC)303return std::move(Out);304return EC;305}306} // end of anonymous namespace307308static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {309if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())310O = Default.getValue();311}312313static void processViewOptions(bool IsOutOfOrder) {314if (!EnableAllViews.getNumOccurrences() &&315!EnableAllStats.getNumOccurrences())316return;317318if (EnableAllViews.getNumOccurrences()) {319processOptionImpl(PrintSummaryView, EnableAllViews);320if (IsOutOfOrder)321processOptionImpl(EnableBottleneckAnalysis, EnableAllViews);322processOptionImpl(PrintResourcePressureView, EnableAllViews);323processOptionImpl(PrintTimelineView, EnableAllViews);324processOptionImpl(PrintInstructionInfoView, EnableAllViews);325}326327const cl::opt<bool> &Default =328EnableAllViews.getPosition() < EnableAllStats.getPosition()329? EnableAllStats330: EnableAllViews;331processOptionImpl(PrintRegisterFileStats, Default);332processOptionImpl(PrintDispatchStats, Default);333processOptionImpl(PrintSchedulerStats, Default);334if (IsOutOfOrder)335processOptionImpl(PrintRetireStats, Default);336}337338// Returns true on success.339static bool runPipeline(mca::Pipeline &P) {340// Handle pipeline errors here.341Expected<unsigned> Cycles = P.run();342if (!Cycles) {343WithColor::error() << toString(Cycles.takeError());344return false;345}346return true;347}348349int main(int argc, char **argv) {350InitLLVM X(argc, argv);351352// Initialize targets and assembly parsers.353InitializeAllTargetInfos();354InitializeAllTargetMCs();355InitializeAllAsmParsers();356InitializeAllTargetMCAs();357358// Register the Target and CPU printer for --version.359cl::AddExtraVersionPrinter(sys::printDefaultTargetAndDetectedCPU);360361// Enable printing of available targets when flag --version is specified.362cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);363364cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});365366// Parse flags and initialize target options.367cl::ParseCommandLineOptions(argc, argv,368"llvm machine code performance analyzer.\n");369370// Get the target from the triple. If a triple is not specified, then select371// the default triple for the host. If the triple doesn't correspond to any372// registered target, then exit with an error message.373const char *ProgName = argv[0];374const Target *TheTarget = getTarget(ProgName);375if (!TheTarget)376return 1;377378// GetTarget() may replaced TripleName with a default triple.379// For safety, reconstruct the Triple object.380Triple TheTriple(TripleName);381382ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =383MemoryBuffer::getFileOrSTDIN(InputFilename);384if (std::error_code EC = BufferPtr.getError()) {385WithColor::error() << InputFilename << ": " << EC.message() << '\n';386return 1;387}388389if (MCPU == "native")390MCPU = std::string(llvm::sys::getHostCPUName());391392// Package up features to be passed to target/subtarget393std::string FeaturesStr;394if (MATTRS.size()) {395SubtargetFeatures Features;396for (std::string &MAttr : MATTRS)397Features.AddFeature(MAttr);398FeaturesStr = Features.getString();399}400401std::unique_ptr<MCSubtargetInfo> STI(402TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));403assert(STI && "Unable to create subtarget info!");404if (!STI->isCPUStringValid(MCPU))405return 1;406407if (!STI->getSchedModel().hasInstrSchedModel()) {408WithColor::error()409<< "unable to find instruction-level scheduling information for"410<< " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU411<< "'.\n";412413if (STI->getSchedModel().InstrItineraries)414WithColor::note()415<< "cpu '" << MCPU << "' provides itineraries. However, "416<< "instruction itineraries are currently unsupported.\n";417return 1;418}419420// Apply overrides to llvm-mca specific options.421bool IsOutOfOrder = STI->getSchedModel().isOutOfOrder();422processViewOptions(IsOutOfOrder);423424std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));425assert(MRI && "Unable to create target register info!");426427MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags();428std::unique_ptr<MCAsmInfo> MAI(429TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions));430assert(MAI && "Unable to create target asm info!");431432SourceMgr SrcMgr;433434// Tell SrcMgr about this buffer, which is what the parser will pick up.435SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());436437std::unique_ptr<buffer_ostream> BOS;438439std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());440assert(MCII && "Unable to create instruction info!");441442std::unique_ptr<MCInstrAnalysis> MCIA(443TheTarget->createMCInstrAnalysis(MCII.get()));444445// Need to initialize an MCInstPrinter as it is446// required for initializing the MCTargetStreamer447// which needs to happen within the CRG.parseAnalysisRegions() call below.448// Without an MCTargetStreamer, certain assembly directives can trigger a449// segfault. (For example, the .cv_fpo_proc directive on x86 will segfault if450// we don't initialize the MCTargetStreamer.)451unsigned IPtempOutputAsmVariant =452OutputAsmVariant == -1 ? 0 : OutputAsmVariant;453std::unique_ptr<MCInstPrinter> IPtemp(TheTarget->createMCInstPrinter(454Triple(TripleName), IPtempOutputAsmVariant, *MAI, *MCII, *MRI));455if (!IPtemp) {456WithColor::error()457<< "unable to create instruction printer for target triple '"458<< TheTriple.normalize() << "' with assembly variant "459<< IPtempOutputAsmVariant << ".\n";460return 1;461}462463// Parse the input and create CodeRegions that llvm-mca can analyze.464MCContext ACtx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr);465std::unique_ptr<MCObjectFileInfo> AMOFI(466TheTarget->createMCObjectFileInfo(ACtx, /*PIC=*/false));467ACtx.setObjectFileInfo(AMOFI.get());468mca::AsmAnalysisRegionGenerator CRG(*TheTarget, SrcMgr, ACtx, *MAI, *STI,469*MCII);470Expected<const mca::AnalysisRegions &> RegionsOrErr =471CRG.parseAnalysisRegions(std::move(IPtemp),472shouldSkip(SkipType::PARSE_FAILURE));473if (!RegionsOrErr) {474if (auto Err =475handleErrors(RegionsOrErr.takeError(), [](const StringError &E) {476WithColor::error() << E.getMessage() << '\n';477})) {478// Default case.479WithColor::error() << toString(std::move(Err)) << '\n';480}481return 1;482}483const mca::AnalysisRegions &Regions = *RegionsOrErr;484485// Early exit if errors were found by the code region parsing logic.486if (!Regions.isValid())487return 1;488489if (Regions.empty()) {490WithColor::error() << "no assembly instructions found.\n";491return 1;492}493494std::unique_ptr<mca::InstrumentManager> IM;495if (!DisableInstrumentManager) {496IM = std::unique_ptr<mca::InstrumentManager>(497TheTarget->createInstrumentManager(*STI, *MCII));498}499if (!IM) {500// If the target doesn't have its own IM implemented (or the -disable-cb501// flag is set) then we use the base class (which does nothing).502IM = std::make_unique<mca::InstrumentManager>(*STI, *MCII);503}504505// Parse the input and create InstrumentRegion that llvm-mca506// can use to improve analysis.507MCContext ICtx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr);508std::unique_ptr<MCObjectFileInfo> IMOFI(509TheTarget->createMCObjectFileInfo(ICtx, /*PIC=*/false));510ICtx.setObjectFileInfo(IMOFI.get());511mca::AsmInstrumentRegionGenerator IRG(*TheTarget, SrcMgr, ICtx, *MAI, *STI,512*MCII, *IM);513Expected<const mca::InstrumentRegions &> InstrumentRegionsOrErr =514IRG.parseInstrumentRegions(std::move(IPtemp),515shouldSkip(SkipType::PARSE_FAILURE));516if (!InstrumentRegionsOrErr) {517if (auto Err = handleErrors(InstrumentRegionsOrErr.takeError(),518[](const StringError &E) {519WithColor::error() << E.getMessage() << '\n';520})) {521// Default case.522WithColor::error() << toString(std::move(Err)) << '\n';523}524return 1;525}526const mca::InstrumentRegions &InstrumentRegions = *InstrumentRegionsOrErr;527528// Early exit if errors were found by the instrumentation parsing logic.529if (!InstrumentRegions.isValid())530return 1;531532// Now initialize the output file.533auto OF = getOutputStream();534if (std::error_code EC = OF.getError()) {535WithColor::error() << EC.message() << '\n';536return 1;537}538539unsigned AssemblerDialect = CRG.getAssemblerDialect();540if (OutputAsmVariant >= 0)541AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);542std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(543Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));544if (!IP) {545WithColor::error()546<< "unable to create instruction printer for target triple '"547<< TheTriple.normalize() << "' with assembly variant "548<< AssemblerDialect << ".\n";549return 1;550}551552// Set the display preference for hex vs. decimal immediates.553IP->setPrintImmHex(PrintImmHex);554555std::unique_ptr<ToolOutputFile> TOF = std::move(*OF);556557const MCSchedModel &SM = STI->getSchedModel();558559std::unique_ptr<mca::InstrPostProcess> IPP;560if (!DisableCustomBehaviour) {561// TODO: It may be a good idea to separate CB and IPP so that they can562// be used independently of each other. What I mean by this is to add563// an extra command-line arg --disable-ipp so that CB and IPP can be564// toggled without needing to toggle both of them together.565IPP = std::unique_ptr<mca::InstrPostProcess>(566TheTarget->createInstrPostProcess(*STI, *MCII));567}568if (!IPP) {569// If the target doesn't have its own IPP implemented (or the -disable-cb570// flag is set) then we use the base class (which does nothing).571IPP = std::make_unique<mca::InstrPostProcess>(*STI, *MCII);572}573574// Create an instruction builder.575mca::InstrBuilder IB(*STI, *MCII, *MRI, MCIA.get(), *IM, CallLatency);576577// Create a context to control ownership of the pipeline hardware.578mca::Context MCA(*MRI, *STI);579580mca::PipelineOptions PO(MicroOpQueue, DecoderThroughput, DispatchWidth,581RegisterFileSize, LoadQueueSize, StoreQueueSize,582AssumeNoAlias, EnableBottleneckAnalysis);583584// Number each region in the sequence.585unsigned RegionIdx = 0;586587std::unique_ptr<MCCodeEmitter> MCE(588TheTarget->createMCCodeEmitter(*MCII, ACtx));589assert(MCE && "Unable to create code emitter!");590591std::unique_ptr<MCAsmBackend> MAB(TheTarget->createMCAsmBackend(592*STI, *MRI, mc::InitMCTargetOptionsFromFlags()));593assert(MAB && "Unable to create asm backend!");594595json::Object JSONOutput;596int NonEmptyRegions = 0;597for (const std::unique_ptr<mca::AnalysisRegion> &Region : Regions) {598// Skip empty code regions.599if (Region->empty())600continue;601602IB.clear();603604// Lower the MCInst sequence into an mca::Instruction sequence.605ArrayRef<MCInst> Insts = Region->getInstructions();606mca::CodeEmitter CE(*STI, *MAB, *MCE, Insts);607608IPP->resetState();609610DenseMap<const MCInst *, SmallVector<mca::Instrument *>> InstToInstruments;611SmallVector<std::unique_ptr<mca::Instruction>> LoweredSequence;612SmallPtrSet<const MCInst *, 16> DroppedInsts;613for (const MCInst &MCI : Insts) {614SMLoc Loc = MCI.getLoc();615const SmallVector<mca::Instrument *> Instruments =616InstrumentRegions.getActiveInstruments(Loc);617618Expected<std::unique_ptr<mca::Instruction>> Inst =619IB.createInstruction(MCI, Instruments);620if (!Inst) {621if (auto NewE = handleErrors(622Inst.takeError(),623[&IP, &STI](const mca::InstructionError<MCInst> &IE) {624std::string InstructionStr;625raw_string_ostream SS(InstructionStr);626if (shouldSkip(SkipType::LACK_SCHED))627WithColor::warning()628<< IE.Message629<< ", skipping with -skip-unsupported-instructions, "630"note accuracy will be impacted:\n";631else632WithColor::error()633<< IE.Message634<< ", use -skip-unsupported-instructions=lack-sched to "635"ignore these on the input.\n";636IP->printInst(&IE.Inst, 0, "", *STI, SS);637SS.flush();638WithColor::note()639<< "instruction: " << InstructionStr << '\n';640})) {641// Default case.642WithColor::error() << toString(std::move(NewE));643}644if (shouldSkip(SkipType::LACK_SCHED)) {645DroppedInsts.insert(&MCI);646continue;647}648return 1;649}650651IPP->postProcessInstruction(Inst.get(), MCI);652InstToInstruments.insert({&MCI, Instruments});653LoweredSequence.emplace_back(std::move(Inst.get()));654}655656Insts = Region->dropInstructions(DroppedInsts);657658// Skip empty regions.659if (Insts.empty())660continue;661NonEmptyRegions++;662663mca::CircularSourceMgr S(LoweredSequence,664PrintInstructionTables ? 1 : Iterations);665666if (PrintInstructionTables) {667// Create a pipeline, stages, and a printer.668auto P = std::make_unique<mca::Pipeline>();669P->appendStage(std::make_unique<mca::EntryStage>(S));670P->appendStage(std::make_unique<mca::InstructionTables>(SM));671672mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);673if (PrintJson) {674Printer.addView(675std::make_unique<mca::InstructionView>(*STI, *IP, Insts));676}677678// Create the views for this pipeline, execute, and emit a report.679if (PrintInstructionInfoView) {680Printer.addView(std::make_unique<mca::InstructionInfoView>(681*STI, *MCII, CE, ShowEncoding, Insts, *IP, LoweredSequence,682ShowBarriers, *IM, InstToInstruments));683}684Printer.addView(685std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));686687if (!runPipeline(*P))688return 1;689690if (PrintJson) {691Printer.printReport(JSONOutput);692} else {693Printer.printReport(TOF->os());694}695696++RegionIdx;697continue;698}699700// Create the CustomBehaviour object for enforcing Target Specific701// behaviours and dependencies that aren't expressed well enough702// in the tablegen. CB cannot depend on the list of MCInst or703// the source code (but it can depend on the list of704// mca::Instruction or any objects that can be reconstructed705// from the target information).706std::unique_ptr<mca::CustomBehaviour> CB;707if (!DisableCustomBehaviour)708CB = std::unique_ptr<mca::CustomBehaviour>(709TheTarget->createCustomBehaviour(*STI, S, *MCII));710if (!CB)711// If the target doesn't have its own CB implemented (or the -disable-cb712// flag is set) then we use the base class (which does nothing).713CB = std::make_unique<mca::CustomBehaviour>(*STI, S, *MCII);714715// Create a basic pipeline simulating an out-of-order backend.716auto P = MCA.createDefaultPipeline(PO, S, *CB);717718mca::PipelinePrinter Printer(*P, *Region, RegionIdx, *STI, PO);719720// Targets can define their own custom Views that exist within their721// /lib/Target/ directory so that the View can utilize their CustomBehaviour722// or other backend symbols / functionality that are not already exposed723// through one of the MC-layer classes. These Views will be initialized724// using the CustomBehaviour::getViews() variants.725// If a target makes a custom View that does not depend on their target726// CB or their backend, they should put the View within727// /tools/llvm-mca/Views/ instead.728if (!DisableCustomBehaviour) {729std::vector<std::unique_ptr<mca::View>> CBViews =730CB->getStartViews(*IP, Insts);731for (auto &CBView : CBViews)732Printer.addView(std::move(CBView));733}734735// When we output JSON, we add a view that contains the instructions736// and CPU resource information.737if (PrintJson) {738auto IV = std::make_unique<mca::InstructionView>(*STI, *IP, Insts);739Printer.addView(std::move(IV));740}741742if (PrintSummaryView)743Printer.addView(744std::make_unique<mca::SummaryView>(SM, Insts, DispatchWidth));745746if (EnableBottleneckAnalysis) {747if (!IsOutOfOrder) {748WithColor::warning()749<< "bottleneck analysis is not supported for in-order CPU '" << MCPU750<< "'.\n";751}752Printer.addView(std::make_unique<mca::BottleneckAnalysis>(753*STI, *IP, Insts, S.getNumIterations()));754}755756if (PrintInstructionInfoView)757Printer.addView(std::make_unique<mca::InstructionInfoView>(758*STI, *MCII, CE, ShowEncoding, Insts, *IP, LoweredSequence,759ShowBarriers, *IM, InstToInstruments));760761// Fetch custom Views that are to be placed after the InstructionInfoView.762// Refer to the comment paired with the CB->getStartViews(*IP, Insts); line763// for more info.764if (!DisableCustomBehaviour) {765std::vector<std::unique_ptr<mca::View>> CBViews =766CB->getPostInstrInfoViews(*IP, Insts);767for (auto &CBView : CBViews)768Printer.addView(std::move(CBView));769}770771if (PrintDispatchStats)772Printer.addView(std::make_unique<mca::DispatchStatistics>());773774if (PrintSchedulerStats)775Printer.addView(std::make_unique<mca::SchedulerStatistics>(*STI));776777if (PrintRetireStats)778Printer.addView(std::make_unique<mca::RetireControlUnitStatistics>(SM));779780if (PrintRegisterFileStats)781Printer.addView(std::make_unique<mca::RegisterFileStatistics>(*STI));782783if (PrintResourcePressureView)784Printer.addView(785std::make_unique<mca::ResourcePressureView>(*STI, *IP, Insts));786787if (PrintTimelineView) {788unsigned TimelineIterations =789TimelineMaxIterations ? TimelineMaxIterations : 10;790Printer.addView(std::make_unique<mca::TimelineView>(791*STI, *IP, Insts, std::min(TimelineIterations, S.getNumIterations()),792TimelineMaxCycles));793}794795// Fetch custom Views that are to be placed after all other Views.796// Refer to the comment paired with the CB->getStartViews(*IP, Insts); line797// for more info.798if (!DisableCustomBehaviour) {799std::vector<std::unique_ptr<mca::View>> CBViews =800CB->getEndViews(*IP, Insts);801for (auto &CBView : CBViews)802Printer.addView(std::move(CBView));803}804805if (!runPipeline(*P))806return 1;807808if (PrintJson) {809Printer.printReport(JSONOutput);810} else {811Printer.printReport(TOF->os());812}813814++RegionIdx;815}816817if (NonEmptyRegions == 0) {818WithColor::error() << "no assembly instructions found.\n";819return 1;820}821822if (PrintJson)823TOF->os() << formatv("{0:2}", json::Value(std::move(JSONOutput))) << "\n";824825TOF->keep();826return 0;827}828829830