blob: e9248f154429f578b2b970777297061f226ee532 [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
92static cl::opt<bool> PrintTimelineView("timeline",
93 cl::desc("Print the timeline view"),
94 cl::init(false));
95
96static cl::opt<unsigned> TimelineMaxIterations(
97 "timeline-max-iterations",
98 cl::desc("Maximum number of iterations to print in timeline view"),
99 cl::init(0));
100
101static cl::opt<unsigned> TimelineMaxCycles(
102 "timeline-max-cycles",
103 cl::desc(
104 "Maximum number of cycles in the timeline view. Defaults to 80 cycles"),
105 cl::init(80));
106
107static cl::opt<bool> PrintModeVerbose("verbose",
108 cl::desc("Enable verbose output"),
109 cl::init(false));
110
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000111static cl::opt<bool> AssumeNoAlias(
112 "noalias",
113 cl::desc("If set, it assumes that loads and stores do not alias"),
114 cl::init(true));
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000115
116static cl::opt<unsigned>
117 LoadQueueSize("lqueue", cl::desc("Size of the load queue"), cl::init(0));
118static cl::opt<unsigned>
119 StoreQueueSize("squeue", cl::desc("Size of the store queue"), cl::init(0));
120
121static const Target *getTarget(const char *ProgName) {
122 TripleName = Triple::normalize(TripleName);
123 if (TripleName.empty())
124 TripleName = Triple::normalize(sys::getDefaultTargetTriple());
125 Triple TheTriple(TripleName);
126
127 // Get the target specific parser.
128 std::string Error;
129 const Target *TheTarget =
130 TargetRegistry::lookupTarget(ArchName, TheTriple, Error);
131 if (!TheTarget) {
132 errs() << ProgName << ": " << Error;
133 return nullptr;
134 }
135
136 // Return the found target.
137 return TheTarget;
138}
139
140static int AssembleInput(const char *ProgName, const Target *TheTarget,
141 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str,
142 MCAsmInfo &MAI, MCSubtargetInfo &STI,
143 MCInstrInfo &MCII, MCTargetOptions &MCOptions) {
144 std::unique_ptr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, Str, MAI));
145 std::unique_ptr<MCTargetAsmParser> TAP(
146 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions));
147
148 if (!TAP) {
149 errs() << ProgName
150 << ": error: this target does not support assembly parsing.\n";
151 return 1;
152 }
153
154 Parser->setTargetParser(*TAP);
155 return Parser->Run(false);
156}
157
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000158static ErrorOr<std::unique_ptr<ToolOutputFile>> getOutputStream() {
159 if (OutputFilename == "")
160 OutputFilename = "-";
161 std::error_code EC;
162 auto Out =
163 llvm::make_unique<ToolOutputFile>(OutputFilename, EC, sys::fs::F_None);
164 if (!EC)
165 return std::move(Out);
166 return EC;
167}
168
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000169namespace {
170
171class MCStreamerWrapper final : public MCStreamer {
172 using InstVec = std::vector<std::unique_ptr<const MCInst>>;
173 InstVec &Insts;
174
175public:
176 MCStreamerWrapper(MCContext &Context, InstVec &Vec)
177 : MCStreamer(Context), Insts(Vec) {}
178
179 // We only want to intercept the emission of new instructions.
180 virtual void EmitInstruction(const MCInst &Inst, const MCSubtargetInfo &STI,
181 bool /* unused */) override {
182 Insts.emplace_back(new MCInst(Inst));
183 }
184
185 bool EmitSymbolAttribute(MCSymbol *Symbol, MCSymbolAttr Attribute) override {
186 return true;
187 }
188
189 void EmitCommonSymbol(MCSymbol *Symbol, uint64_t Size,
190 unsigned ByteAlignment) override {}
191 void EmitZerofill(MCSection *Section, MCSymbol *Symbol = nullptr,
192 uint64_t Size = 0, unsigned ByteAlignment = 0) override {}
193 void EmitGPRel32Value(const MCExpr *Value) override {}
194 void BeginCOFFSymbolDef(const MCSymbol *Symbol) override {}
195 void EmitCOFFSymbolStorageClass(int StorageClass) override {}
196 void EmitCOFFSymbolType(int Type) override {}
197 void EndCOFFSymbolDef() override {}
198
199 const InstVec &GetInstructionSequence() const { return Insts; }
200};
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000201} // end of anonymous namespace
202
203int main(int argc, char **argv) {
204 sys::PrintStackTraceOnErrorSignal(argv[0]);
205 PrettyStackTraceProgram X(argc, argv);
206 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
207
208 // Initialize targets and assembly parsers.
209 llvm::InitializeAllTargetInfos();
210 llvm::InitializeAllTargetMCs();
211 llvm::InitializeAllAsmParsers();
212
213 // Enable printing of available targets when flag --version is specified.
214 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
215
216 // Parse flags and initialize target options.
217 cl::ParseCommandLineOptions(argc, argv,
218 "llvm machine code performance analyzer.\n");
219 MCTargetOptions MCOptions;
220 MCOptions.PreserveAsmComments = false;
221
222 // Get the target from the triple. If a triple is not specified, then select
223 // the default triple for the host. If the triple doesn't correspond to any
224 // registered target, then exit with an error message.
225 const char *ProgName = argv[0];
226 const Target *TheTarget = getTarget(ProgName);
227 if (!TheTarget)
228 return 1;
229
230 // GetTarget() may replaced TripleName with a default triple.
231 // For safety, reconstruct the Triple object.
232 Triple TheTriple(TripleName);
233
234 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr =
235 MemoryBuffer::getFileOrSTDIN(InputFilename);
236 if (std::error_code EC = BufferPtr.getError()) {
237 errs() << InputFilename << ": " << EC.message() << '\n';
238 return 1;
239 }
240
241 SourceMgr SrcMgr;
242
243 // Tell SrcMgr about this buffer, which is what the parser will pick up.
244 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc());
245
246 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
247 assert(MRI && "Unable to create target register info!");
248
249 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName));
250 assert(MAI && "Unable to create target asm info!");
251
252 MCObjectFileInfo MOFI;
253 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr);
254 MOFI.InitMCObjectFileInfo(TheTriple, /* PIC= */ false, Ctx);
255
256 std::unique_ptr<buffer_ostream> BOS;
257 std::unique_ptr<mca::SourceMgr> S =
258 llvm::make_unique<mca::SourceMgr>(Iterations);
259 MCStreamerWrapper Str(Ctx, S->getSequence());
260
261 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
262 std::unique_ptr<MCSubtargetInfo> STI(
263 TheTarget->createMCSubtargetInfo(TripleName, MCPU, /* FeaturesStr */ ""));
264 if (!STI->isCPUStringValid(MCPU))
265 return 1;
266
267 if (!STI->getSchedModel().isOutOfOrder()) {
268 errs() << "error: please specify an out-of-order cpu. '" << MCPU
269 << "' is an in-order cpu.\n";
270 return 1;
271 }
272
273 if (!STI->getSchedModel().hasInstrSchedModel()) {
274 errs()
275 << "error: unable to find instruction-level scheduling information for"
276 << " target triple '" << TheTriple.normalize() << "' and cpu '" << MCPU
277 << "'.\n";
278
279 if (STI->getSchedModel().InstrItineraries)
280 errs() << "note: cpu '" << MCPU << "' provides itineraries. However, "
281 << "instruction itineraries are currently unsupported.\n";
282 return 1;
283 }
284
285 std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
286 Triple(TripleName), OutputAsmVariant, *MAI, *MCII, *MRI));
287 if (!IP) {
288 errs() << "error: unable to create instruction printer for target triple '"
289 << TheTriple.normalize() << "' with assembly variant "
290 << OutputAsmVariant << ".\n";
291 return 1;
292 }
293
294 int Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, Str, *MAI, *STI,
295 *MCII, MCOptions);
296 if (Res)
297 return Res;
298
299 if (S->isEmpty()) {
300 errs() << "error: no assembly instructions found.\n";
301 return 1;
302 }
303
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000304 // Now initialize the output file.
305 auto OF = getOutputStream();
306 if (std::error_code EC = OF.getError()) {
307 errs() << EC.message() << '\n';
308 return 1;
309 }
310
311 std::unique_ptr<llvm::ToolOutputFile> TOF = std::move(*OF);
312
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000313 const MCSchedModel &SM = STI->getSchedModel();
314
315 unsigned Width = SM.IssueWidth;
316 if (DispatchWidth)
317 Width = DispatchWidth;
318
319 std::unique_ptr<mca::Backend> B = llvm::make_unique<mca::Backend>(
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000320 *STI, *MCII, *MRI, *S, Width, RegisterFileSize, MaxRetirePerCycle,
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000321 LoadQueueSize, StoreQueueSize, AssumeNoAlias);
322
323 std::unique_ptr<mca::BackendPrinter> Printer =
Andrea Di Biagio0cc66c72018-03-09 13:52:03 +0000324 llvm::make_unique<mca::BackendPrinter>(*B);
325
Andrea Di Biagio35622482018-03-22 10:19:20 +0000326 Printer->addView(
327 llvm::make_unique<mca::SummaryView>(*STI, *MCII, *S, *IP, Width));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000328
Andrea Di Biagio35622482018-03-22 10:19:20 +0000329 if (PrintModeVerbose)
330 Printer->addView(llvm::make_unique<mca::BackendStatistics>(*STI));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000331
Andrea Di Biagio35622482018-03-22 10:19:20 +0000332 Printer->addView(llvm::make_unique<mca::ResourcePressureView>(*STI, *IP, *S));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000333
334 if (PrintTimelineView) {
Andrea Di Biagio35622482018-03-22 10:19:20 +0000335 Printer->addView(llvm::make_unique<mca::TimelineView>(
336 *STI, *IP, *S, TimelineMaxIterations, TimelineMaxCycles));
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000337 }
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000338
339 B->run();
Andrea Di Biagio8af3fe82018-03-08 16:08:43 +0000340 Printer->printReport(TOF->os());
341 TOF->keep();
342
Andrea Di Biagio3a6b0922018-03-08 13:05:02 +0000343 return 0;
344}