blob: f97f5c99c5e8dadc6212b0c57338bb8cce3dab41 [file] [log] [blame]
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001//===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
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/// \file
11/// This tablegen backend emits code for use by the GlobalISel instruction
12/// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13///
14/// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15/// backend, filters out the ones that are unsupported, maps
16/// SelectionDAG-specific constructs to their GlobalISel counterpart
17/// (when applicable: MVT to LLT; SDNode to generic Instruction).
18///
19/// Not all patterns are supported: pass the tablegen invocation
20/// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21/// as well as why.
22///
23/// The generated file defines a single method:
24/// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25/// intended to be used in InstructionSelector::select as the first-step
26/// selector for the patterns that don't require complex C++.
27///
28/// FIXME: We'll probably want to eventually define a base
29/// "TargetGenInstructionSelector" class.
30///
31//===----------------------------------------------------------------------===//
32
33#include "CodeGenDAGPatterns.h"
34#include "llvm/ADT/Optional.h"
35#include "llvm/ADT/Statistic.h"
36#include "llvm/CodeGen/MachineValueType.h"
37#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000038#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000039#include "llvm/Support/LowLevelTypeImpl.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000040#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000041#include "llvm/TableGen/Error.h"
42#include "llvm/TableGen/Record.h"
43#include "llvm/TableGen/TableGenBackend.h"
44#include <string>
Daniel Sanders8a4bae92017-03-14 21:32:08 +000045#include <numeric>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000046using namespace llvm;
47
48#define DEBUG_TYPE "gisel-emitter"
49
50STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000051STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
52STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000053STATISTIC(NumPatternEmitted, "Number of patterns emitted");
54
Daniel Sanders0848b232017-03-27 13:15:13 +000055cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
56
Ahmed Bougacha36f70352016-12-21 23:26:20 +000057static cl::opt<bool> WarnOnSkippedPatterns(
58 "warn-on-skipped-patterns",
59 cl::desc("Explain why a pattern was skipped for inclusion "
60 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000061 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000062
Daniel Sandersbdfebb82017-03-15 20:18:38 +000063namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000064//===- Helper functions ---------------------------------------------------===//
65
Daniel Sanders52b4ce72017-03-07 23:20:35 +000066/// This class stands in for LLT wherever we want to tablegen-erate an
67/// equivalent at compiler run-time.
68class LLTCodeGen {
69private:
70 LLT Ty;
71
72public:
73 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
74
75 void emitCxxConstructorCall(raw_ostream &OS) const {
76 if (Ty.isScalar()) {
77 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
78 return;
79 }
80 if (Ty.isVector()) {
81 OS << "LLT::vector(" << Ty.getNumElements() << ", " << Ty.getSizeInBits()
82 << ")";
83 return;
84 }
85 llvm_unreachable("Unhandled LLT");
86 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +000087
88 const LLT &get() const { return Ty; }
89};
90
91class InstructionMatcher;
92class OperandPlaceholder {
93private:
94 enum PlaceholderKind {
95 OP_MatchReference,
96 OP_Temporary,
97 } Kind;
98
99 struct MatchReferenceData {
100 InstructionMatcher *InsnMatcher;
101 StringRef InsnVarName;
102 StringRef SymbolicName;
103 };
104
105 struct TemporaryData {
106 unsigned OpIdx;
107 };
108
109 union {
110 struct MatchReferenceData MatchReference;
111 struct TemporaryData Temporary;
112 };
113
114 OperandPlaceholder(PlaceholderKind Kind) : Kind(Kind) {}
115
116public:
117 ~OperandPlaceholder() {}
118
119 static OperandPlaceholder
120 CreateMatchReference(InstructionMatcher *InsnMatcher,
121 const StringRef InsnVarName, const StringRef SymbolicName) {
122 OperandPlaceholder Result(OP_MatchReference);
123 Result.MatchReference.InsnMatcher = InsnMatcher;
124 Result.MatchReference.InsnVarName = InsnVarName;
125 Result.MatchReference.SymbolicName = SymbolicName;
126 return Result;
127 }
128
129 static OperandPlaceholder CreateTemporary(unsigned OpIdx) {
130 OperandPlaceholder Result(OP_Temporary);
131 Result.Temporary.OpIdx = OpIdx;
132 return Result;
133 }
134
135 void emitCxxValueExpr(raw_ostream &OS) const;
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000136};
137
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000138/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
139/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000140static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000141 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000142 if (VT.isVector() && VT.getVectorNumElements() != 1)
143 return LLTCodeGen(LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
144 if (VT.isInteger() || VT.isFloatingPoint())
145 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
146 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000147}
148
149static bool isTrivialOperatorNode(const TreePatternNode *N) {
150 return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
151}
152
153//===- Matchers -----------------------------------------------------------===//
154
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000155class MatchAction;
156
157/// Generates code to check that a match rule matches.
158class RuleMatcher {
159 /// A list of matchers that all need to succeed for the current rule to match.
160 /// FIXME: This currently supports a single match position but could be
161 /// extended to support multiple positions to support div/rem fusion or
162 /// load-multiple instructions.
163 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
164
165 /// A list of actions that need to be taken when all predicates in this rule
166 /// have succeeded.
167 std::vector<std::unique_ptr<MatchAction>> Actions;
168
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000169 /// A map of instruction matchers to the local variables created by
170 /// emitCxxCaptureStmts().
171 std::map<const InstructionMatcher *, std::string> InsnVariableNames;
172
173 /// ID for the next instruction variable defined with defineInsnVar()
174 unsigned NextInsnVarID;
175
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000176public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000177 RuleMatcher()
178 : Matchers(), Actions(), InsnVariableNames(), NextInsnVarID(0) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000179 RuleMatcher(RuleMatcher &&Other) = default;
180 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000181
182 InstructionMatcher &addInstructionMatcher();
183
184 template <class Kind, class... Args> Kind &addAction(Args &&... args);
185
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000186 std::string defineInsnVar(raw_ostream &OS, const InstructionMatcher &Matcher,
187 StringRef Value);
188 StringRef getInsnVarName(const InstructionMatcher &InsnMatcher) const;
189
190 void emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr);
191
192 void emit(raw_ostream &OS);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000193
194 /// Compare the priority of this object and B.
195 ///
196 /// Returns true if this object is more important than B.
197 bool isHigherPriorityThan(const RuleMatcher &B) const;
198
199 /// Report the maximum number of temporary operands needed by the rule
200 /// matcher.
201 unsigned countTemporaryOperands() const;
202};
203
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000204template <class PredicateTy> class PredicateListMatcher {
205private:
206 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
207 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000208
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000209public:
210 /// Construct a new operand predicate and add it to the matcher.
211 template <class Kind, class... Args>
212 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000213 Predicates.emplace_back(
214 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000215 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000216 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000217
218 typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
219 typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
220 iterator_range<typename PredicateVec::const_iterator> predicates() const {
221 return make_range(predicates_begin(), predicates_end());
222 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000223 typename PredicateVec::size_type predicates_size() const { return Predicates.size(); }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000224
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000225 /// Emit a C++ expression that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000226 template <class... Args>
Daniel Sandersf8c804f2017-01-28 11:10:42 +0000227 void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000228 if (Predicates.empty()) {
229 OS << "true";
230 return;
231 }
232
233 StringRef Separator = "";
234 for (const auto &Predicate : predicates()) {
235 OS << Separator << "(";
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000236 Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000237 OS << ")";
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000238 Separator = " &&\n";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000239 }
240 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000241};
242
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000243/// Generates code to check a predicate of an operand.
244///
245/// Typical predicates include:
246/// * Operand is a particular register.
247/// * Operand is assigned a particular register bank.
248/// * Operand is an MBB.
249class OperandPredicateMatcher {
250public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000251 /// This enum is used for RTTI and also defines the priority that is given to
252 /// the predicate when generating the matcher code. Kinds with higher priority
253 /// must be tested first.
254 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000255 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
256 /// but OPM_Int must have priority over OPM_RegBank since constant integers
257 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000258 enum PredicateKind {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000259 OPM_ComplexPattern,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000260 OPM_Int,
Daniel Sanders759ff412017-02-24 13:58:11 +0000261 OPM_LLT,
262 OPM_RegBank,
263 OPM_MBB,
264 };
265
266protected:
267 PredicateKind Kind;
268
269public:
270 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000271 virtual ~OperandPredicateMatcher() {}
272
Daniel Sanders759ff412017-02-24 13:58:11 +0000273 PredicateKind getKind() const { return Kind; }
274
Daniel Sanderse604ef52017-02-20 15:30:43 +0000275 /// Emit a C++ expression that checks the predicate for the given operand.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000276 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanderse604ef52017-02-20 15:30:43 +0000277 StringRef OperandExpr) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000278
279 /// Compare the priority of this object and B.
280 ///
281 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000282 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const {
283 return Kind < B.Kind;
Daniel Sanders759ff412017-02-24 13:58:11 +0000284 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000285
286 /// Report the maximum number of temporary operands needed by the predicate
287 /// matcher.
288 virtual unsigned countTemporaryOperands() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000289};
290
291/// Generates code to check that an operand is a particular LLT.
292class LLTOperandMatcher : public OperandPredicateMatcher {
293protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000294 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000295
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000296public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000297 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanders759ff412017-02-24 13:58:11 +0000298 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
299
300 static bool classof(const OperandPredicateMatcher *P) {
301 return P->getKind() == OPM_LLT;
302 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000303
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000304 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanderse604ef52017-02-20 15:30:43 +0000305 StringRef OperandExpr) const override {
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000306 OS << "MRI.getType(" << OperandExpr << ".getReg()) == (";
307 Ty.emitCxxConstructorCall(OS);
308 OS << ")";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000309 }
310};
311
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000312/// Generates code to check that an operand is a particular target constant.
313class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
314protected:
315 const Record &TheDef;
316 /// The index of the first temporary operand to allocate to this
317 /// ComplexPattern.
318 unsigned BaseTemporaryID;
319
320 unsigned getNumOperands() const {
321 return TheDef.getValueAsDag("Operands")->getNumArgs();
322 }
323
324public:
325 ComplexPatternOperandMatcher(const Record &TheDef, unsigned BaseTemporaryID)
326 : OperandPredicateMatcher(OPM_ComplexPattern), TheDef(TheDef),
327 BaseTemporaryID(BaseTemporaryID) {}
328
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000329 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000330 StringRef OperandExpr) const override {
331 OS << TheDef.getValueAsString("MatcherFn") << "(" << OperandExpr;
332 for (unsigned I = 0; I < getNumOperands(); ++I) {
333 OS << ", ";
334 OperandPlaceholder::CreateTemporary(BaseTemporaryID + I)
335 .emitCxxValueExpr(OS);
336 }
337 OS << ")";
338 }
339
340 unsigned countTemporaryOperands() const override {
341 return getNumOperands();
342 }
343};
344
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000345/// Generates code to check that an operand is in a particular register bank.
346class RegisterBankOperandMatcher : public OperandPredicateMatcher {
347protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000348 const CodeGenRegisterClass &RC;
349
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000350public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000351 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
352 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
353
354 static bool classof(const OperandPredicateMatcher *P) {
355 return P->getKind() == OPM_RegBank;
356 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000357
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000358 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanderse604ef52017-02-20 15:30:43 +0000359 StringRef OperandExpr) const override {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000360 OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
Daniel Sanderse604ef52017-02-20 15:30:43 +0000361 << "RegClass) == RBI.getRegBank(" << OperandExpr
362 << ".getReg(), MRI, TRI))";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000363 }
364};
365
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000366/// Generates code to check that an operand is a basic block.
367class MBBOperandMatcher : public OperandPredicateMatcher {
368public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000369 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
370
371 static bool classof(const OperandPredicateMatcher *P) {
372 return P->getKind() == OPM_MBB;
373 }
374
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000375 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Daniel Sanderse604ef52017-02-20 15:30:43 +0000376 StringRef OperandExpr) const override {
377 OS << OperandExpr << ".isMBB()";
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000378 }
379};
380
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000381/// Generates code to check that an operand is a particular int.
382class IntOperandMatcher : public OperandPredicateMatcher {
383protected:
384 int64_t Value;
385
386public:
387 IntOperandMatcher(int64_t Value)
388 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
389
390 static bool classof(const OperandPredicateMatcher *P) {
391 return P->getKind() == OPM_Int;
392 }
393
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000394 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Simon Pilgrimd0302912017-02-24 17:20:27 +0000395 StringRef OperandExpr) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000396 OS << "isOperandImmEqual(" << OperandExpr << ", " << Value << ", MRI)";
397 }
398};
399
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000400/// Generates code to check that a set of predicates match for a particular
401/// operand.
402class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
403protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000404 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000405 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000406 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000407
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000408public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000409 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
410 const std::string &SymbolicName)
411 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000412
413 bool hasSymbolicName() const { return !SymbolicName.empty(); }
414 const StringRef getSymbolicName() const { return SymbolicName; }
415 unsigned getOperandIndex() const { return OpIdx; }
416
417 std::string getOperandExpr(const StringRef InsnVarName) const {
Pavel Labath52a82e22017-02-21 09:19:41 +0000418 return (InsnVarName + ".getOperand(" + llvm::to_string(OpIdx) + ")").str();
Daniel Sanderse604ef52017-02-20 15:30:43 +0000419 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000420
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000421 InstructionMatcher &getInstructionMatcher() const { return Insn; }
422
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000423 /// Emit a C++ expression that tests whether the instruction named in
424 /// InsnVarName matches all the predicate and all the operands.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000425 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
426 const StringRef InsnVarName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000427 OS << "(/* ";
428 if (SymbolicName.empty())
429 OS << "Operand " << OpIdx;
430 else
431 OS << SymbolicName;
432 OS << " */ ";
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000433 emitCxxPredicateListExpr(OS, Rule, getOperandExpr(InsnVarName));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000434 OS << ")";
435 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000436
437 /// Compare the priority of this object and B.
438 ///
439 /// Returns true if this object is more important than B.
440 bool isHigherPriorityThan(const OperandMatcher &B) const {
441 // Operand matchers involving more predicates have higher priority.
442 if (predicates_size() > B.predicates_size())
443 return true;
444 if (predicates_size() < B.predicates_size())
445 return false;
446
447 // This assumes that predicates are added in a consistent order.
448 for (const auto &Predicate : zip(predicates(), B.predicates())) {
449 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
450 return true;
451 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
452 return false;
453 }
454
455 return false;
456 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000457
458 /// Report the maximum number of temporary operands needed by the operand
459 /// matcher.
460 unsigned countTemporaryOperands() const {
461 return std::accumulate(
462 predicates().begin(), predicates().end(), 0,
463 [](unsigned A,
464 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
465 return A + Predicate->countTemporaryOperands();
466 });
467 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000468};
469
470/// Generates code to check a predicate on an instruction.
471///
472/// Typical predicates include:
473/// * The opcode of the instruction is a particular value.
474/// * The nsw/nuw flag is/isn't set.
475class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000476protected:
477 /// This enum is used for RTTI and also defines the priority that is given to
478 /// the predicate when generating the matcher code. Kinds with higher priority
479 /// must be tested first.
480 enum PredicateKind {
481 IPM_Opcode,
482 };
483
484 PredicateKind Kind;
485
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000486public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000487 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000488 virtual ~InstructionPredicateMatcher() {}
489
Daniel Sanders759ff412017-02-24 13:58:11 +0000490 PredicateKind getKind() const { return Kind; }
491
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000492 /// Emit a C++ expression that tests whether the instruction named in
493 /// InsnVarName matches the predicate.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000494 virtual void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000495 StringRef InsnVarName) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000496
497 /// Compare the priority of this object and B.
498 ///
499 /// Returns true if this object is more important than B.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000500 virtual bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000501 return Kind < B.Kind;
502 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000503
504 /// Report the maximum number of temporary operands needed by the predicate
505 /// matcher.
506 virtual unsigned countTemporaryOperands() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000507};
508
509/// Generates code to check the opcode of an instruction.
510class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
511protected:
512 const CodeGenInstruction *I;
513
514public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000515 InstructionOpcodeMatcher(const CodeGenInstruction *I)
516 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000517
Daniel Sanders759ff412017-02-24 13:58:11 +0000518 static bool classof(const InstructionPredicateMatcher *P) {
519 return P->getKind() == IPM_Opcode;
520 }
521
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000522 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
Ahmed Bougacha6a1ac5a2017-02-09 02:50:01 +0000523 StringRef InsnVarName) const override {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000524 OS << InsnVarName << ".getOpcode() == " << I->Namespace
525 << "::" << I->TheDef->getName();
526 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000527
528 /// Compare the priority of this object and B.
529 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000530 /// Returns true if this object is more important than B.
531 bool isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000532 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
533 return true;
534 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
535 return false;
536
537 // Prioritize opcodes for cosmetic reasons in the generated source. Although
538 // this is cosmetic at the moment, we may want to drive a similar ordering
539 // using instruction frequency information to improve compile time.
540 if (const InstructionOpcodeMatcher *BO =
541 dyn_cast<InstructionOpcodeMatcher>(&B))
542 return I->TheDef->getName() < BO->I->TheDef->getName();
543
544 return false;
545 };
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000546};
547
548/// Generates code to check that a set of predicates and operands match for a
549/// particular instruction.
550///
551/// Typical predicates include:
552/// * Has a specific opcode.
553/// * Has an nsw/nuw flag or doesn't.
554class InstructionMatcher
555 : public PredicateListMatcher<InstructionPredicateMatcher> {
556protected:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000557 typedef std::vector<OperandMatcher> OperandVec;
558
559 /// The operands to match. All rendered operands must be present even if the
560 /// condition is always true.
561 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000562
563public:
564 /// Add an operand to the matcher.
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000565 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000566 Operands.emplace_back(*this, OpIdx, SymbolicName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000567 return Operands.back();
568 }
569
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000570 Optional<const OperandMatcher *> getOptionalOperand(StringRef SymbolicName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000571 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
572 const auto &I = std::find_if(Operands.begin(), Operands.end(),
573 [&SymbolicName](const OperandMatcher &X) {
574 return X.getSymbolicName() == SymbolicName;
575 });
576 if (I != Operands.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000577 return &*I;
578 return None;
579 }
580
581 const OperandMatcher &getOperand(const StringRef SymbolicName) const {
582 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
583 if (OM.hasValue())
584 return *OM.getValue();
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000585 llvm_unreachable("Failed to lookup operand");
586 }
587
588 unsigned getNumOperands() const { return Operands.size(); }
589 OperandVec::const_iterator operands_begin() const {
590 return Operands.begin();
591 }
592 OperandVec::const_iterator operands_end() const {
593 return Operands.end();
594 }
595 iterator_range<OperandVec::const_iterator> operands() const {
596 return make_range(operands_begin(), operands_end());
597 }
598
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000599 /// Emit C++ statements to check the shape of the match and capture
600 /// instructions into local variables.
601 ///
602 /// TODO: When nested instruction matching is implemented, this function will
603 /// descend into the operands and capture variables.
604 void emitCxxCaptureStmts(raw_ostream &OS, RuleMatcher &Rule, StringRef Expr) {
605 OS << "if (" << Expr << ".getNumOperands() < " << getNumOperands() << ")\n"
606 << " return false;\n";
607 }
608
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000609 /// Emit a C++ expression that tests whether the instruction named in
610 /// InsnVarName matches all the predicates and all the operands.
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000611 void emitCxxPredicateExpr(raw_ostream &OS, RuleMatcher &Rule,
612 StringRef InsnVarName) const {
613 emitCxxPredicateListExpr(OS, Rule, InsnVarName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000614 for (const auto &Operand : Operands) {
Ahmed Bougacha905af9f2017-02-04 00:47:02 +0000615 OS << " &&\n(";
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000616 Operand.emitCxxPredicateExpr(OS, Rule, InsnVarName);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000617 OS << ")";
618 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000619 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000620
621 /// Compare the priority of this object and B.
622 ///
623 /// Returns true if this object is more important than B.
624 bool isHigherPriorityThan(const InstructionMatcher &B) const {
625 // Instruction matchers involving more operands have higher priority.
626 if (Operands.size() > B.Operands.size())
627 return true;
628 if (Operands.size() < B.Operands.size())
629 return false;
630
631 for (const auto &Predicate : zip(predicates(), B.predicates())) {
632 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
633 return true;
634 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
635 return false;
636 }
637
638 for (const auto &Operand : zip(Operands, B.Operands)) {
639 if (std::get<0>(Operand).isHigherPriorityThan(std::get<1>(Operand)))
640 return true;
641 if (std::get<1>(Operand).isHigherPriorityThan(std::get<0>(Operand)))
642 return false;
643 }
644
645 return false;
646 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000647
648 /// Report the maximum number of temporary operands needed by the instruction
649 /// matcher.
650 unsigned countTemporaryOperands() const {
651 return std::accumulate(predicates().begin(), predicates().end(), 0,
652 [](unsigned A,
653 const std::unique_ptr<InstructionPredicateMatcher>
654 &Predicate) {
655 return A + Predicate->countTemporaryOperands();
656 }) +
657 std::accumulate(Operands.begin(), Operands.end(), 0,
658 [](unsigned A, const OperandMatcher &Operand) {
659 return A + Operand.countTemporaryOperands();
660 });
661 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000662};
663
Daniel Sanders43c882c2017-02-01 10:53:10 +0000664//===- Actions ------------------------------------------------------------===//
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000665void OperandPlaceholder::emitCxxValueExpr(raw_ostream &OS) const {
666 switch (Kind) {
667 case OP_MatchReference:
668 OS << MatchReference.InsnMatcher->getOperand(MatchReference.SymbolicName)
669 .getOperandExpr(MatchReference.InsnVarName);
670 break;
671 case OP_Temporary:
672 OS << "TempOp" << Temporary.OpIdx;
673 break;
674 }
675}
Daniel Sanders43c882c2017-02-01 10:53:10 +0000676
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000677class OperandRenderer {
678public:
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000679 enum RendererKind { OR_Copy, OR_Register, OR_ComplexPattern };
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000680
681protected:
682 RendererKind Kind;
683
684public:
685 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
686 virtual ~OperandRenderer() {}
687
688 RendererKind getKind() const { return Kind; }
689
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000690 virtual void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000691};
692
693/// A CopyRenderer emits code to copy a single operand from an existing
694/// instruction to the one being built.
695class CopyRenderer : public OperandRenderer {
696protected:
697 /// The matcher for the instruction that this operand is copied from.
698 /// This provides the facility for looking up an a operand by it's name so
699 /// that it can be used as a source for the instruction being built.
700 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000701 /// The name of the operand.
702 const StringRef SymbolicName;
703
704public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000705 CopyRenderer(const InstructionMatcher &Matched, StringRef SymbolicName)
706 : OperandRenderer(OR_Copy), Matched(Matched), SymbolicName(SymbolicName) {
707 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000708
709 static bool classof(const OperandRenderer *R) {
710 return R->getKind() == OR_Copy;
711 }
712
713 const StringRef getSymbolicName() const { return SymbolicName; }
714
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000715 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
716 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
717 StringRef InsnVarName =
718 Rule.getInsnVarName(Operand.getInstructionMatcher());
719 std::string OperandExpr = Operand.getOperandExpr(InsnVarName);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000720 OS << " MIB.add(" << OperandExpr << "/*" << SymbolicName << "*/);\n";
721 }
722};
723
724/// Adds a specific physical register to the instruction being built.
725/// This is typically useful for WZR/XZR on AArch64.
726class AddRegisterRenderer : public OperandRenderer {
727protected:
728 const Record *RegisterDef;
729
730public:
731 AddRegisterRenderer(const Record *RegisterDef)
732 : OperandRenderer(OR_Register), RegisterDef(RegisterDef) {}
733
734 static bool classof(const OperandRenderer *R) {
735 return R->getKind() == OR_Register;
736 }
737
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000738 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000739 OS << " MIB.addReg(" << RegisterDef->getValueAsString("Namespace")
740 << "::" << RegisterDef->getName() << ");\n";
741 }
742};
743
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000744class RenderComplexPatternOperand : public OperandRenderer {
745private:
746 const Record &TheDef;
747 std::vector<OperandPlaceholder> Sources;
748
749 unsigned getNumOperands() const {
750 return TheDef.getValueAsDag("Operands")->getNumArgs();
751 }
752
753public:
754 RenderComplexPatternOperand(const Record &TheDef,
755 const ArrayRef<OperandPlaceholder> Sources)
756 : OperandRenderer(OR_ComplexPattern), TheDef(TheDef), Sources(Sources) {}
757
758 static bool classof(const OperandRenderer *R) {
759 return R->getKind() == OR_ComplexPattern;
760 }
761
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000762 void emitCxxRenderStmts(raw_ostream &OS, RuleMatcher &Rule) const override {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000763 assert(Sources.size() == getNumOperands() && "Inconsistent number of operands");
764 for (const auto &Source : Sources) {
765 OS << "MIB.add(";
766 Source.emitCxxValueExpr(OS);
767 OS << ");\n";
768 }
769 }
770};
771
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000772/// An action taken when all Matcher predicates succeeded for a parent rule.
773///
774/// Typical actions include:
775/// * Changing the opcode of an instruction.
776/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +0000777class MatchAction {
778public:
779 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000780
781 /// Emit the C++ statements to implement the action.
782 ///
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000783 /// \param RecycleVarName If given, it's an instruction to recycle. The
784 /// requirements on the instruction vary from action to
785 /// action.
786 virtual void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
787 StringRef RecycleVarName) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +0000788};
789
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000790/// Generates a comment describing the matched rule being acted upon.
791class DebugCommentAction : public MatchAction {
792private:
793 const PatternToMatch &P;
794
795public:
796 DebugCommentAction(const PatternToMatch &P) : P(P) {}
797
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000798 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
799 StringRef RecycleVarName) const override {
800 OS << "// " << *P.getSrcPattern() << " => " << *P.getDstPattern() << "\n";
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +0000801 }
802};
803
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000804/// Generates code to build an instruction or mutate an existing instruction
805/// into the desired instruction when this is possible.
806class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +0000807private:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000808 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000809 const InstructionMatcher &Matched;
810 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
811
812 /// True if the instruction can be built solely by mutating the opcode.
813 bool canMutate() const {
814 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +0000815 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000816 if (Matched.getOperand(Copy->getSymbolicName()).getOperandIndex() !=
Zachary Turner309a0882017-03-13 16:24:10 +0000817 Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000818 return false;
819 } else
820 return false;
821 }
822
823 return true;
824 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000825
Daniel Sanders43c882c2017-02-01 10:53:10 +0000826public:
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000827 BuildMIAction(const CodeGenInstruction *I, const InstructionMatcher &Matched)
828 : I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +0000829
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000830 template <class Kind, class... Args>
831 Kind &addRenderer(Args&&... args) {
832 OperandRenderers.emplace_back(
833 llvm::make_unique<Kind>(std::forward<Args>(args)...));
834 return *static_cast<Kind *>(OperandRenderers.back().get());
835 }
836
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000837 void emitCxxActionStmts(raw_ostream &OS, RuleMatcher &Rule,
838 StringRef RecycleVarName) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000839 if (canMutate()) {
Tim Northover4340d642017-03-20 21:58:23 +0000840 OS << " " << RecycleVarName << ".setDesc(TII.get(" << I->Namespace
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000841 << "::" << I->TheDef->getName() << "));\n";
Tim Northover4340d642017-03-20 21:58:23 +0000842
843 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
844 OS << " auto MIB = MachineInstrBuilder(MF, &" << RecycleVarName
845 << ");\n";
846
847 for (auto Def : I->ImplicitDefs) {
848 auto Namespace = Def->getValueAsString("Namespace");
849 OS << " MIB.addDef(" << Namespace << "::" << Def->getName()
850 << ", RegState::Implicit);\n";
851 }
852 for (auto Use : I->ImplicitUses) {
853 auto Namespace = Use->getValueAsString("Namespace");
854 OS << " MIB.addUse(" << Namespace << "::" << Use->getName()
855 << ", RegState::Implicit);\n";
856 }
857 }
858
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000859 OS << " MachineInstr &NewI = " << RecycleVarName << ";\n";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000860 return;
861 }
862
863 // TODO: Simple permutation looks like it could be almost as common as
864 // mutation due to commutative operations.
865
866 OS << "MachineInstrBuilder MIB = BuildMI(*I.getParent(), I, "
867 "I.getDebugLoc(), TII.get("
868 << I->Namespace << "::" << I->TheDef->getName() << "));\n";
869 for (const auto &Renderer : OperandRenderers)
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000870 Renderer->emitCxxRenderStmts(OS, Rule);
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000871 OS << " MIB.setMemRefs(I.memoperands_begin(), I.memoperands_end());\n";
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000872 OS << " " << RecycleVarName << ".eraseFromParent();\n";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000873 OS << " MachineInstr &NewI = *MIB;\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000874 }
875};
876
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000877InstructionMatcher &RuleMatcher::addInstructionMatcher() {
878 Matchers.emplace_back(new InstructionMatcher());
879 return *Matchers.back();
880}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +0000881
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000882template <class Kind, class... Args>
883Kind &RuleMatcher::addAction(Args &&... args) {
884 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
885 return *static_cast<Kind *>(Actions.back().get());
886}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000887
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000888std::string RuleMatcher::defineInsnVar(raw_ostream &OS,
889 const InstructionMatcher &Matcher,
890 StringRef Value) {
891 std::string InsnVarName = "MI" + llvm::to_string(NextInsnVarID++);
892 OS << "MachineInstr &" << InsnVarName << " = " << Value << ";\n";
893 InsnVariableNames[&Matcher] = InsnVarName;
894 return InsnVarName;
895}
896
897StringRef RuleMatcher::getInsnVarName(const InstructionMatcher &InsnMatcher) const {
898 const auto &I = InsnVariableNames.find(&InsnMatcher);
899 if (I != InsnVariableNames.end())
900 return I->second;
901 llvm_unreachable("Matched Insn was not captured in a local variable");
902}
903
904/// Emit C++ statements to check the shape of the match and capture
905/// instructions into local variables.
906void RuleMatcher::emitCxxCaptureStmts(raw_ostream &OS, StringRef Expr) {
907 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
908 std::string InsnVarName = defineInsnVar(OS, *Matchers.front(), Expr);
909 Matchers.front()->emitCxxCaptureStmts(OS, *this, InsnVarName);
910}
911
912void RuleMatcher::emit(raw_ostream &OS) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000913 if (Matchers.empty())
914 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000915
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000916 // The representation supports rules that require multiple roots such as:
917 // %ptr(p0) = ...
918 // %elt0(s32) = G_LOAD %ptr
919 // %1(p0) = G_ADD %ptr, 4
920 // %elt1(s32) = G_LOAD p0 %1
921 // which could be usefully folded into:
922 // %ptr(p0) = ...
923 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
924 // on some targets but we don't need to make use of that yet.
925 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000926 OS << "if ([&]() {\n";
927
928 emitCxxCaptureStmts(OS, "I");
929
930 OS << " if (";
931 Matchers.front()->emitCxxPredicateExpr(OS, *this,
932 getInsnVarName(*Matchers.front()));
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000933 OS << ") {\n";
934
935 for (const auto &MA : Actions) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000936 MA->emitCxxActionStmts(OS, *this, "I");
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000937 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000938
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000939 OS << " constrainSelectedInstRegOperands(NewI, TII, TRI, RBI);\n";
940 OS << " return true;\n";
941 OS << " }\n";
942 OS << " return false;\n";
943 OS << " }()) { return true; }\n\n";
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000944}
Daniel Sanders43c882c2017-02-01 10:53:10 +0000945
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000946bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
947 // Rules involving more match roots have higher priority.
948 if (Matchers.size() > B.Matchers.size())
949 return true;
950 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +0000951 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000952
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000953 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
954 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
955 return true;
956 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
957 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000958 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000959
960 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +0000961}
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000962
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000963unsigned RuleMatcher::countTemporaryOperands() const {
964 return std::accumulate(
965 Matchers.begin(), Matchers.end(), 0,
966 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
967 return A + Matcher->countTemporaryOperands();
968 });
969}
970
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000971//===- GlobalISelEmitter class --------------------------------------------===//
972
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000973class GlobalISelEmitter {
974public:
975 explicit GlobalISelEmitter(RecordKeeper &RK);
976 void run(raw_ostream &OS);
977
978private:
979 const RecordKeeper &RK;
980 const CodeGenDAGPatterns CGP;
981 const CodeGenTarget &Target;
982
983 /// Keep track of the equivalence between SDNodes and Instruction.
984 /// This is defined using 'GINodeEquiv' in the target description.
985 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
986
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000987 /// Keep track of the equivalence between ComplexPattern's and
988 /// GIComplexOperandMatcher. Map entries are specified by subclassing
989 /// GIComplexPatternEquiv.
990 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
991
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000992 void gatherNodeEquivs();
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000993 const CodeGenInstruction *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +0000994
995 /// Analyze pattern \p P, returning a matcher for it if possible.
996 /// Otherwise, return an Error explaining why we don't support it.
997 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
998};
999
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001000void GlobalISelEmitter::gatherNodeEquivs() {
1001 assert(NodeEquivs.empty());
1002 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1003 NodeEquivs[Equiv->getValueAsDef("Node")] =
1004 &Target.getInstruction(Equiv->getValueAsDef("I"));
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001005
1006 assert(ComplexPatternEquivs.empty());
1007 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1008 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1009 if (!SelDAGEquiv)
1010 continue;
1011 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1012 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001013}
1014
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001015const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001016 return NodeEquivs.lookup(N);
1017}
1018
1019GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
1020 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
1021
1022//===- Emitter ------------------------------------------------------------===//
1023
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001024/// Helper function to let the emitter report skip reason error messages.
1025static Error failedImport(const Twine &Reason) {
1026 return make_error<StringError>(Reason, inconvertibleErrorCode());
1027}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001028
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001029Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001030 unsigned TempOpIdx = 0;
1031
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001032 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001033 RuleMatcher M;
1034 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001035
1036 // First, analyze the whole pattern.
1037 // If the entire pattern has a predicate (e.g., target features), ignore it.
1038 if (!P.getPredicates()->getValues().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001039 return failedImport("Pattern has a predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001040
1041 // Physreg imp-defs require additional logic. Ignore the pattern.
1042 if (!P.getDstRegs().empty())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001043 return failedImport("Pattern defines a physical register");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001044
1045 // Next, analyze the pattern operators.
1046 TreePatternNode *Src = P.getSrcPattern();
1047 TreePatternNode *Dst = P.getDstPattern();
1048
1049 // If the root of either pattern isn't a simple operator, ignore it.
1050 if (!isTrivialOperatorNode(Dst))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001051 return failedImport("Dst pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001052 if (!isTrivialOperatorNode(Src))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001053 return failedImport("Src pattern root isn't a trivial operator");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001054
1055 Record *DstOp = Dst->getOperator();
1056 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001057 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001058
1059 auto &DstI = Target.getInstruction(DstOp);
1060
1061 auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
1062 if (!SrcGIOrNull)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001063 return failedImport("Pattern operator lacks an equivalent Instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001064 auto &SrcGI = *SrcGIOrNull;
1065
1066 // The operators look good: match the opcode and mutate it to the new one.
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001067 InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
1068 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001069 auto &DstMIBuilder = M.addAction<BuildMIAction>(&DstI, InsnMatcher);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001070
1071 // Next, analyze the children, only accepting patterns that don't require
1072 // any change to operands.
1073 if (Src->getNumChildren() != Dst->getNumChildren())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001074 return failedImport("Src/dst patterns have a different # of children");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001075
1076 unsigned OpIdx = 0;
1077
1078 // Start with the defined operands (i.e., the results of the root operator).
1079 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001080 return failedImport("Src pattern results and dst MI defs are different");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001081
1082 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001083 const auto &DstIOperand = DstI.Operands[OpIdx];
1084 Record *DstIOpRec = DstIOperand.Rec;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001085 if (!DstIOpRec->isSubClassOf("RegisterClass"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001086 return failedImport("Dst MI def isn't a register class");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001087
1088 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1089 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001090 return failedImport("Dst operand has an unsupported type");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001091
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001092 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx, DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001093 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1094 OM.addPredicate<RegisterBankOperandMatcher>(
1095 Target.getRegisterClass(DstIOpRec));
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001096 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher, DstIOperand.Name);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001097 ++OpIdx;
1098 }
1099
1100 // Finally match the used operands (i.e., the children of the root operator).
1101 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
1102 auto *SrcChild = Src->getChild(i);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001103
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001104 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, SrcChild->getName());
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001105
1106 // The only non-leaf child we accept is 'bb': it's an operator because
1107 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1108 if (!SrcChild->isLeaf()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001109 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1110 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1111 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001112 OM.addPredicate<MBBOperandMatcher>();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001113 continue;
1114 }
1115 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001116 return failedImport("Src pattern child isn't a leaf node or an MBB");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001117 }
1118
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001119 if (SrcChild->hasAnyPredicate())
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001120 return failedImport("Src pattern child has predicate");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001121
1122 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1123 if (ChildTypes.size() != 1)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001124 return failedImport("Src pattern child has multiple results");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001125
1126 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1127 if (!OpTyOrNone)
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001128 return failedImport("Src operand has an unsupported type");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001129 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001130
1131 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
1132 OM.addPredicate<IntOperandMatcher>(ChildInt->getValue());
1133 continue;
1134 }
1135
1136 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
1137 auto *ChildRec = ChildDefInit->getDef();
1138
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001139 if (ChildRec->isSubClassOf("RegisterClass")) {
1140 OM.addPredicate<RegisterBankOperandMatcher>(
1141 Target.getRegisterClass(ChildRec));
1142 continue;
1143 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001144
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001145 if (ChildRec->isSubClassOf("ComplexPattern")) {
1146 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1147 if (ComplexPattern == ComplexPatternEquivs.end())
1148 return failedImport(
1149 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1150
1151 const auto &Predicate = OM.addPredicate<ComplexPatternOperandMatcher>(
1152 *ComplexPattern->second, TempOpIdx);
1153 TempOpIdx += Predicate.countTemporaryOperands();
1154 continue;
1155 }
1156
1157 return failedImport(
1158 "Src pattern child def is an unsupported tablegen class");
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001159 }
1160
1161 return failedImport("Src pattern child is an unsupported kind");
1162 }
1163
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001164 TempOpIdx = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001165 // Finally render the used operands (i.e., the children of the root operator).
1166 for (unsigned i = 0, e = Dst->getNumChildren(); i != e; ++i) {
1167 auto *DstChild = Dst->getChild(i);
1168
1169 // The only non-leaf child we accept is 'bb': it's an operator because
1170 // BasicBlockSDNode isn't inline, but in MI it's just another operand.
1171 if (!DstChild->isLeaf()) {
1172 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
1173 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
1174 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001175 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001176 DstChild->getName());
1177 continue;
1178 }
1179 }
1180 return failedImport("Dst pattern child isn't a leaf node or an MBB");
1181 }
1182
1183 // Otherwise, we're looking for a bog-standard RegisterClass operand.
1184 if (DstChild->hasAnyPredicate())
1185 return failedImport("Dst pattern child has predicate");
1186
1187 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
1188 auto *ChildRec = ChildDefInit->getDef();
1189
1190 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
1191 if (ChildTypes.size() != 1)
1192 return failedImport("Dst pattern child has multiple results");
1193
1194 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1195 if (!OpTyOrNone)
1196 return failedImport("Dst operand has an unsupported type");
1197
1198 if (ChildRec->isSubClassOf("Register")) {
1199 DstMIBuilder.addRenderer<AddRegisterRenderer>(ChildRec);
1200 continue;
1201 }
1202
1203 if (ChildRec->isSubClassOf("RegisterClass")) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001204 DstMIBuilder.addRenderer<CopyRenderer>(InsnMatcher,
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001205 DstChild->getName());
1206 continue;
1207 }
1208
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001209 if (ChildRec->isSubClassOf("ComplexPattern")) {
1210 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
1211 if (ComplexPattern == ComplexPatternEquivs.end())
1212 return failedImport(
1213 "SelectionDAG ComplexPattern not mapped to GlobalISel");
1214
1215 SmallVector<OperandPlaceholder, 2> RenderedOperands;
1216 for (unsigned I = 0; I < InsnMatcher.getOperand(DstChild->getName())
1217 .countTemporaryOperands();
1218 ++I) {
1219 RenderedOperands.push_back(OperandPlaceholder::CreateTemporary(I));
1220 TempOpIdx++;
1221 }
1222 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
1223 *ComplexPattern->second,
1224 RenderedOperands);
1225 continue;
1226 }
1227
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001228 return failedImport(
1229 "Dst pattern child def is an unsupported tablegen class");
1230 }
1231
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001232 return failedImport("Dst pattern child is an unsupported kind");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001233 }
1234
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001235 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001236 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001237 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001238}
1239
1240void GlobalISelEmitter::run(raw_ostream &OS) {
1241 // Track the GINodeEquiv definitions.
1242 gatherNodeEquivs();
1243
1244 emitSourceFileHeader(("Global Instruction Selector for the " +
1245 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001246 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001247 // Look through the SelectionDAG patterns we found, possibly emitting some.
1248 for (const PatternToMatch &Pat : CGP.ptms()) {
1249 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001250 auto MatcherOrErr = runOnPattern(Pat);
1251
1252 // The pattern analysis can fail, indicating an unsupported pattern.
1253 // Report that if we've been asked to do so.
1254 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001255 if (WarnOnSkippedPatterns) {
1256 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001257 "Skipped pattern: " + toString(std::move(Err)));
1258 } else {
1259 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001260 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001261 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001262 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001263 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001264
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001265 Rules.push_back(std::move(MatcherOrErr.get()));
1266 }
1267
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001268 std::stable_sort(Rules.begin(), Rules.end(),
1269 [&](const RuleMatcher &A, const RuleMatcher &B) {
Daniel Sanders759ff412017-02-24 13:58:11 +00001270 if (A.isHigherPriorityThan(B)) {
1271 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
1272 "and less important at "
1273 "the same time");
1274 return true;
1275 }
1276 return false;
1277 });
1278
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001279 unsigned MaxTemporaries = 0;
1280 for (const auto &Rule : Rules)
1281 MaxTemporaries = std::max(MaxTemporaries, Rule.countTemporaryOperands());
1282
1283 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n";
1284 for (unsigned I = 0; I < MaxTemporaries; ++I)
1285 OS << " mutable MachineOperand TempOp" << I << ";\n";
1286 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
1287
1288 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n";
1289 for (unsigned I = 0; I < MaxTemporaries; ++I)
1290 OS << ", TempOp" << I << "(MachineOperand::CreatePlaceholder())\n";
1291 OS << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
1292
1293 OS << "#ifdef GET_GLOBALISEL_IMPL\n"
1294 << "bool " << Target.getName()
1295 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
1296 << " MachineFunction &MF = *I.getParent()->getParent();\n"
1297 << " const MachineRegisterInfo &MRI = MF.getRegInfo();\n";
1298
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001299 for (auto &Rule : Rules) {
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00001300 Rule.emit(OS);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001301 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001302 }
1303
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001304 OS << " return false;\n"
1305 << "}\n"
1306 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001307}
1308
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001309} // end anonymous namespace
1310
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001311//===----------------------------------------------------------------------===//
1312
1313namespace llvm {
1314void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
1315 GlobalISelEmitter(RK).run(OS);
1316}
1317} // End llvm namespace