blob: efd0d1957fd47a47cbd2dbcd69e427fc2084ba47 [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 Biagiodf5d9482018-03-23 19:40:04 +000026#include "InstructionInfoView.h"
Andrea Di Biagiod1569292018-03-26 12:04:53 +000027#include "InstructionTables.h"
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000028#include "RegisterFileStatistics.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000029#include "ResourcePressureView.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000030#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000031#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000032#include "llvm/MC/MCAsmInfo.h"
33#include "llvm/MC/MCContext.h"
34#include "llvm/MC/MCObjectFileInfo.h"
35#include "llvm/MC/MCParser/MCTargetAsmParser.h"
36#include "llvm/MC/MCRegisterInfo.h"
37#include "llvm/MC/MCStreamer.h"
38#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000039#include "llvm/Support/ErrorOr.h"
40#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000041#include "llvm/Support/MemoryBuffer.h"
42#include "llvm/Support/PrettyStackTrace.h"
43#include "llvm/Support/Signals.h"
44#include "llvm/Support/SourceMgr.h"
45#include "llvm/Support/TargetRegistry.h"
46#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000047#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000048
49using namespace llvm;
50
51static cl::opt<std::string>
52 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
53
54static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
55 cl::init("-"),
56 cl::value_desc("filename"));
57
58static cl::opt<std::string>
59 ArchName("march", cl::desc("Target arch to assemble for, "
60 "see -version for available targets"));
61
62static cl::opt<std::string>
63 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000064 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000065
66static cl::opt<std::string>
67 MCPU("mcpu",
68 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
69 cl::value_desc("cpu-name"), cl::init("generic"));
70
71static cl::opt<unsigned>
72 OutputAsmVariant("output-asm-variant",
73 cl::desc("Syntax variant to use for output printing"));
74
75static cl::opt<unsigned> Iterations("iterations",
76 cl::desc("Number of iterations to run"),
77 cl::init(0));
78
79static cl::opt<unsigned> DispatchWidth(
80 "dispatch",
81 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
82 cl::init(0));
83
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000084static cl::opt<unsigned>
85 RegisterFileSize("register-file-size",
86 cl::desc("Maximum number of temporary registers which can "
87 "be used for register mappings"),
88 cl::init(0));
89
Andrea Di Biagio29538c62018-03-23 11:33:09 +000090static cl::opt<bool>
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +000091 PrintRegisterFileStats("register-file-stats",
92 cl::desc("Print register file statistics"),
93 cl::init(false));
94
95static cl::opt<bool>
Andrea Di Biagio29538c62018-03-23 11:33:09 +000096 PrintResourcePressureView("resource-pressure",
97 cl::desc("Print the resource pressure view"),
98 cl::init(true));
99
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000100static cl::opt<bool> PrintTimelineView("timeline",
101 cl::desc("Print the timeline view"),
102 cl::init(false));
103
104static cl::opt<unsigned> TimelineMaxIterations(
105 "timeline-max-iterations",
106 cl::desc("Maximum number of iterations to print in timeline view"),
107 cl::init(0));
108
109static cl::opt<unsigned> TimelineMaxCycles(
110 "timeline-max-cycles",
111 cl::desc(
112 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
113 cl::init(80));
114
115static cl::opt<bool> PrintModeVerbose("verbose",
116 cl::desc("Enable verbose output"),
117 cl::init(false));
118
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000119static cl::opt<bool> AssumeNoAlias(
120 "noalias",
121 cl::desc("If set, it assumes that loads and stores do not alias"),
122 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000123
124static cl::opt<unsigned>
125 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000126
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000127static cl::opt<unsigned>
128 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
129
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000130static cl::opt<bool>
131 PrintInstructionTables("instruction-tables",
132 cl::desc("Print instruction tables"),
133 cl::init(false));
134
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000135static cl::opt<bool>
136 PrintInstructionInfoView("instruction-info",
137 cl::desc("Print the instruction info view"),
138 cl::init(true));
139
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000140static const Target *getTarget(const char *ProgName) {
141 TripleName = Triple::normalize(TripleName);
142 if (TripleName.empty())
143 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
144 Triple TheTriple(TripleName);
145
146 // Get the target specific parser.
147 std::string Error;
148 const Target *TheTarget =
149 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
150 if (!TheTarget) {
151 errs() << ProgName << ": " << Error;
152 return nullptr;
153 }
154
155 // Return the found target.
156 return TheTarget;
157}
158
159static int AssembleInput(const char *ProgName, const Target *TheTarget,
160 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
161 MCAsmInfo &MAI, MCSubtargetInfo &STI,
162 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
163 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
164 std::unique_ptr<MCTargetAsmParser> TAP(
165 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
166
167 if (!TAP) {
168 errs() << ProgName
169 << ": error: this target does not support assembly parsing.\n";
170 return 1;
171 }
172
173 Parser->setTargetParser(*TAP);
174 return Parser->Run(false);
175}
176
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000177static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
178 if (OutputFilename == "")
179 OutputFilename = "-";
180 std::error_code EC;
181 auto Out =
182 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
183 if (!EC)
184 return std::move(Out);
185 return EC;
186}
187
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000188namespace {
189
190class MCStreamerWrapper final : public MCStreamer {
191 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
192 InstVec &Insts;
193
194public:
195 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
196 : MCStreamer(Context), Insts(Vec) {}
197
198 // We only want to intercept the emission of new instructions.
199 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
200 bool /* unused */) override {
201 Insts.emplace_back(new MCInst(Inst));
202 }
203
204 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
205 return true;
206 }
207
208 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
209 unsigned ByteAlignment) override {}
210 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
211 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
212 void EmitGPRel32Value(const MCExpr *Value) override {}
213 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
214 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
215 void EmitCOFFSymbolType(int Type) override {}
216 void EndCOFFSymbolDef() override {}
217
218 const InstVec &GetInstructionSequence() const { return Insts; }
219};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000220} // end of anonymous namespace
221
222int main(int argc, char **argv) {
223 sys::PrintStackTraceOnErrorSignal(argv[0]);
224 PrettyStackTraceProgram X(argc, argv);
225 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
226
227 // Initialize targets and assembly parsers.
228 llvm::InitializeAllTargetInfos();
229 llvm::InitializeAllTargetMCs();
230 llvm::InitializeAllAsmParsers();
231
232 // Enable printing of available targets when flag --version is specified.
233 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
234
235 // Parse flags and initialize target options.
236 cl::ParseCommandLineOptions(argc, argv,
237 "llvm machine code performance analyzer.\n");
238 MCTargetOptions MCOptions;
239 MCOptions.PreserveAsmComments = false;
240
241 // Get the target from the triple. If a triple is not specified, then select
242 // the default triple for the host. If the triple doesn't correspond to any
243 // registered target, then exit with an error message.
244 const char *ProgName = argv[0];
245 const Target *TheTarget = getTarget(ProgName);
246 if (!TheTarget)
247 return 1;
248
249 // GetTarget() may replaced TripleName with a default triple.
250 // For safety, reconstruct the Triple object.
251 Triple TheTriple(TripleName);
252
253 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
254 MemoryBuffer::getFileOrSTDIN(InputFilename);
255 if (std::error_code EC = BufferPtr.getError()) {
256 errs() << InputFilename << ": " << EC.message() << '\n';
257 return 1;
258 }
259
260 SourceMgr SrcMgr;
261
262 // Tell SrcMgr about this buffer, which is what the parser will pick up.
263 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
264
265 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
266 assert(MRI && "Unable to create target register info!");
267
268 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
269 assert(MAI && "Unable to create target asm info!");
270
271 MCObjectFileInfo MOFI;
272 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
273 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
274
275 std::unique_ptr<buffer_ostream> BOS;
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000276
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000277 std::unique_ptr<mca::SourceMgr> S = llvm::make_unique<mca::SourceMgr>(
278 PrintInstructionTables ? 1 : Iterations);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000279 MCStreamerWrapper Str(Ctx, S->getSequence());
280
281 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
282 std::unique_ptr<MCSubtargetInfo> STI(
283 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
284 if (!STI->isCPUStringValid(MCPU))
285 return 1;
286
287 if (!STI->getSchedModel().isOutOfOrder()) {
288 errs() << "error: please specify an out-of-order cpu. '" << MCPU
289 << "' is an in-order cpu.\n";
290 return 1;
291 }
292
293 if (!STI->getSchedModel().hasInstrSchedModel()) {
294 errs()
295 << "error: unable to find instruction-level scheduling information for"
296 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
297 << "'.\n";
298
299 if (STI->getSchedModel().InstrItineraries)
300 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
301 << "instruction itineraries are currently unsupported.\n";
302 return 1;
303 }
304
305 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
306 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
307 if (!IP) {
308 errs() << "error: unable to create instruction printer for target triple '"
309 << TheTriple.normalize() << "' with assembly variant "
310 << OutputAsmVariant << ".\n";
311 return 1;
312 }
313
314 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
315 *MCII, MCOptions);
316 if (Res)
317 return Res;
318
319 if (S->isEmpty()) {
320 errs() << "error: no assembly instructions found.\n";
321 return 1;
322 }
323
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000324 // Now initialize the output file.
325 auto OF = getOutputStream();
326 if (std::error_code EC = OF.getError()) {
327 errs() << EC.message() << '\n';
328 return 1;
329 }
330
331 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
332
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000333 const MCSchedModel &SM = STI->getSchedModel();
334
335 unsigned Width = SM.IssueWidth;
336 if (DispatchWidth)
337 Width = DispatchWidth;
338
Andrea Di Biagiob5088da2018-03-23 11:50:43 +0000339 // Create an instruction builder.
340 std::unique_ptr<mca::InstrBuilder> IB =
341 llvm::make_unique<mca::InstrBuilder>(*STI, *MCII);
342
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000343 if (PrintInstructionTables) {
344 mca::InstructionTables IT(STI->getSchedModel(), *IB, *S);
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000345
346 if (PrintInstructionInfoView) {
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000347 IT.addView(
348 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, *S, *IP));
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000349 }
350
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000351 IT.addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000352 IT.run();
Andrea Di Biagio5ffd2c32018-03-26 14:25:52 +0000353 IT.printReport(TOF->os());
Andrea Di Biagiod1569292018-03-26 12:04:53 +0000354 TOF->keep();
355 return 0;
356 }
357
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000358 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagio020ba252018-04-05 11:36:50 +0000359 *STI, *MRI, *IB, *S, Width, RegisterFileSize, LoadQueueSize,
360 StoreQueueSize, AssumeNoAlias);
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000361
362 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000363 llvm::make_unique<mca::BackendPrinter>(*B);
364
Andrea Di Biagiodf5d9482018-03-23 19:40:04 +0000365 Printer->addView(llvm::make_unique<mca::SummaryView>(*S, Width));
366
Andrea Di Biagioff9c1092018-03-26 13:44:54 +0000367 if (PrintInstructionInfoView)
368 Printer->addView(
369 llvm::make_unique<mca::InstructionInfoView>(*STI, *MCII, *S, *IP));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000370
Andrea Di Biagio35622482018-03-22 10:19:20 +0000371 if (PrintModeVerbose)
372 Printer->addView(llvm::make_unique<mca::BackendStatistics>(*STI));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000373
Andrea Di Biagio8dabf4f2018-04-03 16:46:23 +0000374 if (PrintRegisterFileStats)
375 Printer->addView(llvm::make_unique<mca::RegisterFileStatistics>(*STI));
376
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000377 if (PrintResourcePressureView)
Andrea Di Biagio94fafdf2018-03-24 16:05:36 +0000378 Printer->addView(
379 llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000380
381 if (PrintTimelineView) {
Andrea Di Biagio35622482018-03-22 10:19:20 +0000382 Printer->addView(llvm::make_unique<mca::TimelineView>(
383 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000384 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000385
386 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000387 Printer->printReport(TOF->os());
388 TOF->keep();
389
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000390 return 0;
391}