blob: ab9c137e4df27142487f87cf3a583ad16583828b [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"
25#include "BackendStatistics.h"
Andrea Di Biagioc6590122018-04-09 16:39:52 +000026#include "CodeRegion.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 Biagio0cc66c72018-03-09 13:52:03 +000031#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000032#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000033#include "llvm/MC/MCAsmInfo.h"
34#include "llvm/MC/MCContext.h"
35#include "llvm/MC/MCObjectFileInfo.h"
36#include "llvm/MC/MCParser/MCTargetAsmParser.h"
37#include "llvm/MC/MCRegisterInfo.h"
38#include "llvm/MC/MCStreamer.h"
39#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000040#include "llvm/Support/ErrorOr.h"
41#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000042#include "llvm/Support/MemoryBuffer.h"
43#include "llvm/Support/PrettyStackTrace.h"
44#include "llvm/Support/Signals.h"
45#include "llvm/Support/SourceMgr.h"
46#include "llvm/Support/TargetRegistry.h"
47#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000048#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000049
50using namespace llvm;
51
52static cl::opt<std::string>
53 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
54
55static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
56 cl::init("-"),
57 cl::value_desc("filename"));
58
59static cl::opt<std::string>
60 ArchName("march", cl::desc("Target arch to assemble for, "
61 "see -version for available targets"));
62
63static cl::opt<std::string>
64 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000065 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000066
67static cl::opt<std::string>
68 MCPU("mcpu",
69 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
70 cl::value_desc("cpu-name"), cl::init("generic"));
71
72static cl::opt<unsigned>
73 OutputAsmVariant("output-asm-variant",
74 cl::desc("Syntax variant to use for output printing"));
75
76static cl::opt<unsigned> Iterations("iterations",
77 cl::desc("Number of iterations to run"),
78 cl::init(0));
79
80static cl::opt<unsigned> DispatchWidth(
81 "dispatch",
82 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
83 cl::init(0));
84
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000085static cl::opt<unsigned>
86 RegisterFileSize("register-file-size",
87 cl::desc("Maximum number of temporary registers which can "
88 "be used for register mappings"),
89 cl::init(0));
90
Andrea Di Biagio29538c62018-03-23 11:33:09 +000091static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000092 PrintRegisterFileStats("register-file-stats",
93 cl::desc("Print register file statistics"),
94 cl::init(false));
95
96static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +000097 PrintResourcePressureView("resource-pressure",
98 cl::desc("Print the resource pressure view"),
99 cl::init(true));
100
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000101static cl::opt<bool> PrintTimelineView("timeline",
102 cl::desc("Print the timeline view"),
103 cl::init(false));
104
105static cl::opt<unsigned> TimelineMaxIterations(
106 "timeline-max-iterations",
107 cl::desc("Maximum number of iterations to print in timeline view"),
108 cl::init(0));
109
110static cl::opt<unsigned> TimelineMaxCycles(
111 "timeline-max-cycles",
112 cl::desc(
113 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
114 cl::init(80));
115
116static cl::opt<bool> PrintModeVerbose("verbose",
117 cl::desc("Enable verbose output"),
118 cl::init(false));
119
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000120static cl::opt<bool> AssumeNoAlias(
121 "noalias",
122 cl::desc("If set, it assumes that loads and stores do not alias"),
123 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000124
125static cl::opt<unsigned>
126 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000127
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000128static cl::opt<unsigned>
129 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
130
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000131static cl::opt<bool>
132 PrintInstructionTables("instruction-tables",
133 cl::desc("Print instruction tables"),
134 cl::init(false));
135
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000136static cl::opt<bool>
137 PrintInstructionInfoView("instruction-info",
138 cl::desc("Print the instruction info view"),
139 cl::init(true));
140
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000141namespace {
142
143const Target *getTarget(const char *ProgName) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000144 TripleName = Triple::normalize(TripleName);
145 if (TripleName.empty())
146 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
147 Triple TheTriple(TripleName);
148
149 // Get the target specific parser.
150 std::string Error;
151 const Target *TheTarget =
152 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
153 if (!TheTarget) {
154 errs() << ProgName << ": " << Error;
155 return nullptr;
156 }
157
158 // Return the found target.
159 return TheTarget;
160}
161
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000162// A comment consumer that parses strings.
163// The only valid tokens are strings.
164class MCACommentConsumer : public AsmCommentConsumer {
165public:
166 mca::CodeRegions &Regions;
167
168 MCACommentConsumer(mca::CodeRegions &R) : Regions(R) {}
169 void HandleComment(SMLoc Loc, StringRef CommentText) override {
170 // Skip empty comments.
171 StringRef Comment(CommentText);
172 if (Comment.empty())
173 return;
174
175 // Skip spaces and tabs
176 unsigned Position = Comment.find_first_not_of(" \t");
177 if (Position >= Comment.size())
178 // we reached the end of the comment. Bail out.
179 return;
180
181 Comment = Comment.drop_front(Position);
182 if (Comment.consume_front("LLVM-MCA-END")) {
183 Regions.endRegion(Loc);
184 return;
185 }
186
187 // Now try to parse string LLVM-MCA-BEGIN
188 if (!Comment.consume_front("LLVM-MCA-BEGIN"))
189 return;
190
191 // Skip spaces and tabs
192 Position = Comment.find_first_not_of(" \t");
193 if (Position < Comment.size())
Fangrui Songbb082572018-04-09 17:06:57 +0000194 Comment = Comment.drop_front(Position);
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000195 // Use the rest of the string as a descriptor for this code snippet.
196 Regions.beginRegion(Comment, Loc);
197 }
198};
199
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000200int AssembleInput(const char *ProgName, MCAsmParser &Parser,
201 const Target *TheTarget, MCSubtargetInfo &STI,
202 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000203 std::unique_ptr<MCTargetAsmParser> TAP(
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000204 TheTarget->createMCAsmParser(STI, Parser, MCII, MCOptions));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000205
206 if (!TAP) {
207 errs() << ProgName
208 << ": error: this target does not support assembly parsing.\n";
209 return 1;
210 }
211
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000212 Parser.setTargetParser(*TAP);
213 return Parser.Run(false);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000214}
215
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000216ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000217 if (OutputFilename == "")
218 OutputFilename = "-";
219 std::error_code EC;
220 auto Out =
221 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
222 if (!EC)
223 return std::move(Out);
224 return EC;
225}
226
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000227class MCStreamerWrapper final : public MCStreamer {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000228 mca::CodeRegions &Regions;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000229
230public:
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000231 MCStreamerWrapper(MCContext &Context, mca::CodeRegions &R)
232 : MCStreamer(Context), Regions(R) {}
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000233
234 // We only want to intercept the emission of new instructions.
235 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
236 bool /* unused */) override {
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000237 Regions.addInstruction(llvm::make_unique<const MCInst>(Inst));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000238 }
239
240 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
241 return true;
242 }
243
244 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
245 unsigned ByteAlignment) override {}
246 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
247 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
248 void EmitGPRel32Value(const MCExpr *Value) override {}
249 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
250 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
251 void EmitCOFFSymbolType(int Type) override {}
252 void EndCOFFSymbolDef() override {}
253
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000254 const std::vector<std::unique_ptr<const MCInst>> &
255 GetInstructionSequence(unsigned Index) const {
256 return Regions.getInstructionSequence(Index);
257 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000258};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000259} // end of anonymous namespace
260
261int main(int argc, char **argv) {
262 sys::PrintStackTraceOnErrorSignal(argv[0]);
263 PrettyStackTraceProgram X(argc, argv);
264 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
265
266 // Initialize targets and assembly parsers.
267 llvm::InitializeAllTargetInfos();
268 llvm::InitializeAllTargetMCs();
269 llvm::InitializeAllAsmParsers();
270
271 // Enable printing of available targets when flag --version is specified.
272 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
273
274 // Parse flags and initialize target options.
275 cl::ParseCommandLineOptions(argc, argv,
276 "llvm machine code performance analyzer.\n");
277 MCTargetOptions MCOptions;
278 MCOptions.PreserveAsmComments = false;
279
280 // Get the target from the triple. If a triple is not specified, then select
281 // the default triple for the host. If the triple doesn't correspond to any
282 // registered target, then exit with an error message.
283 const char *ProgName = argv[0];
284 const Target *TheTarget = getTarget(ProgName);
285 if (!TheTarget)
286 return 1;
287
288 // GetTarget() may replaced TripleName with a default triple.
289 // For safety, reconstruct the Triple object.
290 Triple TheTriple(TripleName);
291
292 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
293 MemoryBuffer::getFileOrSTDIN(InputFilename);
294 if (std::error_code EC = BufferPtr.getError()) {
295 errs() << InputFilename << ": " << EC.message() << '\n';
296 return 1;
297 }
298
299 SourceMgr SrcMgr;
300
301 // Tell SrcMgr about this buffer, which is what the parser will pick up.
302 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
303
304 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
305 assert(MRI && "Unable to create target register info!");
306
307 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
308 assert(MAI && "Unable to create target asm info!");
309
310 MCObjectFileInfo MOFI;
311 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
312 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
313
314 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000315
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000316 mca::CodeRegions Regions(SrcMgr);
317 MCStreamerWrapper Str(Ctx, Regions);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000318
319 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
320 std::unique_ptr<MCSubtargetInfo> STI(
321 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
322 if (!STI->isCPUStringValid(MCPU))
323 return 1;
324
325 if (!STI->getSchedModel().isOutOfOrder()) {
326 errs() << "error: please specify an out-of-order cpu. '" << MCPU
327 << "' is an in-order cpu.\n";
328 return 1;
329 }
330
331 if (!STI->getSchedModel().hasInstrSchedModel()) {
332 errs()
333 << "error: unable to find instruction-level scheduling information for"
334 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
335 << "'.\n";
336
337 if (STI->getSchedModel().InstrItineraries)
338 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
339 << "instruction itineraries are currently unsupported.\n";
340 return 1;
341 }
342
343 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
344 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
345 if (!IP) {
346 errs() << "error: unable to create instruction printer for target triple '"
347 << TheTriple.normalize() << "' with assembly variant "
348 << OutputAsmVariant << ".\n";
349 return 1;
350 }
351
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000352 std::unique_ptr<MCAsmParser> P(createMCAsmParser(SrcMgr, Ctx, Str, *MAI));
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000353 MCAsmLexer &Lexer = P->getLexer();
354 MCACommentConsumer CC(Regions);
355 Lexer.setCommentConsumer(&CC);
356
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000357 if (AssembleInput(ProgName, *P, TheTarget, *STI, *MCII, MCOptions))
358 return 1;
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000359
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000360 if (Regions.empty()) {
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000361 errs() << "error: no assembly instructions found.\n";
362 return 1;
363 }
364
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000365 // Now initialize the output file.
366 auto OF = getOutputStream();
367 if (std::error_code EC = OF.getError()) {
368 errs() << EC.message() << '\n';
369 return 1;
370 }
371
372 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
373
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000374 const MCSchedModel &SM = STI->getSchedModel();
375
376 unsigned Width = SM.IssueWidth;
377 if (DispatchWidth)
378 Width = DispatchWidth;
379
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000380 // Create an instruction builder.
Andrea Di Biagio5c469442018-04-08 15:10:19 +0000381 mca::InstrBuilder IB(*STI, *MCII);
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000382
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000383 // Number each region in the sequence.
384 unsigned RegionIdx = 0;
385 for (const std::unique_ptr<mca::CodeRegion> &Region : Regions) {
386 // Skip empty code regions.
387 if (Region->empty())
388 continue;
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000389
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000390 // Don't print the header of this region if it is the default region, and
391 // it doesn't have an end location.
392 if (Region->startLoc().isValid() || Region->endLoc().isValid()) {
393 TOF->os() << "\n[" << RegionIdx++ << "] Code Region";
394 StringRef Desc = Region->getDescription();
395 if (!Desc.empty())
396 TOF->os() << " - " << Desc;
397 TOF->os() << "\n\n";
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000398 }
399
Andrea Di Biagioc6590122018-04-09 16:39:52 +0000400 mca::SourceMgr S(Region->getInstructions(),
401 PrintInstructionTables ? 1 : Iterations);
402
403 if (PrintInstructionTables) {
404 mca::InstructionTables IT(STI->getSchedModel(), IB, S);
405
406 if (PrintInstructionInfoView) {
407 IT.addView(
408 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
409 }
410
411 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
412 IT.run();
413 IT.printReport(TOF->os());
414 continue;
415 }
416
417 mca::Backend B(*STI, *MRI, IB, S, Width, RegisterFileSize, LoadQueueSize,
418 StoreQueueSize, AssumeNoAlias);
419 mca::BackendPrinter Printer(B);
420
421 Printer.addView(llvm::make_unique<mca::SummaryView>(S, Width));
422 if (PrintInstructionInfoView)
423 Printer.addView(
424 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, S, *IP));
425
426 if (PrintModeVerbose)
427 Printer.addView(llvm::make_unique<mca::BackendStatistics>(*STI));
428
429 if (PrintRegisterFileStats)
430 Printer.addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
431
432 if (PrintResourcePressureView)
433 Printer.addView(
434 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, S));
435
436 if (PrintTimelineView) {
437 Printer.addView(llvm::make_unique<mca::TimelineView>(
438 *STI, *IP, S, TimelineMaxIterations, TimelineMaxCycles));
439 }
440
441 B.run();
442 Printer.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000443 }
444
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000445 TOF->keep();
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000446 return 0;
447}