blob: a304d4778929c57e5942221c922ca21dfae4a0fa [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"
Rui Ueyama197194b2018-04-13 18:26:06 +000044#include "llvm/Support/InitLLVM.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000045#include "llvm/Support/MemoryBuffer.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000046#include "llvm/Support/SourceMgr.h"
47#include "llvm/Support/TargetRegistry.h"
48#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000049#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000050
51using namespace llvm;
52
53static cl::opt<std::string>
54 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
55
56static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
57 cl::init("-"),
58 cl::value_desc("filename"));
59
60static cl::opt<std::string>
61 ArchName("march", cl::desc("Target arch to assemble for, "
62 "see -version for available targets"));
63
64static cl::opt<std::string>
65 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000066 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000067
68static cl::opt<std::string>
69 MCPU("mcpu",
70 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
71 cl::value_desc("cpu-name"), cl::init("generic"));
72
73static cl::opt<unsigned>
74 OutputAsmVariant("output-asm-variant",
75 cl::desc("Syntax variant to use for output printing"));
76
77static cl::opt<unsigned> Iterations("iterations",
78 cl::desc("Number of iterations to run"),
79 cl::init(0));
80
81static cl::opt<unsigned> DispatchWidth(
82 "dispatch",
83 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
84 cl::init(0));
85
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000086static cl::opt<unsigned>
87 RegisterFileSize("register-file-size",
88 cl::desc("Maximum number of temporary registers which can "
89 "be used for register mappings"),
90 cl::init(0));
91
Andrea Di Biagio29538c62018-03-23 11:33:09 +000092static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000093 PrintRegisterFileStats("register-file-stats",
94 cl::desc("Print register file statistics"),
95 cl::init(false));
96
97static cl::opt<bool>
Andrea Di Biagio821f6502018-04-10 14:55:14 +000098 PrintDispatchStats("dispatch-stats",
99 cl::desc("Print dispatch statistics"),
100 cl::init(false));
101
102static cl::opt<bool>
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000103 PrintSchedulerStats("scheduler-stats",
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000104 cl::desc("Print scheduler statistics"),
105 cl::init(false));
106
107static cl::opt<bool>
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000108 PrintRetireStats("retire-stats",
109 cl::desc("Print retire control unit statistics"),
110 cl::init(false));
111
112static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000113 PrintResourcePressureView("resource-pressure",
114 cl::desc("Print the resource pressure view"),
115 cl::init(true));
116
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000117static cl::opt<bool> PrintTimelineView("timeline",
118 cl::desc("Print the timeline view"),
119 cl::init(false));
120
121static cl::opt<unsigned> TimelineMaxIterations(
122 "timeline-max-iterations",
123 cl::desc("Maximum number of iterations to print in timeline view"),
124 cl::init(0));
125
126static cl::opt<unsigned> TimelineMaxCycles(
127 "timeline-max-cycles",
128 cl::desc(
129 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
130 cl::init(80));
131
132static cl::opt<bool> PrintModeVerbose("verbose",
133 cl::desc("Enable verbose output"),
134 cl::init(false));
135
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000136static cl::opt<bool> AssumeNoAlias(
137 "noalias",
138 cl::desc("If set, it assumes that loads and stores do not alias"),
139 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000140
141static cl::opt<unsigned>
142 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000143
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000144static cl::opt<unsigned>
145 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
146
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000147static cl::opt<bool>
148 PrintInstructionTables("instruction-tables",
149 cl::desc("Print instruction tables"),
150 cl::init(false));
151
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000152static cl::opt<bool>
153 PrintInstructionInfoView("instruction-info",
154 cl::desc("Print the instruction info view"),
155 cl::init(true));
156
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000157namespace {
158
159const Target *getTarget(const char *ProgName) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000160 TripleName = Triple::normalize(TripleName);
161 if (TripleName.empty())
162 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
163 Triple TheTriple(TripleName);
164
165 // Get the target specific parser.
166 std::string Error;
167 const Target *TheTarget =
168 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
169 if (!TheTarget) {
170 errs() << ProgName << ": " << Error;
171 return nullptr;
172 }
173
174 // Return the found target.
175 return TheTarget;
176}
177
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000178// A comment consumer that parses strings.
179// The only valid tokens are strings.
180class MCACommentConsumer : public AsmCommentConsumer {
181public:
182 mca::CodeRegions &Regions;
183
184 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
185 void HandleComment(SMLoc Loc, StringRef CommentText) override {
186 // Skip empty comments.
187 StringRef Comment(CommentText);
188 if (Comment.empty())
189 return;
190
191 // Skip spaces and tabs
192 unsigned Position = Comment.find_first_not_of(" \t");
193 if (Position >= Comment.size())
194 // we reached the end of the comment. Bail out.
195 return;
196
197 Comment = Comment.drop_front(Position);
198 if (Comment.consume_front("LLVM-MCA-END")) {
199 Regions.endRegion(Loc);
200 return;
201 }
202
203 // Now try to parse string LLVM-MCA-BEGIN
204 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
205 return;
206
207 // Skip spaces and tabs
208 Position = Comment.find_first_not_of(" \t");
209 if (Position < Comment.size())
Fangrui Songbb082572018-04-09 17:06:57 +0000210 Comment = Comment.drop_front(Position);
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000211 // Use the rest of the string as a descriptor for this code snippet.
212 Regions.beginRegion(Comment, Loc);
213 }
214};
215
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000216int AssembleInput(const char *ProgName, MCAsmParser &Parser,
217 const Target *TheTarget, MCSubtargetInfo &STI,
218 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000219 std::unique_ptr<MCTargetAsmParser> TAP(
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000220 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000221
222 if (!TAP) {
223 errs() << ProgName
224 << ": error: this target does not support assembly parsing.\n";
225 return 1;
226 }
227
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000228 Parser.setTargetParser(*TAP);
229 return Parser.Run(false);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000230}
231
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000232ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000233 if (OutputFilename == "")
234 OutputFilename = "-";
235 std::error_code EC;
236 auto Out =
237 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
238 if (!EC)
239 return std::move(Out);
240 return EC;
241}
242
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000243class MCStreamerWrapper final : public MCStreamer {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000244 mca::CodeRegions &Regions;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000245
246public:
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000247 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
248 : MCStreamer(Context), Regions(R) {}
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000249
250 // We only want to intercept the emission of new instructions.
251 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
252 bool /* unused */) override {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000253 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000254 }
255
256 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
257 return true;
258 }
259
260 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
261 unsigned ByteAlignment) override {}
262 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
263 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
264 void EmitGPRel32Value(const MCExpr *Value) override {}
265 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
266 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
267 void EmitCOFFSymbolType(int Type) override {}
268 void EndCOFFSymbolDef() override {}
269
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000270 const std::vector<std::unique_ptr<const MCInst>> &
271 GetInstructionSequence(unsigned Index) const {
272 return Regions.getInstructionSequence(Index);
273 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000274};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000275} // end of anonymous namespace
276
277int main(int argc, char **argv) {
Rui Ueyama197194b2018-04-13 18:26:06 +0000278 InitLLVM X(argc, argv);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000279
280 // Initialize targets and assembly parsers.
281 llvm::InitializeAllTargetInfos();
282 llvm::InitializeAllTargetMCs();
283 llvm::InitializeAllAsmParsers();
284
285 // Enable printing of available targets when flag --version is specified.
286 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
287
288 // Parse flags and initialize target options.
289 cl::ParseCommandLineOptions(argc, argv,
290 "llvm machine code performance analyzer.\n");
291 MCTargetOptions MCOptions;
292 MCOptions.PreserveAsmComments = false;
293
294 // Get the target from the triple. If a triple is not specified, then select
295 // the default triple for the host. If the triple doesn't correspond to any
296 // registered target, then exit with an error message.
297 const char *ProgName = argv[0];
298 const Target *TheTarget = getTarget(ProgName);
299 if (!TheTarget)
300 return 1;
301
302 // GetTarget() may replaced TripleName with a default triple.
303 // For safety, reconstruct the Triple object.
304 Triple TheTriple(TripleName);
305
306 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
307 MemoryBuffer::getFileOrSTDIN(InputFilename);
308 if (std::error_code EC = BufferPtr.getError()) {
309 errs() << InputFilename << ": " << EC.message() << '\n';
310 return 1;
311 }
312
313 SourceMgr SrcMgr;
314
315 // Tell SrcMgr about this buffer, which is what the parser will pick up.
316 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
317
318 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
319 assert(MRI && "Unable to create target register info!");
320
321 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
322 assert(MAI && "Unable to create target asm info!");
323
324 MCObjectFileInfo MOFI;
325 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
326 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
327
328 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000329
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000330 mca::CodeRegions Regions(SrcMgr);
331 MCStreamerWrapper Str(Ctx, Regions);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000332
333 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
334 std::unique_ptr<MCSubtargetInfo> STI(
335 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
336 if (!STI->isCPUStringValid(MCPU))
337 return 1;
338
339 if (!STI->getSchedModel().isOutOfOrder()) {
340 errs() << "error: please specify an out-of-order cpu. '" << MCPU
341 << "' is an in-order cpu.\n";
342 return 1;
343 }
344
345 if (!STI->getSchedModel().hasInstrSchedModel()) {
346 errs()
347 << "error: unable to find instruction-level scheduling information for"
348 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
349 << "'.\n";
350
351 if (STI->getSchedModel().InstrItineraries)
352 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
353 << "instruction itineraries are currently unsupported.\n";
354 return 1;
355 }
356
357 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
358 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
359 if (!IP) {
360 errs() << "error: unable to create instruction printer for target triple '"
361 << TheTriple.normalize() << "' with assembly variant "
362 << OutputAsmVariant << ".\n";
363 return 1;
364 }
365
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000366 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000367 MCAsmLexer &Lexer = P->getLexer();
368 MCACommentConsumer CC(Regions);
369 Lexer.setCommentConsumer(&CC);
370
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000371 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
372 return 1;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000373
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000374 if (Regions.empty()) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000375 errs() << "error: no assembly instructions found.\n";
376 return 1;
377 }
378
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000379 // Now initialize the output file.
380 auto OF = getOutputStream();
381 if (std::error_code EC = OF.getError()) {
382 errs() << EC.message() << '\n';
383 return 1;
384 }
385
386 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
387
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000388 const MCSchedModel &SM = STI->getSchedModel();
389
390 unsigned Width = SM.IssueWidth;
391 if (DispatchWidth)
392 Width = DispatchWidth;
393
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000394 // Create an instruction builder.
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000395 mca::InstrBuilder IB(*STI, *MCII);
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000396
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000397 // Number each region in the sequence.
398 unsigned RegionIdx = 0;
399 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
400 // Skip empty code regions.
401 if (Region->empty())
402 continue;
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000403
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000404 // Don't print the header of this region if it is the default region, and
405 // it doesn't have an end location.
406 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
407 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
408 StringRef Desc = Region->getDescription();
409 if (!Desc.empty())
410 TOF->os() << " - " << Desc;
411 TOF->os() << "\n\n";
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000412 }
413
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000414 mca::SourceMgr S(Region->getInstructions(),
415 PrintInstructionTables ? 1 : Iterations);
416
417 if (PrintInstructionTables) {
418 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
419
420 if (PrintInstructionInfoView) {
421 IT.addView(
422 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
423 }
424
425 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
426 IT.run();
427 IT.printReport(TOF->os());
428 continue;
429 }
430
431 mca::Backend B(*STI, *MRI, IB, S, Width, RegisterFileSize, LoadQueueSize,
432 StoreQueueSize, AssumeNoAlias);
433 mca::BackendPrinter Printer(B);
434
435 Printer.addView(llvm::make_unique<mca::SummaryView>(S, Width));
436 if (PrintInstructionInfoView)
437 Printer.addView(
438 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
439
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000440 if (PrintDispatchStats)
Andrea Di Biagio074ff7c2018-04-11 12:31:44 +0000441 Printer.addView(llvm::make_unique<mca::DispatchStatistics>());
Andrea Di Biagio821f6502018-04-10 14:55:14 +0000442
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000443 if (PrintSchedulerStats)
Andrea Di Biagio1cc29c02018-04-11 11:37:46 +0000444 Printer.addView(llvm::make_unique<mca::SchedulerStatistics>(*STI));
445
Andrea Di Biagiof41ad5c2018-04-11 12:12:53 +0000446 if (PrintRetireStats)
447 Printer.addView(llvm::make_unique<mca::RetireControlUnitStatistics>());
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000448
449 if (PrintRegisterFileStats)
450 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
451
452 if (PrintResourcePressureView)
453 Printer.addView(
454 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
455
456 if (PrintTimelineView) {
457 Printer.addView(llvm::make_unique<mca::TimelineView>(
458 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
459 }
460
461 B.run();
462 Printer.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000463 }
464
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000465 TOF->keep();
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000466 return 0;
467}