blob: 89900a40dd6c7cf08f87722e83fceeddbb763b5b [file] [log] [blame]
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +00001//===-- 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.
12//
13// llvm-mca [options] <file-name>
14// -march <type>
15// -mcpu <cpu>
16// -o <file>
17//
18// The target defaults to the host target.
19// The cpu defaults to 'generic'.
20// The output defaults to standard output.
21//
22//===----------------------------------------------------------------------===//
23
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000024#include "BackendPrinter.h"
Andrea Di Biagioc6590122018-04-09 16:39:52 +000025#include "CodeRegion.h"
Andrea Di Biagio821f6502018-04-10 14:55:14 +000026#include "DispatchStatistics.h"
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +000027#include "InstructionInfoView.h"
Andrea Di Biagiod1569292018-03-26 12:04:53 +000028#include "InstructionTables.h"
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000029#include "RegisterFileStatistics.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000030#include "ResourcePressureView.h"
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +000031#include "RetireControlUnitStatistics.h"
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +000032#include "SchedulerStatistics.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000033#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000034#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000035#include "llvm/MC/MCAsmInfo.h"
36#include "llvm/MC/MCContext.h"
37#include "llvm/MC/MCObjectFileInfo.h"
38#include "llvm/MC/MCParser/MCTargetAsmParser.h"
39#include "llvm/MC/MCRegisterInfo.h"
40#include "llvm/MC/MCStreamer.h"
41#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000042#include "llvm/Support/ErrorOr.h"
43#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000044#include "llvm/Support/MemoryBuffer.h"
45#include "llvm/Support/PrettyStackTrace.h"
46#include "llvm/Support/Signals.h"
47#include "llvm/Support/SourceMgr.h"
48#include "llvm/Support/TargetRegistry.h"
49#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000050#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000051
52using namespace llvm;
53
54static cl::opt<std::string>
55 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
56
57static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
58 cl::init("-"),
59 cl::value_desc("filename"));
60
61static cl::opt<std::string>
62 ArchName("march", cl::desc("Target arch to assemble for, "
63 "see -version for available targets"));
64
65static cl::opt<std::string>
66 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000067 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000068
69static cl::opt<std::string>
70 MCPU("mcpu",
71 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
72 cl::value_desc("cpu-name"), cl::init("generic"));
73
74static cl::opt<unsigned>
75 OutputAsmVariant("output-asm-variant",
76 cl::desc("Syntax variant to use for output printing"));
77
78static cl::opt<unsigned> Iterations("iterations",
79 cl::desc("Number of iterations to run"),
80 cl::init(0));
81
82static cl::opt<unsigned> DispatchWidth(
83 "dispatch",
84 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
85 cl::init(0));
86
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000087static cl::opt<unsigned>
88 RegisterFileSize("register-file-size",
89 cl::desc("Maximum number of temporary registers which can "
90 "be used for register mappings"),
91 cl::init(0));
92
Andrea Di Biagio29538c62018-03-23 11:33:09 +000093static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000094 PrintRegisterFileStats("register-file-stats",
95 cl::desc("Print register file statistics"),
96 cl::init(false));
97
98static cl::opt<bool>
Andrea Di Biagio821f6502018-04-10 14:55:14 +000099 PrintDispatchStats("dispatch-stats",
100 cl::desc("Print dispatch statistics"),
101 cl::init(false));
102
103static cl::opt<bool>
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000104 PrintSchedulerStats("scheduler-stats",
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000105 cl::desc("Print scheduler statistics"),
106 cl::init(false));
107
108static cl::opt<bool>
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000109 PrintRetireStats("retire-stats",
110 cl::desc("Print retire control unit statistics"),
111 cl::init(false));
112
113static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000114 PrintResourcePressureView("resource-pressure",
115 cl::desc("Print the resource pressure view"),
116 cl::init(true));
117
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000118static cl::opt<bool> PrintTimelineView("timeline",
119 cl::desc("Print the timeline view"),
120 cl::init(false));
121
122static cl::opt<unsigned> TimelineMaxIterations(
123 "timeline-max-iterations",
124 cl::desc("Maximum number of iterations to print in timeline view"),
125 cl::init(0));
126
127static cl::opt<unsigned> TimelineMaxCycles(
128 "timeline-max-cycles",
129 cl::desc(
130 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
131 cl::init(80));
132
133static cl::opt<bool> PrintModeVerbose("verbose",
134 cl::desc("Enable verbose output"),
135 cl::init(false));
136
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000137static cl::opt<bool> AssumeNoAlias(
138 "noalias",
139 cl::desc("If set, it assumes that loads and stores do not alias"),
140 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000141
142static cl::opt<unsigned>
143 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000144
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000145static cl::opt<unsigned>
146 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
147
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000148static cl::opt<bool>
149 PrintInstructionTables("instruction-tables",
150 cl::desc("Print instruction tables"),
151 cl::init(false));
152
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000153static cl::opt<bool>
154 PrintInstructionInfoView("instruction-info",
155 cl::desc("Print the instruction info view"),
156 cl::init(true));
157
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000158namespace {
159
160const Target *getTarget(const char *ProgName) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000161 TripleName = Triple::normalize(TripleName);
162 if (TripleName.empty())
163 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
164 Triple TheTriple(TripleName);
165
166 // Get the target specific parser.
167 std::string Error;
168 const Target *TheTarget =
169 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
170 if (!TheTarget) {
171 errs() << ProgName << ": " << Error;
172 return nullptr;
173 }
174
175 // Return the found target.
176 return TheTarget;
177}
178
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000179// A comment consumer that parses strings.
180// The only valid tokens are strings.
181class MCACommentConsumer : public AsmCommentConsumer {
182public:
183 mca::CodeRegions &Regions;
184
185 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
186 void HandleComment(SMLoc Loc, StringRef CommentText) override {
187 // Skip empty comments.
188 StringRef Comment(CommentText);
189 if (Comment.empty())
190 return;
191
192 // Skip spaces and tabs
193 unsigned Position = Comment.find_first_not_of(" \t");
194 if (Position >= Comment.size())
195 // we reached the end of the comment. Bail out.
196 return;
197
198 Comment = Comment.drop_front(Position);
199 if (Comment.consume_front("LLVM-MCA-END")) {
200 Regions.endRegion(Loc);
201 return;
202 }
203
204 // Now try to parse string LLVM-MCA-BEGIN
205 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
206 return;
207
208 // Skip spaces and tabs
209 Position = Comment.find_first_not_of(" \t");
210 if (Position < Comment.size())
Fangrui Songbb082572018-04-09 17:06:57 +0000211 Comment = Comment.drop_front(Position);
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000212 // Use the rest of the string as a descriptor for this code snippet.
213 Regions.beginRegion(Comment, Loc);
214 }
215};
216
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000217int AssembleInput(const char *ProgName, MCAsmParser &Parser,
218 const Target *TheTarget, MCSubtargetInfo &STI,
219 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000220 std::unique_ptr<MCTargetAsmParser> TAP(
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000221 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000222
223 if (!TAP) {
224 errs() << ProgName
225 << ": error: this target does not support assembly parsing.\n";
226 return 1;
227 }
228
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000229 Parser.setTargetParser(*TAP);
230 return Parser.Run(false);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000231}
232
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000233ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000234 if (OutputFilename == "")
235 OutputFilename = "-";
236 std::error_code EC;
237 auto Out =
238 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
239 if (!EC)
240 return std::move(Out);
241 return EC;
242}
243
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000244class MCStreamerWrapper final : public MCStreamer {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000245 mca::CodeRegions &Regions;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000246
247public:
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000248 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
249 : MCStreamer(Context), Regions(R) {}
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000250
251 // We only want to intercept the emission of new instructions.
252 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
253 bool /* unused */) override {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000254 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000255 }
256
257 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
258 return true;
259 }
260
261 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
262 unsigned ByteAlignment) override {}
263 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
264 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
265 void EmitGPRel32Value(const MCExpr *Value) override {}
266 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
267 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
268 void EmitCOFFSymbolType(int Type) override {}
269 void EndCOFFSymbolDef() override {}
270
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000271 const std::vector<std::unique_ptr<const MCInst>> &
272 GetInstructionSequence(unsigned Index) const {
273 return Regions.getInstructionSequence(Index);
274 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000275};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000276} // end of anonymous namespace
277
278int main(int argc, char **argv) {
279 sys::PrintStackTraceOnErrorSignal(argv[0]);
280 PrettyStackTraceProgram X(argc, argv);
281 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
282
283 // Initialize targets and assembly parsers.
284 llvm::InitializeAllTargetInfos();
285 llvm::InitializeAllTargetMCs();
286 llvm::InitializeAllAsmParsers();
287
288 // Enable printing of available targets when flag --version is specified.
289 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
290
291 // Parse flags and initialize target options.
292 cl::ParseCommandLineOptions(argc, argv,
293 "llvm machine code performance analyzer.\n");
294 MCTargetOptions MCOptions;
295 MCOptions.PreserveAsmComments = false;
296
297 // Get the target from the triple. If a triple is not specified, then select
298 // the default triple for the host. If the triple doesn't correspond to any
299 // registered target, then exit with an error message.
300 const char *ProgName = argv[0];
301 const Target *TheTarget = getTarget(ProgName);
302 if (!TheTarget)
303 return 1;
304
305 // GetTarget() may replaced TripleName with a default triple.
306 // For safety, reconstruct the Triple object.
307 Triple TheTriple(TripleName);
308
309 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
310 MemoryBuffer::getFileOrSTDIN(InputFilename);
311 if (std::error_code EC = BufferPtr.getError()) {
312 errs() << InputFilename << ": " << EC.message() << '\n';
313 return 1;
314 }
315
316 SourceMgr SrcMgr;
317
318 // Tell SrcMgr about this buffer, which is what the parser will pick up.
319 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
320
321 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
322 assert(MRI && "Unable to create target register info!");
323
324 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
325 assert(MAI && "Unable to create target asm info!");
326
327 MCObjectFileInfo MOFI;
328 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
329 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
330
331 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000332
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000333 mca::CodeRegions Regions(SrcMgr);
334 MCStreamerWrapper Str(Ctx, Regions);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000335
336 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
337 std::unique_ptr<MCSubtargetInfo> STI(
338 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
339 if (!STI->isCPUStringValid(MCPU))
340 return 1;
341
342 if (!STI->getSchedModel().isOutOfOrder()) {
343 errs() << "error: please specify an out-of-order cpu. '" << MCPU
344 << "' is an in-order cpu.\n";
345 return 1;
346 }
347
348 if (!STI->getSchedModel().hasInstrSchedModel()) {
349 errs()
350 << "error: unable to find instruction-level scheduling information for"
351 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
352 << "'.\n";
353
354 if (STI->getSchedModel().InstrItineraries)
355 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
356 << "instruction itineraries are currently unsupported.\n";
357 return 1;
358 }
359
360 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
361 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
362 if (!IP) {
363 errs() << "error: unable to create instruction printer for target triple '"
364 << TheTriple.normalize() << "' with assembly variant "
365 << OutputAsmVariant << ".\n";
366 return 1;
367 }
368
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000369 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000370 MCAsmLexer &Lexer = P->getLexer();
371 MCACommentConsumer CC(Regions);
372 Lexer.setCommentConsumer(&CC);
373
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000374 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
375 return 1;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000376
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000377 if (Regions.empty()) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000378 errs() << "error: no assembly instructions found.\n";
379 return 1;
380 }
381
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000382 // Now initialize the output file.
383 auto OF = getOutputStream();
384 if (std::error_code EC = OF.getError()) {
385 errs() << EC.message() << '\n';
386 return 1;
387 }
388
389 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
390
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000391 const MCSchedModel &SM = STI->getSchedModel();
392
393 unsigned Width = SM.IssueWidth;
394 if (DispatchWidth)
395 Width = DispatchWidth;
396
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000397 // Create an instruction builder.
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000398 mca::InstrBuilder IB(*STI, *MCII);
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000399
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000400 // Number each region in the sequence.
401 unsigned RegionIdx = 0;
402 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
403 // Skip empty code regions.
404 if (Region->empty())
405 continue;
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000406
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000407 // Don't print the header of this region if it is the default region, and
408 // it doesn't have an end location.
409 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
410 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
411 StringRef Desc = Region->getDescription();
412 if (!Desc.empty())
413 TOF->os() << " - " << Desc;
414 TOF->os() << "\n\n";
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000415 }
416
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000417 mca::SourceMgr S(Region->getInstructions(),
418 PrintInstructionTables ? 1 : Iterations);
419
420 if (PrintInstructionTables) {
421 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
422
423 if (PrintInstructionInfoView) {
424 IT.addView(
425 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
426 }
427
428 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
429 IT.run();
430 IT.printReport(TOF->os());
431 continue;
432 }
433
434 mca::Backend B(*STI, *MRI, IB, S, Width, RegisterFileSize, LoadQueueSize,
435 StoreQueueSize, AssumeNoAlias);
436 mca::BackendPrinter Printer(B);
437
438 Printer.addView(llvm::make_unique<mca::SummaryView>(S, Width));
439 if (PrintInstructionInfoView)
440 Printer.addView(
441 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
442
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000443 if (PrintDispatchStats)
Andrea Di Biagio074ff7c2018-04-11 12:31:44 +0000444 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000445
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000446 if (PrintSchedulerStats)
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000447 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
448
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000449 if (PrintRetireStats)
450 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000451
452 if (PrintRegisterFileStats)
453 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
454
455 if (PrintResourcePressureView)
456 Printer.addView(
457 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
458
459 if (PrintTimelineView) {
460 Printer.addView(llvm::make_unique<mca::TimelineView>(
461 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
462 }
463
464 B.run();
465 Printer.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000466 }
467
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000468 TOF->keep();
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000469 return 0;
470}