blob: 0ae9c8849bbba0258f1324925a316c6afd4a1052 [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"
26#include "ResourcePressureView.h"
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +000027#include "SummaryView.h"
Andrea Di Biagio53e6ade2018-03-09 12:50:42 +000028#include "TimelineView.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000029#include "llvm/MC/MCAsmInfo.h"
30#include "llvm/MC/MCContext.h"
31#include "llvm/MC/MCObjectFileInfo.h"
32#include "llvm/MC/MCParser/MCTargetAsmParser.h"
33#include "llvm/MC/MCRegisterInfo.h"
34#include "llvm/MC/MCStreamer.h"
35#include "llvm/Support/CommandLine.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000036#include "llvm/Support/ErrorOr.h"
37#include "llvm/Support/FileSystem.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000038#include "llvm/Support/MemoryBuffer.h"
39#include "llvm/Support/PrettyStackTrace.h"
40#include "llvm/Support/Signals.h"
41#include "llvm/Support/SourceMgr.h"
42#include "llvm/Support/TargetRegistry.h"
43#include "llvm/Support/TargetSelect.h"
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000044#include "llvm/Support/ToolOutputFile.h"
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000045
46using namespace llvm;
47
48static cl::opt<std::string>
49 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-"));
50
51static cl::opt<std::string> OutputFilename("o", cl::desc("Output filename"),
52 cl::init("-"),
53 cl::value_desc("filename"));
54
55static cl::opt<std::string>
56 ArchName("march", cl::desc("Target arch to assemble for, "
57 "see -version for available targets"));
58
59static cl::opt<std::string>
60 TripleName("mtriple", cl::desc("Target triple to assemble for, "
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +000061 "see -version for available targets"));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000062
63static cl::opt<std::string>
64 MCPU("mcpu",
65 cl::desc("Target a specific cpu type (-mcpu=help for details)"),
66 cl::value_desc("cpu-name"), cl::init("generic"));
67
68static cl::opt<unsigned>
69 OutputAsmVariant("output-asm-variant",
70 cl::desc("Syntax variant to use for output printing"));
71
72static cl::opt<unsigned> Iterations("iterations",
73 cl::desc("Number of iterations to run"),
74 cl::init(0));
75
76static cl::opt<unsigned> DispatchWidth(
77 "dispatch",
78 cl::desc("Dispatch Width. By default it is set equal to IssueWidth"),
79 cl::init(0));
80
81static cl::opt<unsigned> MaxRetirePerCycle(
82 "max-retire-per-cycle",
83 cl::desc("Maximum number of instructions that can be retired in one cycle"),
84 cl::init(0));
85
86static 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>
93 PrintResourcePressureView("resource-pressure",
94 cl::desc("Print the resource pressure view"),
95 cl::init(true));
96
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +000097static cl::opt<bool> PrintTimelineView("timeline",
98 cl::desc("Print the timeline view"),
99 cl::init(false));
100
101static cl::opt<unsigned> TimelineMaxIterations(
102 "timeline-max-iterations",
103 cl::desc("Maximum number of iterations to print in timeline view"),
104 cl::init(0));
105
106static cl::opt<unsigned> TimelineMaxCycles(
107 "timeline-max-cycles",
108 cl::desc(
109 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
110 cl::init(80));
111
112static cl::opt<bool> PrintModeVerbose("verbose",
113 cl::desc("Enable verbose output"),
114 cl::init(false));
115
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000116static cl::opt<bool> AssumeNoAlias(
117 "noalias",
118 cl::desc("If set, it assumes that loads and stores do not alias"),
119 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000120
121static cl::opt<unsigned>
122 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
123static cl::opt<unsigned>
124 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
125
126static const Target *getTarget(const char *ProgName) {
127 TripleName = Triple::normalize(TripleName);
128 if (TripleName.empty())
129 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
130 Triple TheTriple(TripleName);
131
132 // Get the target specific parser.
133 std::string Error;
134 const Target *TheTarget =
135 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
136 if (!TheTarget) {
137 errs() << ProgName << ": " << Error;
138 return nullptr;
139 }
140
141 // Return the found target.
142 return TheTarget;
143}
144
145static int AssembleInput(const char *ProgName, const Target *TheTarget,
146 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
147 MCAsmInfo &MAI, MCSubtargetInfo &STI,
148 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
149 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
150 std::unique_ptr<MCTargetAsmParser> TAP(
151 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
152
153 if (!TAP) {
154 errs() << ProgName
155 << ": error: this target does not support assembly parsing.\n";
156 return 1;
157 }
158
159 Parser->setTargetParser(*TAP);
160 return Parser->Run(false);
161}
162
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000163static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
164 if (OutputFilename == "")
165 OutputFilename = "-";
166 std::error_code EC;
167 auto Out =
168 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
169 if (!EC)
170 return std::move(Out);
171 return EC;
172}
173
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000174namespace {
175
176class MCStreamerWrapper final : public MCStreamer {
177 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
178 InstVec &Insts;
179
180public:
181 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
182 : MCStreamer(Context), Insts(Vec) {}
183
184 // We only want to intercept the emission of new instructions.
185 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
186 bool /* unused */) override {
187 Insts.emplace_back(new MCInst(Inst));
188 }
189
190 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
191 return true;
192 }
193
194 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
195 unsigned ByteAlignment) override {}
196 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
197 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
198 void EmitGPRel32Value(const MCExpr *Value) override {}
199 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
200 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
201 void EmitCOFFSymbolType(int Type) override {}
202 void EndCOFFSymbolDef() override {}
203
204 const InstVec &GetInstructionSequence() const { return Insts; }
205};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000206} // end of anonymous namespace
207
208int main(int argc, char **argv) {
209 sys::PrintStackTraceOnErrorSignal(argv[0]);
210 PrettyStackTraceProgram X(argc, argv);
211 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
212
213 // Initialize targets and assembly parsers.
214 llvm::InitializeAllTargetInfos();
215 llvm::InitializeAllTargetMCs();
216 llvm::InitializeAllAsmParsers();
217
218 // Enable printing of available targets when flag --version is specified.
219 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
220
221 // Parse flags and initialize target options.
222 cl::ParseCommandLineOptions(argc, argv,
223 "llvm machine code performance analyzer.\n");
224 MCTargetOptions MCOptions;
225 MCOptions.PreserveAsmComments = false;
226
227 // Get the target from the triple. If a triple is not specified, then select
228 // the default triple for the host. If the triple doesn't correspond to any
229 // registered target, then exit with an error message.
230 const char *ProgName = argv[0];
231 const Target *TheTarget = getTarget(ProgName);
232 if (!TheTarget)
233 return 1;
234
235 // GetTarget() may replaced TripleName with a default triple.
236 // For safety, reconstruct the Triple object.
237 Triple TheTriple(TripleName);
238
239 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
240 MemoryBuffer::getFileOrSTDIN(InputFilename);
241 if (std::error_code EC = BufferPtr.getError()) {
242 errs() << InputFilename << ": " << EC.message() << '\n';
243 return 1;
244 }
245
246 SourceMgr SrcMgr;
247
248 // Tell SrcMgr about this buffer, which is what the parser will pick up.
249 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
250
251 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
252 assert(MRI && "Unable to create target register info!");
253
254 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
255 assert(MAI && "Unable to create target asm info!");
256
257 MCObjectFileInfo MOFI;
258 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
259 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
260
261 std::unique_ptr<buffer_ostream> BOS;
262 std::unique_ptr<mca::SourceMgr> S =
263 llvm::make_unique<mca::SourceMgr>(Iterations);
264 MCStreamerWrapper Str(Ctx, S->getSequence());
265
266 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
267 std::unique_ptr<MCSubtargetInfo> STI(
268 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
269 if (!STI->isCPUStringValid(MCPU))
270 return 1;
271
272 if (!STI->getSchedModel().isOutOfOrder()) {
273 errs() << "error: please specify an out-of-order cpu. '" << MCPU
274 << "' is an in-order cpu.\n";
275 return 1;
276 }
277
278 if (!STI->getSchedModel().hasInstrSchedModel()) {
279 errs()
280 << "error: unable to find instruction-level scheduling information for"
281 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
282 << "'.\n";
283
284 if (STI->getSchedModel().InstrItineraries)
285 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
286 << "instruction itineraries are currently unsupported.\n";
287 return 1;
288 }
289
290 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
291 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
292 if (!IP) {
293 errs() << "error: unable to create instruction printer for target triple '"
294 << TheTriple.normalize() << "' with assembly variant "
295 << OutputAsmVariant << ".\n";
296 return 1;
297 }
298
299 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
300 *MCII, MCOptions);
301 if (Res)
302 return Res;
303
304 if (S->isEmpty()) {
305 errs() << "error: no assembly instructions found.\n";
306 return 1;
307 }
308
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000309 // Now initialize the output file.
310 auto OF = getOutputStream();
311 if (std::error_code EC = OF.getError()) {
312 errs() << EC.message() << '\n';
313 return 1;
314 }
315
316 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
317
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000318 const MCSchedModel &SM = STI->getSchedModel();
319
320 unsigned Width = SM.IssueWidth;
321 if (DispatchWidth)
322 Width = DispatchWidth;
323
324 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000325 *STI, *MCII, *MRI, *S, Width, RegisterFileSize, MaxRetirePerCycle,
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000326 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
327
328 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000329 llvm::make_unique<mca::BackendPrinter>(*B);
330
Andrea Di Biagio35622482018-03-22 10:19:20 +0000331 Printer->addView(
332 llvm::make_unique<mca::SummaryView>(*STI, *MCII, *S, *IP, Width));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000333
Andrea Di Biagio35622482018-03-22 10:19:20 +0000334 if (PrintModeVerbose)
335 Printer->addView(llvm::make_unique<mca::BackendStatistics>(*STI));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000336
Andrea Di Biagio29538c62018-03-23 11:33:09 +0000337 if (PrintResourcePressureView)
338 Printer->addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000339
340 if (PrintTimelineView) {
Andrea Di Biagio35622482018-03-22 10:19:20 +0000341 Printer->addView(llvm::make_unique<mca::TimelineView>(
342 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000343 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000344
345 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000346 Printer->printReport(TOF->os());
347 TOF->keep();
348
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000349 return 0;
350}