[PowerPC] Optimize compares fed by ANDISo
[llvm-core.git] / tools / llvm-mca / llvm-mca.cpp
bloba7b543acafdd0e814d754a36956efb7d847ddf35
1 //===-- llvm-mca.cpp - Machine Code Analyzer -------------------*- C++ -* -===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This utility is a simple driver that allows static performance analysis on
11 // machine code similarly to how IACA (Intel Architecture Code Analyzer) works.
13 // llvm-mca [options] <file-name>
14 // -march <type>
15 // -mcpu <cpu>
16 // -o <file>
18 // The target defaults to the host target.
19 // The cpu defaults to the 'native' host cpu.
20 // The output defaults to standard output.
22 //===----------------------------------------------------------------------===//
24 #include "CodeRegion.h"
25 #include "PipelinePrinter.h"
26 #include "Stages/FetchStage.h"
27 #include "Stages/InstructionTables.h"
28 #include "Views/DispatchStatistics.h"
29 #include "Views/InstructionInfoView.h"
30 #include "Views/RegisterFileStatistics.h"
31 #include "Views/ResourcePressureView.h"
32 #include "Views/RetireControlUnitStatistics.h"
33 #include "Views/SchedulerStatistics.h"
34 #include "Views/SummaryView.h"
35 #include "Views/TimelineView.h"
36 #include "include/Context.h"
37 #include "include/Pipeline.h"
38 #include "llvm/MC/MCAsmInfo.h"
39 #include "llvm/MC/MCContext.h"
40 #include "llvm/MC/MCObjectFileInfo.h"
41 #include "llvm/MC/MCParser/MCTargetAsmParser.h"
42 #include "llvm/MC/MCRegisterInfo.h"
43 #include "llvm/MC/MCStreamer.h"
44 #include "llvm/Support/CommandLine.h"
45 #include "llvm/Support/ErrorHandling.h"
46 #include "llvm/Support/ErrorOr.h"
47 #include "llvm/Support/FileSystem.h"
48 #include "llvm/Support/Host.h"
49 #include "llvm/Support/InitLLVM.h"
50 #include "llvm/Support/MemoryBuffer.h"
51 #include "llvm/Support/SourceMgr.h"
52 #include "llvm/Support/TargetRegistry.h"
53 #include "llvm/Support/TargetSelect.h"
54 #include "llvm/Support/ToolOutputFile.h"
55 #include "llvm/Support/WithColor.h"
57 using namespace llvm;
59 static cl::OptionCategory ToolOptions("Tool Options");
60 static cl::OptionCategory ViewOptions("View Options");
62 static cl::opt<std::string> InputFilename(cl::Positional,
63 cl::desc("<input file>"),
64 cl::cat(ToolOptions), cl::init("-"));
66 static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
67 cl::init("-"), cl::cat(ToolOptions),
68 cl::value_desc("filename"));
70 static cl::opt<std::string>
71 ArchName("march", cl::desc("Target arch to assemble for, "
72 "see -version for available targets"),
73 cl::cat(ToolOptions));
75 static cl::opt<std::string>
76 TripleName("mtriple", cl::desc("Target triple to assemble for, "
77 "see -version for available targets"),
78 cl::cat(ToolOptions));
80 static cl::opt<std::string>
81 MCPU("mcpu",
82 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
83 cl::value_desc("cpu-name"), cl::cat(ToolOptions), cl::init("native"));
85 static cl::opt<int>
86 OutputAsmVariant("output-asm-variant",
87 cl::desc("Syntax variant to use for output printing"),
88 cl::cat(ToolOptions), cl::init(-1));
90 static cl::opt<unsigned> Iterations("iterations",
91 cl::desc("Number of iterations to run"),
92 cl::cat(ToolOptions), cl::init(0));
94 static cl::opt<unsigned>
95 DispatchWidth("dispatch", cl::desc("Override the processor dispatch width"),
96 cl::cat(ToolOptions), cl::init(0));
98 static cl::opt<unsigned>
99 RegisterFileSize("register-file-size",
100 cl::desc("Maximum number of physical registers which can "
101 "be used for register mappings"),
102 cl::cat(ToolOptions), cl::init(0));
104 static cl::opt<bool>
105 PrintRegisterFileStats("register-file-stats",
106 cl::desc("Print register file statistics"),
107 cl::cat(ViewOptions), cl::init(false));
109 static cl::opt<bool> PrintDispatchStats("dispatch-stats",
110 cl::desc("Print dispatch statistics"),
111 cl::cat(ViewOptions), cl::init(false));
113 static cl::opt<bool>
114 PrintSummaryView("summary-view", cl::Hidden,
115 cl::desc("Print summary view (enabled by default)"),
116 cl::cat(ViewOptions), cl::init(true));
118 static cl::opt<bool> PrintSchedulerStats("scheduler-stats",
119 cl::desc("Print scheduler statistics"),
120 cl::cat(ViewOptions), cl::init(false));
122 static cl::opt<bool>
123 PrintRetireStats("retire-stats",
124 cl::desc("Print retire control unit statistics"),
125 cl::cat(ViewOptions), cl::init(false));
127 static cl::opt<bool> PrintResourcePressureView(
128 "resource-pressure",
129 cl::desc("Print the resource pressure view (enabled by default)"),
130 cl::cat(ViewOptions), cl::init(true));
132 static cl::opt<bool> PrintTimelineView("timeline",
133 cl::desc("Print the timeline view"),
134 cl::cat(ViewOptions), cl::init(false));
136 static cl::opt<unsigned> TimelineMaxIterations(
137 "timeline-max-iterations",
138 cl::desc("Maximum number of iterations to print in timeline view"),
139 cl::cat(ViewOptions), cl::init(0));
141 static cl::opt<unsigned> TimelineMaxCycles(
142 "timeline-max-cycles",
143 cl::desc(
144 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
145 cl::cat(ViewOptions), cl::init(80));
147 static cl::opt<bool>
148 AssumeNoAlias("noalias",
149 cl::desc("If set, assume that loads and stores do not alias"),
150 cl::cat(ToolOptions), cl::init(true));
152 static cl::opt<unsigned>
153 LoadQueueSize("lqueue",
154 cl::desc("Size of the load queue (unbound by default)"),
155 cl::cat(ToolOptions), cl::init(0));
157 static cl::opt<unsigned>
158 StoreQueueSize("squeue",
159 cl::desc("Size of the store queue (unbound by default)"),
160 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));
167 static cl::opt<bool> PrintInstructionInfoView(
168 "instruction-info",
169 cl::desc("Print the instruction info view (enabled by default)"),
170 cl::cat(ViewOptions), cl::init(true));
172 static cl::opt<bool> EnableAllStats("all-stats",
173 cl::desc("Print all hardware statistics"),
174 cl::cat(ViewOptions), cl::init(false));
176 static cl::opt<bool>
177 EnableAllViews("all-views",
178 cl::desc("Print all views including hardware statistics"),
179 cl::cat(ViewOptions), cl::init(false));
181 namespace {
183 const Target *getTarget(const char *ProgName) {
184 if (TripleName.empty())
185 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
186 Triple TheTriple(TripleName);
188 // Get the target specific parser.
189 std::string Error;
190 const Target *TheTarget =
191 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
192 if (!TheTarget) {
193 errs() << ProgName << ": " << Error;
194 return nullptr;
197 // Return the found target.
198 return TheTarget;
201 // A comment consumer that parses strings.
202 // The only valid tokens are strings.
203 class MCACommentConsumer : public AsmCommentConsumer {
204 public:
205 mca::CodeRegions &Regions;
207 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
208 void HandleComment(SMLoc Loc, StringRef CommentText) override {
209 // Skip empty comments.
210 StringRef Comment(CommentText);
211 if (Comment.empty())
212 return;
214 // Skip spaces and tabs
215 unsigned Position = Comment.find_first_not_of(" \t");
216 if (Position >= Comment.size())
217 // we reached the end of the comment. Bail out.
218 return;
220 Comment = Comment.drop_front(Position);
221 if (Comment.consume_front("LLVM-MCA-END")) {
222 Regions.endRegion(Loc);
223 return;
226 // Now try to parse string LLVM-MCA-BEGIN
227 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
228 return;
230 // Skip spaces and tabs
231 Position = Comment.find_first_not_of(" \t");
232 if (Position < Comment.size())
233 Comment = Comment.drop_front(Position);
234 // Use the rest of the string as a descriptor for this code snippet.
235 Regions.beginRegion(Comment, Loc);
239 int AssembleInput(MCAsmParser &Parser, const Target *TheTarget,
240 MCSubtargetInfo &STI, MCInstrInfo &MCII,
241 MCTargetOptions &MCOptions) {
242 std::unique_ptr<MCTargetAsmParser> TAP(
243 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
245 if (!TAP) {
246 WithColor::error() << "this target does not support assembly parsing.\n";
247 return 1;
250 Parser.setTargetParser(*TAP);
251 return Parser.Run(false);
254 ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
255 if (OutputFilename == "")
256 OutputFilename = "-";
257 std::error_code EC;
258 auto Out =
259 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
260 if (!EC)
261 return std::move(Out);
262 return EC;
265 class MCStreamerWrapper final : public MCStreamer {
266 mca::CodeRegions &Regions;
268 public:
269 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
270 : MCStreamer(Context), Regions(R) {}
272 // We only want to intercept the emission of new instructions.
273 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
274 bool /* unused */) override {
275 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
278 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
279 return true;
282 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
283 unsigned ByteAlignment) override {}
284 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
285 uint64_t Size = 0, unsigned ByteAlignment = 0,
286 SMLoc Loc = SMLoc()) override {}
287 void EmitGPRel32Value(const MCExpr *Value) override {}
288 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
289 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
290 void EmitCOFFSymbolType(int Type) override {}
291 void EndCOFFSymbolDef() override {}
293 const std::vector<std::unique_ptr<const MCInst>> &
294 GetInstructionSequence(unsigned Index) const {
295 return Regions.getInstructionSequence(Index);
298 } // end of anonymous namespace
300 static void processOptionImpl(cl::opt<bool> &O, const cl::opt<bool> &Default) {
301 if (!O.getNumOccurrences() || O.getPosition() < Default.getPosition())
302 O = Default.getValue();
305 static void processViewOptions() {
306 if (!EnableAllViews.getNumOccurrences() &&
307 !EnableAllStats.getNumOccurrences())
308 return;
310 if (EnableAllViews.getNumOccurrences()) {
311 processOptionImpl(PrintSummaryView, EnableAllViews);
312 processOptionImpl(PrintResourcePressureView, EnableAllViews);
313 processOptionImpl(PrintTimelineView, EnableAllViews);
314 processOptionImpl(PrintInstructionInfoView, EnableAllViews);
317 const cl::opt<bool> &Default =
318 EnableAllViews.getPosition() < EnableAllStats.getPosition()
319 ? EnableAllStats
320 : EnableAllViews;
321 processOptionImpl(PrintRegisterFileStats, Default);
322 processOptionImpl(PrintDispatchStats, Default);
323 processOptionImpl(PrintSchedulerStats, Default);
324 processOptionImpl(PrintRetireStats, Default);
327 int main(int argc, char **argv) {
328 InitLLVM X(argc, argv);
330 // Initialize targets and assembly parsers.
331 llvm::InitializeAllTargetInfos();
332 llvm::InitializeAllTargetMCs();
333 llvm::InitializeAllAsmParsers();
335 // Enable printing of available targets when flag --version is specified.
336 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
338 cl::HideUnrelatedOptions({&ToolOptions, &ViewOptions});
340 // Parse flags and initialize target options.
341 cl::ParseCommandLineOptions(argc, argv,
342 "llvm machine code performance analyzer.\n");
344 MCTargetOptions MCOptions;
345 MCOptions.PreserveAsmComments = false;
347 // Get the target from the triple. If a triple is not specified, then select
348 // the default triple for the host. If the triple doesn't correspond to any
349 // registered target, then exit with an error message.
350 const char *ProgName = argv[0];
351 const Target *TheTarget = getTarget(ProgName);
352 if (!TheTarget)
353 return 1;
355 // GetTarget() may replaced TripleName with a default triple.
356 // For safety, reconstruct the Triple object.
357 Triple TheTriple(TripleName);
359 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
360 MemoryBuffer::getFileOrSTDIN(InputFilename);
361 if (std::error_code EC = BufferPtr.getError()) {
362 WithColor::error() << InputFilename << ": " << EC.message() << '\n';
363 return 1;
366 // Apply overrides to llvm-mca specific options.
367 processViewOptions();
369 SourceMgr SrcMgr;
371 // Tell SrcMgr about this buffer, which is what the parser will pick up.
372 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
374 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
375 assert(MRI && "Unable to create target register info!");
377 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
378 assert(MAI && "Unable to create target asm info!");
380 MCObjectFileInfo MOFI;
381 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
382 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
384 std::unique_ptr<buffer_ostream> BOS;
386 mca::CodeRegions Regions(SrcMgr);
387 MCStreamerWrapper Str(Ctx, Regions);
389 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
391 std::unique_ptr<MCInstrAnalysis> MCIA(
392 TheTarget->createMCInstrAnalysis(MCII.get()));
394 if (!MCPU.compare("native"))
395 MCPU = llvm::sys::getHostCPUName();
397 std::unique_ptr<MCSubtargetInfo> STI(
398 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
399 if (!STI->isCPUStringValid(MCPU))
400 return 1;
402 if (!PrintInstructionTables && !STI->getSchedModel().isOutOfOrder()) {
403 WithColor::error() << "please specify an out-of-order cpu. '" << MCPU
404 << "' is an in-order cpu.\n";
405 return 1;
408 if (!STI->getSchedModel().hasInstrSchedModel()) {
409 WithColor::error()
410 << "unable to find instruction-level scheduling information for"
411 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
412 << "'.\n";
414 if (STI->getSchedModel().InstrItineraries)
415 WithColor::note()
416 << "cpu '" << MCPU << "' provides itineraries. However, "
417 << "instruction itineraries are currently unsupported.\n";
418 return 1;
421 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
422 MCAsmLexer &Lexer = P->getLexer();
423 MCACommentConsumer CC(Regions);
424 Lexer.setCommentConsumer(&CC);
426 if (AssembleInput(*P, TheTarget, *STI, *MCII, MCOptions))
427 return 1;
429 if (Regions.empty()) {
430 WithColor::error() << "no assembly instructions found.\n";
431 return 1;
434 // Now initialize the output file.
435 auto OF = getOutputStream();
436 if (std::error_code EC = OF.getError()) {
437 WithColor::error() << EC.message() << '\n';
438 return 1;
441 unsigned AssemblerDialect = P->getAssemblerDialect();
442 if (OutputAsmVariant >= 0)
443 AssemblerDialect = static_cast<unsigned>(OutputAsmVariant);
444 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
445 Triple(TripleName), AssemblerDialect, *MAI, *MCII, *MRI));
446 if (!IP) {
447 WithColor::error()
448 << "unable to create instruction printer for target triple '"
449 << TheTriple.normalize() << "' with assembly variant "
450 << AssemblerDialect << ".\n";
451 return 1;
454 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
456 const MCSchedModel &SM = STI->getSchedModel();
458 unsigned Width = SM.IssueWidth;
459 if (DispatchWidth)
460 Width = DispatchWidth;
462 // Create an instruction builder.
463 mca::InstrBuilder IB(*STI, *MCII, *MRI, *MCIA, *IP);
465 // Create a context to control ownership of the pipeline hardware.
466 mca::Context MCA(*MRI, *STI);
468 mca::PipelineOptions PO(Width, RegisterFileSize, LoadQueueSize,
469 StoreQueueSize, AssumeNoAlias);
471 // Number each region in the sequence.
472 unsigned RegionIdx = 0;
473 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
474 // Skip empty code regions.
475 if (Region->empty())
476 continue;
478 // Don't print the header of this region if it is the default region, and
479 // it doesn't have an end location.
480 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
481 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
482 StringRef Desc = Region->getDescription();
483 if (!Desc.empty())
484 TOF->os() << " - " << Desc;
485 TOF->os() << "\n\n";
488 mca::SourceMgr S(Region->getInstructions(),
489 PrintInstructionTables ? 1 : Iterations);
491 if (PrintInstructionTables) {
492 // Create a pipeline, stages, and a printer.
493 auto P = llvm::make_unique<mca::Pipeline>();
494 P->appendStage(llvm::make_unique<mca::FetchStage>(IB, S));
495 P->appendStage(llvm::make_unique<mca::InstructionTables>(SM, IB));
496 mca::PipelinePrinter Printer(*P);
498 // Create the views for this pipeline, execute, and emit a report.
499 if (PrintInstructionInfoView) {
500 Printer.addView(
501 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
503 Printer.addView(
504 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
505 auto Err = P->run();
506 if (Err)
507 report_fatal_error(toString(std::move(Err)));
508 Printer.printReport(TOF->os());
509 continue;
512 // Create a basic pipeline simulating an out-of-order backend.
513 auto P = MCA.createDefaultPipeline(PO, IB, S);
514 mca::PipelinePrinter Printer(*P);
516 if (PrintSummaryView)
517 Printer.addView(llvm::make_unique<mca::SummaryView>(SM, S, Width));
519 if (PrintInstructionInfoView)
520 Printer.addView(
521 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
523 if (PrintDispatchStats)
524 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
526 if (PrintSchedulerStats)
527 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
529 if (PrintRetireStats)
530 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
532 if (PrintRegisterFileStats)
533 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
535 if (PrintResourcePressureView)
536 Printer.addView(
537 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
539 if (PrintTimelineView) {
540 Printer.addView(llvm::make_unique<mca::TimelineView>(
541 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
544 auto Err = P->run();
545 if (Err)
546 report_fatal_error(toString(std::move(Err)));
547 Printer.printReport(TOF->os());
549 // Clear the InstrBuilder internal state in preparation for another round.
550 IB.clear();
553 TOF->keep();
554 return 0;