blob: d1821b64dd8ff5a4da724d86c6b53b0964af74f4 [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"
Daniel Sanderse7b0d662017-04-21 15:59:56 +000034#include "SubtargetFeatureInfo.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000035#include "llvm/ADT/Optional.h"
Daniel Sanders0ed28822017-04-12 08:23:08 +000036#include "llvm/ADT/SmallSet.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000037#include "llvm/ADT/Statistic.h"
38#include "llvm/CodeGen/MachineValueType.h"
39#include "llvm/Support/CommandLine.h"
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +000040#include "llvm/Support/Error.h"
Daniel Sanders52b4ce72017-03-07 23:20:35 +000041#include "llvm/Support/LowLevelTypeImpl.h"
Pavel Labath52a82e22017-02-21 09:19:41 +000042#include "llvm/Support/ScopedPrinter.h"
Ahmed Bougacha36f70352016-12-21 23:26:20 +000043#include "llvm/TableGen/Error.h"
44#include "llvm/TableGen/Record.h"
45#include "llvm/TableGen/TableGenBackend.h"
46#include <string>
Daniel Sanders8a4bae92017-03-14 21:32:08 +000047#include <numeric>
Ahmed Bougacha36f70352016-12-21 23:26:20 +000048using namespace llvm;
49
50#define DEBUG_TYPE "gisel-emitter"
51
52STATISTIC(NumPatternTotal, "Total number of patterns");
Daniel Sandersb41ce2b2017-02-20 14:31:27 +000053STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
54STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
Ahmed Bougacha36f70352016-12-21 23:26:20 +000055STATISTIC(NumPatternEmitted, "Number of patterns emitted");
56
Daniel Sanders0848b232017-03-27 13:15:13 +000057cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
58
Ahmed Bougacha36f70352016-12-21 23:26:20 +000059static cl::opt<bool> WarnOnSkippedPatterns(
60 "warn-on-skipped-patterns",
61 cl::desc("Explain why a pattern was skipped for inclusion "
62 "in the GlobalISel selector"),
Daniel Sanders0848b232017-03-27 13:15:13 +000063 cl::init(false), cl::cat(GlobalISelEmitterCat));
Ahmed Bougacha36f70352016-12-21 23:26:20 +000064
Daniel Sandersbdfebb82017-03-15 20:18:38 +000065namespace {
Ahmed Bougacha36f70352016-12-21 23:26:20 +000066//===- Helper functions ---------------------------------------------------===//
67
Daniel Sanders52b4ce72017-03-07 23:20:35 +000068/// This class stands in for LLT wherever we want to tablegen-erate an
69/// equivalent at compiler run-time.
70class LLTCodeGen {
71private:
72 LLT Ty;
73
74public:
75 LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
76
Daniel Sanders7aac7cc2017-07-20 09:25:44 +000077 std::string getCxxEnumValue() const {
78 std::string Str;
79 raw_string_ostream OS(Str);
80
81 emitCxxEnumValue(OS);
82 return OS.str();
83 }
84
Daniel Sanders6ab0daa2017-07-04 14:35:06 +000085 void emitCxxEnumValue(raw_ostream &OS) const {
86 if (Ty.isScalar()) {
87 OS << "GILLT_s" << Ty.getSizeInBits();
88 return;
89 }
90 if (Ty.isVector()) {
91 OS << "GILLT_v" << Ty.getNumElements() << "s" << Ty.getScalarSizeInBits();
92 return;
93 }
94 llvm_unreachable("Unhandled LLT");
95 }
96
Daniel Sanders52b4ce72017-03-07 23:20:35 +000097 void emitCxxConstructorCall(raw_ostream &OS) const {
98 if (Ty.isScalar()) {
99 OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
100 return;
101 }
102 if (Ty.isVector()) {
Daniel Sanders32291982017-06-28 13:50:04 +0000103 OS << "LLT::vector(" << Ty.getNumElements() << ", "
104 << Ty.getScalarSizeInBits() << ")";
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000105 return;
106 }
107 llvm_unreachable("Unhandled LLT");
108 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000109
110 const LLT &get() const { return Ty; }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000111
112 /// This ordering is used for std::unique() and std::sort(). There's no
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000113 /// particular logic behind the order.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000114 bool operator<(const LLTCodeGen &Other) const {
115 if (!Ty.isValid())
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000116 return Other.Ty.isValid();
117 if (Ty.isScalar()) {
118 if (!Other.Ty.isValid())
119 return false;
120 if (Other.Ty.isScalar())
121 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000122 return false;
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000123 }
124 if (Ty.isVector()) {
125 if (!Other.Ty.isValid() || Other.Ty.isScalar())
126 return false;
127 if (Other.Ty.isVector()) {
128 if (Ty.getNumElements() < Other.Ty.getNumElements())
129 return true;
130 if (Ty.getNumElements() > Other.Ty.getNumElements())
131 return false;
132 return Ty.getSizeInBits() < Other.Ty.getSizeInBits();
133 }
134 return false;
135 }
136 llvm_unreachable("Unhandled LLT");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000137 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000138};
139
140class InstructionMatcher;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000141/// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
142/// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000143static Optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000144 MVT VT(SVT);
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000145 if (VT.isVector() && VT.getVectorNumElements() != 1)
Daniel Sanders32291982017-06-28 13:50:04 +0000146 return LLTCodeGen(
147 LLT::vector(VT.getVectorNumElements(), VT.getScalarSizeInBits()));
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000148 if (VT.isInteger() || VT.isFloatingPoint())
149 return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
150 return None;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000151}
152
Daniel Sandersd0656a32017-04-13 09:45:37 +0000153static std::string explainPredicates(const TreePatternNode *N) {
154 std::string Explanation = "";
155 StringRef Separator = "";
156 for (const auto &P : N->getPredicateFns()) {
157 Explanation +=
158 (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
159 if (P.isAlwaysTrue())
160 Explanation += " always-true";
161 if (P.isImmediatePattern())
162 Explanation += " immediate";
163 }
164 return Explanation;
165}
166
Daniel Sandersd0656a32017-04-13 09:45:37 +0000167std::string explainOperator(Record *Operator) {
168 if (Operator->isSubClassOf("SDNode"))
Craig Topper2b8419a2017-05-31 19:01:11 +0000169 return (" (" + Operator->getValueAsString("Opcode") + ")").str();
Daniel Sandersd0656a32017-04-13 09:45:37 +0000170
171 if (Operator->isSubClassOf("Intrinsic"))
172 return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
173
174 return " (Operator not understood)";
175}
176
177/// Helper function to let the emitter report skip reason error messages.
178static Error failedImport(const Twine &Reason) {
179 return make_error<StringError>(Reason, inconvertibleErrorCode());
180}
181
182static Error isTrivialOperatorNode(const TreePatternNode *N) {
183 std::string Explanation = "";
184 std::string Separator = "";
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000185 if (N->isLeaf()) {
186 if (isa<IntInit>(N->getLeafValue()))
187 return Error::success();
188
189 Explanation = "Is a leaf";
190 Separator = ", ";
191 }
192
Daniel Sandersd0656a32017-04-13 09:45:37 +0000193 if (N->hasAnyPredicate()) {
194 Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
195 Separator = ", ";
196 }
197
198 if (N->getTransformFn()) {
199 Explanation += Separator + "Has a transform function";
200 Separator = ", ";
201 }
202
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000203 if (!N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn())
Daniel Sandersd0656a32017-04-13 09:45:37 +0000204 return Error::success();
205
206 return failedImport(Explanation);
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000207}
208
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +0000209static Record *getInitValueAsRegClass(Init *V) {
210 if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
211 if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
212 return VDefInit->getDef()->getValueAsDef("RegClass");
213 if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
214 return VDefInit->getDef();
215 }
216 return nullptr;
217}
218
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000219std::string
220getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
221 std::string Name = "GIFBS";
222 for (const auto &Feature : FeatureBitset)
223 Name += ("_" + Feature->getName()).str();
224 return Name;
225}
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000226
227//===- MatchTable Helpers -------------------------------------------------===//
228
229class MatchTable;
230
231/// A record to be stored in a MatchTable.
232///
233/// This class represents any and all output that may be required to emit the
234/// MatchTable. Instances are most often configured to represent an opcode or
235/// value that will be emitted to the table with some formatting but it can also
236/// represent commas, comments, and other formatting instructions.
237struct MatchTableRecord {
238 enum RecordFlagsBits {
239 MTRF_None = 0x0,
240 /// Causes EmitStr to be formatted as comment when emitted.
241 MTRF_Comment = 0x1,
242 /// Causes the record value to be followed by a comma when emitted.
243 MTRF_CommaFollows = 0x2,
244 /// Causes the record value to be followed by a line break when emitted.
245 MTRF_LineBreakFollows = 0x4,
246 /// Indicates that the record defines a label and causes an additional
247 /// comment to be emitted containing the index of the label.
248 MTRF_Label = 0x8,
249 /// Causes the record to be emitted as the index of the label specified by
250 /// LabelID along with a comment indicating where that label is.
251 MTRF_JumpTarget = 0x10,
252 /// Causes the formatter to add a level of indentation before emitting the
253 /// record.
254 MTRF_Indent = 0x20,
255 /// Causes the formatter to remove a level of indentation after emitting the
256 /// record.
257 MTRF_Outdent = 0x40,
258 };
259
260 /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
261 /// reference or define.
262 unsigned LabelID;
263 /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
264 /// value, a label name.
265 std::string EmitStr;
266
267private:
268 /// The number of MatchTable elements described by this record. Comments are 0
269 /// while values are typically 1. Values >1 may occur when we need to emit
270 /// values that exceed the size of a MatchTable element.
271 unsigned NumElements;
272
273public:
274 /// A bitfield of RecordFlagsBits flags.
275 unsigned Flags;
276
277 MatchTableRecord(Optional<unsigned> LabelID_, StringRef EmitStr,
278 unsigned NumElements, unsigned Flags)
279 : LabelID(LabelID_.hasValue() ? LabelID_.getValue() : ~0u),
280 EmitStr(EmitStr), NumElements(NumElements), Flags(Flags) {
281 assert((!LabelID_.hasValue() || LabelID != ~0u) &&
282 "This value is reserved for non-labels");
283 }
284
285 void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
286 const MatchTable &Table) const;
287 unsigned size() const { return NumElements; }
288};
289
290/// Holds the contents of a generated MatchTable to enable formatting and the
291/// necessary index tracking needed to support GIM_Try.
292class MatchTable {
293 /// An unique identifier for the table. The generated table will be named
294 /// MatchTable${ID}.
295 unsigned ID;
296 /// The records that make up the table. Also includes comments describing the
297 /// values being emitted and line breaks to format it.
298 std::vector<MatchTableRecord> Contents;
299 /// The currently defined labels.
300 DenseMap<unsigned, unsigned> LabelMap;
301 /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
302 unsigned CurrentSize;
303
Daniel Sanders8e82af22017-07-27 11:03:45 +0000304 /// A unique identifier for a MatchTable label.
305 static unsigned CurrentLabelID;
306
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000307public:
308 static MatchTableRecord LineBreak;
309 static MatchTableRecord Comment(StringRef Comment) {
310 return MatchTableRecord(None, Comment, 0, MatchTableRecord::MTRF_Comment);
311 }
312 static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
313 unsigned ExtraFlags = 0;
314 if (IndentAdjust > 0)
315 ExtraFlags |= MatchTableRecord::MTRF_Indent;
316 if (IndentAdjust < 0)
317 ExtraFlags |= MatchTableRecord::MTRF_Outdent;
318
319 return MatchTableRecord(None, Opcode, 1,
320 MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
321 }
322 static MatchTableRecord NamedValue(StringRef NamedValue) {
323 return MatchTableRecord(None, NamedValue, 1,
324 MatchTableRecord::MTRF_CommaFollows);
325 }
326 static MatchTableRecord NamedValue(StringRef Namespace,
327 StringRef NamedValue) {
328 return MatchTableRecord(None, (Namespace + "::" + NamedValue).str(), 1,
329 MatchTableRecord::MTRF_CommaFollows);
330 }
331 static MatchTableRecord IntValue(int64_t IntValue) {
332 return MatchTableRecord(None, llvm::to_string(IntValue), 1,
333 MatchTableRecord::MTRF_CommaFollows);
334 }
335 static MatchTableRecord Label(unsigned LabelID) {
336 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
337 MatchTableRecord::MTRF_Label |
338 MatchTableRecord::MTRF_Comment |
339 MatchTableRecord::MTRF_LineBreakFollows);
340 }
341 static MatchTableRecord JumpTarget(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000342 return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000343 MatchTableRecord::MTRF_JumpTarget |
344 MatchTableRecord::MTRF_Comment |
345 MatchTableRecord::MTRF_CommaFollows);
346 }
347
348 MatchTable(unsigned ID) : ID(ID), CurrentSize(0) {}
349
350 void push_back(const MatchTableRecord &Value) {
351 if (Value.Flags & MatchTableRecord::MTRF_Label)
352 defineLabel(Value.LabelID);
353 Contents.push_back(Value);
354 CurrentSize += Value.size();
355 }
356
Daniel Sanders8e82af22017-07-27 11:03:45 +0000357 unsigned allocateLabelID() const { return CurrentLabelID++; }
358
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000359 void defineLabel(unsigned LabelID) {
Daniel Sanders8e82af22017-07-27 11:03:45 +0000360 LabelMap.insert(std::make_pair(LabelID, CurrentSize));
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000361 }
362
363 unsigned getLabelIndex(unsigned LabelID) const {
364 const auto I = LabelMap.find(LabelID);
365 assert(I != LabelMap.end() && "Use of undeclared label");
366 return I->second;
367 }
368
Daniel Sanders8e82af22017-07-27 11:03:45 +0000369 void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
370
371 void emitDeclaration(raw_ostream &OS) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000372 unsigned Indentation = 4;
Daniel Sanderscbbbfe42017-07-27 12:47:31 +0000373 OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000374 LineBreak.emit(OS, true, *this);
375 OS << std::string(Indentation, ' ');
376
377 for (auto I = Contents.begin(), E = Contents.end(); I != E;
378 ++I) {
379 bool LineBreakIsNext = false;
380 const auto &NextI = std::next(I);
381
382 if (NextI != E) {
383 if (NextI->EmitStr == "" &&
384 NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
385 LineBreakIsNext = true;
386 }
387
388 if (I->Flags & MatchTableRecord::MTRF_Indent)
389 Indentation += 2;
390
391 I->emit(OS, LineBreakIsNext, *this);
392 if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
393 OS << std::string(Indentation, ' ');
394
395 if (I->Flags & MatchTableRecord::MTRF_Outdent)
396 Indentation -= 2;
397 }
398 OS << "};\n";
399 }
400};
401
Daniel Sanders8e82af22017-07-27 11:03:45 +0000402unsigned MatchTable::CurrentLabelID = 0;
403
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000404MatchTableRecord MatchTable::LineBreak = {
405 None, "" /* Emit String */, 0 /* Elements */,
406 MatchTableRecord::MTRF_LineBreakFollows};
407
408void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
409 const MatchTable &Table) const {
410 bool UseLineComment =
411 LineBreakIsNextAfterThis | (Flags & MTRF_LineBreakFollows);
412 if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
413 UseLineComment = false;
414
415 if (Flags & MTRF_Comment)
416 OS << (UseLineComment ? "// " : "/*");
417
418 OS << EmitStr;
419 if (Flags & MTRF_Label)
420 OS << ": @" << Table.getLabelIndex(LabelID);
421
422 if (Flags & MTRF_Comment && !UseLineComment)
423 OS << "*/";
424
425 if (Flags & MTRF_JumpTarget) {
426 if (Flags & MTRF_Comment)
427 OS << " ";
428 OS << Table.getLabelIndex(LabelID);
429 }
430
431 if (Flags & MTRF_CommaFollows) {
432 OS << ",";
433 if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
434 OS << " ";
435 }
436
437 if (Flags & MTRF_LineBreakFollows)
438 OS << "\n";
439}
440
441MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
442 Table.push_back(Value);
443 return Table;
444}
445
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000446//===- Matchers -----------------------------------------------------------===//
447
Daniel Sandersbee57392017-04-04 13:25:23 +0000448class OperandMatcher;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000449class MatchAction;
450
451/// Generates code to check that a match rule matches.
452class RuleMatcher {
453 /// A list of matchers that all need to succeed for the current rule to match.
454 /// FIXME: This currently supports a single match position but could be
455 /// extended to support multiple positions to support div/rem fusion or
456 /// load-multiple instructions.
457 std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
458
459 /// A list of actions that need to be taken when all predicates in this rule
460 /// have succeeded.
461 std::vector<std::unique_ptr<MatchAction>> Actions;
462
Daniel Sanders078572b2017-08-02 11:03:36 +0000463 typedef std::map<const InstructionMatcher *, unsigned>
464 DefinedInsnVariablesMap;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000465 /// A map of instruction matchers to the local variables created by
Daniel Sanders9d662d22017-07-06 10:06:12 +0000466 /// emitCaptureOpcodes().
Daniel Sanders078572b2017-08-02 11:03:36 +0000467 DefinedInsnVariablesMap InsnVariableIDs;
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000468
469 /// ID for the next instruction variable defined with defineInsnVar()
470 unsigned NextInsnVarID;
471
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000472 std::vector<Record *> RequiredFeatures;
473
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000474public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000475 RuleMatcher()
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000476 : Matchers(), Actions(), InsnVariableIDs(), NextInsnVarID(0) {}
Zachary Turnerb7dbd872017-03-20 19:56:52 +0000477 RuleMatcher(RuleMatcher &&Other) = default;
478 RuleMatcher &operator=(RuleMatcher &&Other) = default;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000479
Daniel Sanders05540042017-08-08 10:44:31 +0000480 InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
Daniel Sanderse7b0d662017-04-21 15:59:56 +0000481 void addRequiredFeature(Record *Feature);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000482 const std::vector<Record *> &getRequiredFeatures() const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000483
484 template <class Kind, class... Args> Kind &addAction(Args &&... args);
485
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000486 /// Define an instruction without emitting any code to do so.
487 /// This is used for the root of the match.
488 unsigned implicitlyDefineInsnVar(const InstructionMatcher &Matcher);
489 /// Define an instruction and emit corresponding state-machine opcodes.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000490 unsigned defineInsnVar(MatchTable &Table, const InstructionMatcher &Matcher,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000491 unsigned InsnVarID, unsigned OpIdx);
492 unsigned getInsnVarID(const InstructionMatcher &InsnMatcher) const;
Daniel Sanders078572b2017-08-02 11:03:36 +0000493 DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
494 return InsnVariableIDs.begin();
495 }
496 DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
497 return InsnVariableIDs.end();
498 }
499 iterator_range<typename DefinedInsnVariablesMap::const_iterator>
500 defined_insn_vars() const {
501 return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
502 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000503
Daniel Sanders05540042017-08-08 10:44:31 +0000504 const InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
505
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000506 void emitCaptureOpcodes(MatchTable &Table);
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000507
Daniel Sanders8e82af22017-07-27 11:03:45 +0000508 void emit(MatchTable &Table);
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000509
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000510 /// Compare the priority of this object and B.
511 ///
512 /// Returns true if this object is more important than B.
513 bool isHigherPriorityThan(const RuleMatcher &B) const;
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000514
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000515 /// Report the maximum number of temporary operands needed by the rule
516 /// matcher.
517 unsigned countRendererFns() const;
Daniel Sanders2deea182017-04-22 15:11:04 +0000518
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000519 // FIXME: Remove this as soon as possible
520 InstructionMatcher &insnmatcher_front() const { return *Matchers.front(); }
Daniel Sandersbdfebb82017-03-15 20:18:38 +0000521};
522
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000523template <class PredicateTy> class PredicateListMatcher {
524private:
525 typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
526 PredicateVec Predicates;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000527
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000528public:
529 /// Construct a new operand predicate and add it to the matcher.
530 template <class Kind, class... Args>
531 Kind &addPredicate(Args&&... args) {
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000532 Predicates.emplace_back(
533 llvm::make_unique<Kind>(std::forward<Args>(args)...));
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000534 return *static_cast<Kind *>(Predicates.back().get());
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000535 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000536
Daniel Sanders32291982017-06-28 13:50:04 +0000537 typename PredicateVec::const_iterator predicates_begin() const {
538 return Predicates.begin();
539 }
540 typename PredicateVec::const_iterator predicates_end() const {
541 return Predicates.end();
542 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000543 iterator_range<typename PredicateVec::const_iterator> predicates() const {
544 return make_range(predicates_begin(), predicates_end());
545 }
Daniel Sanders32291982017-06-28 13:50:04 +0000546 typename PredicateVec::size_type predicates_size() const {
547 return Predicates.size();
548 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000549
Daniel Sanders9d662d22017-07-06 10:06:12 +0000550 /// Emit MatchTable opcodes that tests whether all the predicates are met.
Ahmed Bougachab67a3ce2017-01-26 22:07:37 +0000551 template <class... Args>
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000552 void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) const {
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000553 if (Predicates.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000554 Table << MatchTable::Comment("No predicates") << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000555 return;
556 }
557
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000558 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000559 Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000560 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000561};
562
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000563/// Generates code to check a predicate of an operand.
564///
565/// Typical predicates include:
566/// * Operand is a particular register.
567/// * Operand is assigned a particular register bank.
568/// * Operand is an MBB.
569class OperandPredicateMatcher {
570public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000571 /// This enum is used for RTTI and also defines the priority that is given to
572 /// the predicate when generating the matcher code. Kinds with higher priority
573 /// must be tested first.
574 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000575 /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
576 /// but OPM_Int must have priority over OPM_RegBank since constant integers
577 /// are represented by a virtual register defined by a G_CONSTANT instruction.
Daniel Sanders759ff412017-02-24 13:58:11 +0000578 enum PredicateKind {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000579 OPM_ComplexPattern,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000580 OPM_IntrinsicID,
Daniel Sanders05540042017-08-08 10:44:31 +0000581 OPM_Instruction,
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000582 OPM_Int,
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000583 OPM_LiteralInt,
Daniel Sanders759ff412017-02-24 13:58:11 +0000584 OPM_LLT,
585 OPM_RegBank,
586 OPM_MBB,
587 };
588
589protected:
590 PredicateKind Kind;
591
592public:
593 OperandPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000594 virtual ~OperandPredicateMatcher() {}
595
Daniel Sanders759ff412017-02-24 13:58:11 +0000596 PredicateKind getKind() const { return Kind; }
597
Daniel Sandersbee57392017-04-04 13:25:23 +0000598 /// Return the OperandMatcher for the specified operand or nullptr if there
599 /// isn't one by that name in this operand predicate matcher.
600 ///
601 /// InstructionOperandMatcher is the only subclass that can return non-null
602 /// for this.
603 virtual Optional<const OperandMatcher *>
Daniel Sandersdb7ed372017-04-04 13:52:00 +0000604 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000605 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
606 return None;
607 }
608
Daniel Sanders9d662d22017-07-06 10:06:12 +0000609 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sandersbee57392017-04-04 13:25:23 +0000610 ///
Daniel Sanders9d662d22017-07-06 10:06:12 +0000611 /// Only InstructionOperandMatcher needs to do anything for this method the
612 /// rest just walk the tree.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000613 virtual void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000614 unsigned InsnVarID, unsigned OpIdx) const {}
Daniel Sandersbee57392017-04-04 13:25:23 +0000615
Daniel Sanders9d662d22017-07-06 10:06:12 +0000616 /// Emit MatchTable opcodes that check the predicate for the given operand.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000617 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000618 unsigned InsnVarID,
619 unsigned OpIdx) const = 0;
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.
Daniel Sanders05540042017-08-08 10:44:31 +0000624 virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000625
626 /// Report the maximum number of temporary operands needed by the predicate
627 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000628 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000629};
630
631/// Generates code to check that an operand is a particular LLT.
632class LLTOperandMatcher : public OperandPredicateMatcher {
633protected:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000634 LLTCodeGen Ty;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000635
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000636public:
Daniel Sanders52b4ce72017-03-07 23:20:35 +0000637 LLTOperandMatcher(const LLTCodeGen &Ty)
Daniel Sanderseb2f5f32017-08-15 15:10:31 +0000638 : OperandPredicateMatcher(OPM_LLT), Ty(Ty) {}
Daniel Sanders759ff412017-02-24 13:58:11 +0000639
640 static bool classof(const OperandPredicateMatcher *P) {
641 return P->getKind() == OPM_LLT;
642 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000643
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000644 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000645 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000646 Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
647 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
648 << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
649 << MatchTable::NamedValue(Ty.getCxxEnumValue())
650 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000651 }
652};
653
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000654/// Generates code to check that an operand is a particular target constant.
655class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
656protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000657 const OperandMatcher &Operand;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000658 const Record &TheDef;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000659
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000660 unsigned getAllocatedTemporariesBaseID() const;
661
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000662public:
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000663 ComplexPatternOperandMatcher(const OperandMatcher &Operand,
664 const Record &TheDef)
665 : OperandPredicateMatcher(OPM_ComplexPattern), Operand(Operand),
666 TheDef(TheDef) {}
667
668 static bool classof(const OperandPredicateMatcher *P) {
669 return P->getKind() == OPM_ComplexPattern;
670 }
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000671
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000672 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000673 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders2deea182017-04-22 15:11:04 +0000674 unsigned ID = getAllocatedTemporariesBaseID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000675 Table << MatchTable::Opcode("GIM_CheckComplexPattern")
676 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
677 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
678 << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
679 << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
680 << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000681 }
682
Daniel Sanders2deea182017-04-22 15:11:04 +0000683 unsigned countRendererFns() const override {
684 return 1;
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000685 }
686};
687
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000688/// Generates code to check that an operand is in a particular register bank.
689class RegisterBankOperandMatcher : public OperandPredicateMatcher {
690protected:
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000691 const CodeGenRegisterClass &RC;
692
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000693public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000694 RegisterBankOperandMatcher(const CodeGenRegisterClass &RC)
695 : OperandPredicateMatcher(OPM_RegBank), RC(RC) {}
696
697 static bool classof(const OperandPredicateMatcher *P) {
698 return P->getKind() == OPM_RegBank;
699 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000700
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000701 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000702 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000703 Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
704 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
705 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
706 << MatchTable::Comment("RC")
707 << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
708 << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000709 }
710};
711
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000712/// Generates code to check that an operand is a basic block.
713class MBBOperandMatcher : public OperandPredicateMatcher {
714public:
Daniel Sanders759ff412017-02-24 13:58:11 +0000715 MBBOperandMatcher() : OperandPredicateMatcher(OPM_MBB) {}
716
717 static bool classof(const OperandPredicateMatcher *P) {
718 return P->getKind() == OPM_MBB;
719 }
720
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000721 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000722 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000723 Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
724 << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
725 << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000726 }
727};
728
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000729/// Generates code to check that an operand is a G_CONSTANT with a particular
730/// int.
731class ConstantIntOperandMatcher : public OperandPredicateMatcher {
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000732protected:
733 int64_t Value;
734
735public:
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000736 ConstantIntOperandMatcher(int64_t Value)
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000737 : OperandPredicateMatcher(OPM_Int), Value(Value) {}
738
739 static bool classof(const OperandPredicateMatcher *P) {
740 return P->getKind() == OPM_Int;
741 }
742
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000743 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000744 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000745 Table << MatchTable::Opcode("GIM_CheckConstantInt")
746 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
747 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
748 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000749 }
750};
751
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000752/// Generates code to check that an operand is a raw int (where MO.isImm() or
753/// MO.isCImm() is true).
754class LiteralIntOperandMatcher : public OperandPredicateMatcher {
755protected:
756 int64_t Value;
757
758public:
759 LiteralIntOperandMatcher(int64_t Value)
760 : OperandPredicateMatcher(OPM_LiteralInt), Value(Value) {}
761
762 static bool classof(const OperandPredicateMatcher *P) {
763 return P->getKind() == OPM_LiteralInt;
764 }
765
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000766 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000767 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000768 Table << MatchTable::Opcode("GIM_CheckLiteralInt")
769 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
770 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
771 << MatchTable::IntValue(Value) << MatchTable::LineBreak;
Daniel Sanders452c8ae2017-05-23 19:33:16 +0000772 }
773};
774
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000775/// Generates code to check that an operand is an intrinsic ID.
776class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
777protected:
778 const CodeGenIntrinsic *II;
779
780public:
781 IntrinsicIDOperandMatcher(const CodeGenIntrinsic *II)
782 : OperandPredicateMatcher(OPM_IntrinsicID), II(II) {}
783
784 static bool classof(const OperandPredicateMatcher *P) {
785 return P->getKind() == OPM_IntrinsicID;
786 }
787
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000788 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000789 unsigned InsnVarID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000790 Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
791 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
792 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
793 << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
794 << MatchTable::LineBreak;
Daniel Sandersfe12c0f2017-07-11 08:57:29 +0000795 }
796};
797
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000798/// Generates code to check that a set of predicates match for a particular
799/// operand.
800class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
801protected:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000802 InstructionMatcher &Insn;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000803 unsigned OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000804 std::string SymbolicName;
Ahmed Bougacha36f70352016-12-21 23:26:20 +0000805
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000806 /// The index of the first temporary variable allocated to this operand. The
807 /// number of allocated temporaries can be found with
Daniel Sanders2deea182017-04-22 15:11:04 +0000808 /// countRendererFns().
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000809 unsigned AllocatedTemporariesBaseID;
810
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000811public:
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000812 OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000813 const std::string &SymbolicName,
814 unsigned AllocatedTemporariesBaseID)
815 : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
816 AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000817
818 bool hasSymbolicName() const { return !SymbolicName.empty(); }
819 const StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sandersffc7d582017-03-29 15:37:18 +0000820 void setSymbolicName(StringRef Name) {
821 assert(SymbolicName.empty() && "Operand already has a symbolic name");
822 SymbolicName = Name;
823 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000824 unsigned getOperandIndex() const { return OpIdx; }
825
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000826 std::string getOperandExpr(unsigned InsnVarID) const {
827 return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
828 llvm::to_string(OpIdx) + ")";
Daniel Sanderse604ef52017-02-20 15:30:43 +0000829 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000830
Daniel Sandersbee57392017-04-04 13:25:23 +0000831 Optional<const OperandMatcher *>
832 getOptionalOperand(StringRef DesiredSymbolicName) const {
833 assert(!DesiredSymbolicName.empty() && "Cannot lookup unnamed operand");
834 if (DesiredSymbolicName == SymbolicName)
835 return this;
836 for (const auto &OP : predicates()) {
837 const auto &MaybeOperand = OP->getOptionalOperand(DesiredSymbolicName);
838 if (MaybeOperand.hasValue())
839 return MaybeOperand.getValue();
840 }
841 return None;
842 }
843
Daniel Sandersb96f40d2017-03-20 15:20:42 +0000844 InstructionMatcher &getInstructionMatcher() const { return Insn; }
845
Daniel Sanders9d662d22017-07-06 10:06:12 +0000846 /// Emit MatchTable opcodes to capture instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000847 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +0000848 unsigned InsnVarID) const {
Daniel Sandersbee57392017-04-04 13:25:23 +0000849 for (const auto &Predicate : predicates())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000850 Predicate->emitCaptureOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +0000851 }
852
Daniel Sanders9d662d22017-07-06 10:06:12 +0000853 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000854 /// InsnVarID matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000855 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000856 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000857 std::string Comment;
858 raw_string_ostream CommentOS(Comment);
859 CommentOS << "MIs[" << InsnVarID << "] ";
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000860 if (SymbolicName.empty())
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000861 CommentOS << "Operand " << OpIdx;
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000862 else
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000863 CommentOS << SymbolicName;
864 Table << MatchTable::Comment(CommentOS.str()) << MatchTable::LineBreak;
865
866 emitPredicateListOpcodes(Table, Rule, InsnVarID, OpIdx);
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000867 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000868
869 /// Compare the priority of this object and B.
870 ///
871 /// Returns true if this object is more important than B.
872 bool isHigherPriorityThan(const OperandMatcher &B) const {
873 // Operand matchers involving more predicates have higher priority.
874 if (predicates_size() > B.predicates_size())
875 return true;
876 if (predicates_size() < B.predicates_size())
877 return false;
878
879 // This assumes that predicates are added in a consistent order.
880 for (const auto &Predicate : zip(predicates(), B.predicates())) {
881 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
882 return true;
883 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
884 return false;
885 }
886
887 return false;
888 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000889
890 /// Report the maximum number of temporary operands needed by the operand
891 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000892 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000893 return std::accumulate(
894 predicates().begin(), predicates().end(), 0,
895 [](unsigned A,
896 const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +0000897 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000898 });
899 }
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000900
901 unsigned getAllocatedTemporariesBaseID() const {
902 return AllocatedTemporariesBaseID;
903 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000904};
905
Daniel Sanders4f3eb242017-04-05 13:14:03 +0000906unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
907 return Operand.getAllocatedTemporariesBaseID();
908}
909
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000910/// Generates code to check a predicate on an instruction.
911///
912/// Typical predicates include:
913/// * The opcode of the instruction is a particular value.
914/// * The nsw/nuw flag is/isn't set.
915class InstructionPredicateMatcher {
Daniel Sanders759ff412017-02-24 13:58:11 +0000916protected:
917 /// This enum is used for RTTI and also defines the priority that is given to
918 /// the predicate when generating the matcher code. Kinds with higher priority
919 /// must be tested first.
920 enum PredicateKind {
921 IPM_Opcode,
922 };
923
924 PredicateKind Kind;
925
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000926public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000927 InstructionPredicateMatcher(PredicateKind Kind) : Kind(Kind) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000928 virtual ~InstructionPredicateMatcher() {}
929
Daniel Sanders759ff412017-02-24 13:58:11 +0000930 PredicateKind getKind() const { return Kind; }
931
Daniel Sanders9d662d22017-07-06 10:06:12 +0000932 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000933 /// InsnVarID matches the predicate.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000934 virtual void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000935 unsigned InsnVarID) const = 0;
Daniel Sanders759ff412017-02-24 13:58:11 +0000936
937 /// Compare the priority of this object and B.
938 ///
939 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000940 virtual bool
941 isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
Daniel Sanders759ff412017-02-24 13:58:11 +0000942 return Kind < B.Kind;
943 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +0000944
945 /// Report the maximum number of temporary operands needed by the predicate
946 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +0000947 virtual unsigned countRendererFns() const { return 0; }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000948};
949
950/// Generates code to check the opcode of an instruction.
951class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
952protected:
953 const CodeGenInstruction *I;
954
955public:
Daniel Sanders8d4d72f2017-02-24 14:53:35 +0000956 InstructionOpcodeMatcher(const CodeGenInstruction *I)
957 : InstructionPredicateMatcher(IPM_Opcode), I(I) {}
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000958
Daniel Sanders759ff412017-02-24 13:58:11 +0000959 static bool classof(const InstructionPredicateMatcher *P) {
960 return P->getKind() == IPM_Opcode;
961 }
962
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000963 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +0000964 unsigned InsnVarID) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +0000965 Table << MatchTable::Opcode("GIM_CheckOpcode") << MatchTable::Comment("MI")
966 << MatchTable::IntValue(InsnVarID)
967 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
968 << MatchTable::LineBreak;
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000969 }
Daniel Sanders759ff412017-02-24 13:58:11 +0000970
971 /// Compare the priority of this object and B.
972 ///
Daniel Sanders066ebbf2017-02-24 15:43:30 +0000973 /// Returns true if this object is more important than B.
Daniel Sanders32291982017-06-28 13:50:04 +0000974 bool
975 isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
Daniel Sanders759ff412017-02-24 13:58:11 +0000976 if (InstructionPredicateMatcher::isHigherPriorityThan(B))
977 return true;
978 if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
979 return false;
980
981 // Prioritize opcodes for cosmetic reasons in the generated source. Although
982 // this is cosmetic at the moment, we may want to drive a similar ordering
983 // using instruction frequency information to improve compile time.
984 if (const InstructionOpcodeMatcher *BO =
985 dyn_cast<InstructionOpcodeMatcher>(&B))
986 return I->TheDef->getName() < BO->I->TheDef->getName();
987
988 return false;
989 };
Daniel Sanders05540042017-08-08 10:44:31 +0000990
991 bool isConstantInstruction() const {
992 return I->TheDef->getName() == "G_CONSTANT";
993 }
Daniel Sandersdc662ff2017-01-26 11:10:14 +0000994};
995
996/// Generates code to check that a set of predicates and operands match for a
997/// particular instruction.
998///
999/// Typical predicates include:
1000/// * Has a specific opcode.
1001/// * Has an nsw/nuw flag or doesn't.
1002class InstructionMatcher
1003 : public PredicateListMatcher<InstructionPredicateMatcher> {
1004protected:
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001005 typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001006
1007 /// The operands to match. All rendered operands must be present even if the
1008 /// condition is always true.
1009 OperandVec Operands;
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001010
Daniel Sanders05540042017-08-08 10:44:31 +00001011 std::string SymbolicName;
1012
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001013public:
Daniel Sanders05540042017-08-08 10:44:31 +00001014 InstructionMatcher(StringRef SymbolicName) : SymbolicName(SymbolicName) {}
1015
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001016 /// Add an operand to the matcher.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001017 OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
1018 unsigned AllocatedTemporariesBaseID) {
1019 Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
1020 AllocatedTemporariesBaseID));
1021 return *Operands.back();
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001022 }
1023
Daniel Sandersffc7d582017-03-29 15:37:18 +00001024 OperandMatcher &getOperand(unsigned OpIdx) {
1025 auto I = std::find_if(Operands.begin(), Operands.end(),
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001026 [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
1027 return X->getOperandIndex() == OpIdx;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001028 });
1029 if (I != Operands.end())
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001030 return **I;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001031 llvm_unreachable("Failed to lookup operand");
1032 }
1033
Daniel Sandersbee57392017-04-04 13:25:23 +00001034 Optional<const OperandMatcher *>
1035 getOptionalOperand(StringRef SymbolicName) const {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001036 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
Daniel Sandersbee57392017-04-04 13:25:23 +00001037 for (const auto &Operand : Operands) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001038 const auto &OM = Operand->getOptionalOperand(SymbolicName);
Daniel Sandersbee57392017-04-04 13:25:23 +00001039 if (OM.hasValue())
1040 return OM.getValue();
1041 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001042 return None;
1043 }
1044
Daniel Sandersdb7ed372017-04-04 13:52:00 +00001045 const OperandMatcher &getOperand(StringRef SymbolicName) const {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001046 Optional<const OperandMatcher *>OM = getOptionalOperand(SymbolicName);
1047 if (OM.hasValue())
1048 return *OM.getValue();
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001049 llvm_unreachable("Failed to lookup operand");
1050 }
1051
Daniel Sanders05540042017-08-08 10:44:31 +00001052 StringRef getSymbolicName() const { return SymbolicName; }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001053 unsigned getNumOperands() const { return Operands.size(); }
Daniel Sandersbee57392017-04-04 13:25:23 +00001054 OperandVec::iterator operands_begin() { return Operands.begin(); }
1055 OperandVec::iterator operands_end() { return Operands.end(); }
1056 iterator_range<OperandVec::iterator> operands() {
1057 return make_range(operands_begin(), operands_end());
1058 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001059 OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
1060 OperandVec::const_iterator operands_end() const { return Operands.end(); }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001061 iterator_range<OperandVec::const_iterator> operands() const {
1062 return make_range(operands_begin(), operands_end());
1063 }
1064
Daniel Sanders9d662d22017-07-06 10:06:12 +00001065 /// Emit MatchTable opcodes to check the shape of the match and capture
1066 /// instructions into the MIs table.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001067 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001068 unsigned InsnID) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001069 Table << MatchTable::Opcode("GIM_CheckNumOperands")
1070 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1071 << MatchTable::Comment("Expected")
1072 << MatchTable::IntValue(getNumOperands()) << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001073 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001074 Operand->emitCaptureOpcodes(Table, Rule, InsnID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001075 }
1076
Daniel Sanders9d662d22017-07-06 10:06:12 +00001077 /// Emit MatchTable opcodes that test whether the instruction named in
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001078 /// InsnVarName matches all the predicates and all the operands.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001079 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001080 unsigned InsnVarID) const {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001081 emitPredicateListOpcodes(Table, Rule, InsnVarID);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001082 for (const auto &Operand : Operands)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001083 Operand->emitPredicateOpcodes(Table, Rule, InsnVarID);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001084 }
Daniel Sanders759ff412017-02-24 13:58:11 +00001085
1086 /// Compare the priority of this object and B.
1087 ///
1088 /// Returns true if this object is more important than B.
1089 bool isHigherPriorityThan(const InstructionMatcher &B) const {
1090 // Instruction matchers involving more operands have higher priority.
1091 if (Operands.size() > B.Operands.size())
1092 return true;
1093 if (Operands.size() < B.Operands.size())
1094 return false;
1095
1096 for (const auto &Predicate : zip(predicates(), B.predicates())) {
1097 if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
1098 return true;
1099 if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
1100 return false;
1101 }
1102
1103 for (const auto &Operand : zip(Operands, B.Operands)) {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001104 if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001105 return true;
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001106 if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
Daniel Sanders759ff412017-02-24 13:58:11 +00001107 return false;
1108 }
1109
1110 return false;
1111 };
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001112
1113 /// Report the maximum number of temporary operands needed by the instruction
1114 /// matcher.
Daniel Sanders2deea182017-04-22 15:11:04 +00001115 unsigned countRendererFns() const {
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001116 return std::accumulate(predicates().begin(), predicates().end(), 0,
1117 [](unsigned A,
1118 const std::unique_ptr<InstructionPredicateMatcher>
1119 &Predicate) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001120 return A + Predicate->countRendererFns();
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001121 }) +
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001122 std::accumulate(
1123 Operands.begin(), Operands.end(), 0,
1124 [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001125 return A + Operand->countRendererFns();
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001126 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001127 }
Daniel Sanders05540042017-08-08 10:44:31 +00001128
1129 bool isConstantInstruction() const {
1130 for (const auto &P : predicates())
1131 if (const InstructionOpcodeMatcher *Opcode =
1132 dyn_cast<InstructionOpcodeMatcher>(P.get()))
1133 return Opcode->isConstantInstruction();
1134 return false;
1135 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001136};
1137
Daniel Sandersbee57392017-04-04 13:25:23 +00001138/// Generates code to check that the operand is a register defined by an
1139/// instruction that matches the given instruction matcher.
1140///
1141/// For example, the pattern:
1142/// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
1143/// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
1144/// the:
1145/// (G_ADD $src1, $src2)
1146/// subpattern.
1147class InstructionOperandMatcher : public OperandPredicateMatcher {
1148protected:
1149 std::unique_ptr<InstructionMatcher> InsnMatcher;
1150
1151public:
Daniel Sanders05540042017-08-08 10:44:31 +00001152 InstructionOperandMatcher(StringRef SymbolicName)
Daniel Sandersbee57392017-04-04 13:25:23 +00001153 : OperandPredicateMatcher(OPM_Instruction),
Daniel Sanders05540042017-08-08 10:44:31 +00001154 InsnMatcher(new InstructionMatcher(SymbolicName)) {}
Daniel Sandersbee57392017-04-04 13:25:23 +00001155
1156 static bool classof(const OperandPredicateMatcher *P) {
1157 return P->getKind() == OPM_Instruction;
1158 }
1159
1160 InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
1161
1162 Optional<const OperandMatcher *>
1163 getOptionalOperand(StringRef SymbolicName) const override {
1164 assert(!SymbolicName.empty() && "Cannot lookup unnamed operand");
1165 return InsnMatcher->getOptionalOperand(SymbolicName);
1166 }
1167
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001168 void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders9d662d22017-07-06 10:06:12 +00001169 unsigned InsnID, unsigned OpIdx) const override {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001170 unsigned InsnVarID = Rule.defineInsnVar(Table, *InsnMatcher, InsnID, OpIdx);
1171 InsnMatcher->emitCaptureOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001172 }
1173
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001174 void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001175 unsigned InsnVarID_,
1176 unsigned OpIdx_) const override {
1177 unsigned InsnVarID = Rule.getInsnVarID(*InsnMatcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001178 InsnMatcher->emitPredicateOpcodes(Table, Rule, InsnVarID);
Daniel Sandersbee57392017-04-04 13:25:23 +00001179 }
1180};
1181
Daniel Sanders43c882c2017-02-01 10:53:10 +00001182//===- Actions ------------------------------------------------------------===//
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001183class OperandRenderer {
1184public:
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001185 enum RendererKind {
1186 OR_Copy,
1187 OR_CopySubReg,
Daniel Sanders05540042017-08-08 10:44:31 +00001188 OR_CopyConstantAsImm,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001189 OR_Imm,
1190 OR_Register,
1191 OR_ComplexPattern
1192 };
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001193
1194protected:
1195 RendererKind Kind;
1196
1197public:
1198 OperandRenderer(RendererKind Kind) : Kind(Kind) {}
1199 virtual ~OperandRenderer() {}
1200
1201 RendererKind getKind() const { return Kind; }
1202
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001203 virtual void emitRenderOpcodes(MatchTable &Table,
1204 RuleMatcher &Rule) const = 0;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001205};
1206
1207/// A CopyRenderer emits code to copy a single operand from an existing
1208/// instruction to the one being built.
1209class CopyRenderer : public OperandRenderer {
1210protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001211 unsigned NewInsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001212 /// The matcher for the instruction that this operand is copied from.
1213 /// This provides the facility for looking up an a operand by it's name so
1214 /// that it can be used as a source for the instruction being built.
1215 const InstructionMatcher &Matched;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001216 /// The name of the operand.
1217 const StringRef SymbolicName;
1218
1219public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001220 CopyRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1221 StringRef SymbolicName)
1222 : OperandRenderer(OR_Copy), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanders05540042017-08-08 10:44:31 +00001223 SymbolicName(SymbolicName) {
1224 assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
1225 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001226
1227 static bool classof(const OperandRenderer *R) {
1228 return R->getKind() == OR_Copy;
1229 }
1230
1231 const StringRef getSymbolicName() const { return SymbolicName; }
1232
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001233 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001234 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001235 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001236 Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
1237 << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
1238 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1239 << MatchTable::IntValue(Operand.getOperandIndex())
1240 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001241 }
1242};
1243
Daniel Sanders05540042017-08-08 10:44:31 +00001244/// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
1245/// an extended immediate operand.
1246class CopyConstantAsImmRenderer : public OperandRenderer {
1247protected:
1248 unsigned NewInsnID;
1249 /// The name of the operand.
1250 const std::string SymbolicName;
1251 bool Signed;
1252
1253public:
1254 CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
1255 : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
1256 SymbolicName(SymbolicName), Signed(true) {}
1257
1258 static bool classof(const OperandRenderer *R) {
1259 return R->getKind() == OR_CopyConstantAsImm;
1260 }
1261
1262 const StringRef getSymbolicName() const { return SymbolicName; }
1263
1264 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1265 const InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
1266 unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
1267 Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
1268 : "GIR_CopyConstantAsUImm")
1269 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1270 << MatchTable::Comment("OldInsnID")
1271 << MatchTable::IntValue(OldInsnVarID)
1272 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
1273 }
1274};
1275
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001276/// A CopySubRegRenderer emits code to copy a single register operand from an
1277/// existing instruction to the one being built and indicate that only a
1278/// subregister should be copied.
1279class CopySubRegRenderer : public OperandRenderer {
1280protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001281 unsigned NewInsnID;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001282 /// The matcher for the instruction that this operand is copied from.
1283 /// This provides the facility for looking up an a operand by it's name so
1284 /// that it can be used as a source for the instruction being built.
1285 const InstructionMatcher &Matched;
1286 /// The name of the operand.
1287 const StringRef SymbolicName;
1288 /// The subregister to extract.
1289 const CodeGenSubRegIndex *SubReg;
1290
1291public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001292 CopySubRegRenderer(unsigned NewInsnID, const InstructionMatcher &Matched,
1293 StringRef SymbolicName, const CodeGenSubRegIndex *SubReg)
1294 : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID), Matched(Matched),
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001295 SymbolicName(SymbolicName), SubReg(SubReg) {}
1296
1297 static bool classof(const OperandRenderer *R) {
1298 return R->getKind() == OR_CopySubReg;
1299 }
1300
1301 const StringRef getSymbolicName() const { return SymbolicName; }
1302
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001303 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001304 const OperandMatcher &Operand = Matched.getOperand(SymbolicName);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001305 unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001306 Table << MatchTable::Opcode("GIR_CopySubReg")
1307 << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
1308 << MatchTable::Comment("OldInsnID")
1309 << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
1310 << MatchTable::IntValue(Operand.getOperandIndex())
1311 << MatchTable::Comment("SubRegIdx")
1312 << MatchTable::IntValue(SubReg->EnumValue)
1313 << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001314 }
1315};
1316
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001317/// Adds a specific physical register to the instruction being built.
1318/// This is typically useful for WZR/XZR on AArch64.
1319class AddRegisterRenderer : public OperandRenderer {
1320protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001321 unsigned InsnID;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001322 const Record *RegisterDef;
1323
1324public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001325 AddRegisterRenderer(unsigned InsnID, const Record *RegisterDef)
1326 : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef) {
1327 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001328
1329 static bool classof(const OperandRenderer *R) {
1330 return R->getKind() == OR_Register;
1331 }
1332
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001333 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1334 Table << MatchTable::Opcode("GIR_AddRegister")
1335 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1336 << MatchTable::NamedValue(
1337 (RegisterDef->getValue("Namespace")
1338 ? RegisterDef->getValueAsString("Namespace")
1339 : ""),
1340 RegisterDef->getName())
1341 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001342 }
1343};
1344
Daniel Sanders0ed28822017-04-12 08:23:08 +00001345/// Adds a specific immediate to the instruction being built.
1346class ImmRenderer : public OperandRenderer {
1347protected:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001348 unsigned InsnID;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001349 int64_t Imm;
1350
1351public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001352 ImmRenderer(unsigned InsnID, int64_t Imm)
1353 : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
Daniel Sanders0ed28822017-04-12 08:23:08 +00001354
1355 static bool classof(const OperandRenderer *R) {
1356 return R->getKind() == OR_Imm;
1357 }
1358
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001359 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1360 Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
1361 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
1362 << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
Daniel Sanders0ed28822017-04-12 08:23:08 +00001363 }
1364};
1365
Daniel Sanders2deea182017-04-22 15:11:04 +00001366/// Adds operands by calling a renderer function supplied by the ComplexPattern
1367/// matcher function.
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001368class RenderComplexPatternOperand : public OperandRenderer {
1369private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001370 unsigned InsnID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001371 const Record &TheDef;
Daniel Sanders2deea182017-04-22 15:11:04 +00001372 /// The name of the operand.
1373 const StringRef SymbolicName;
1374 /// The renderer number. This must be unique within a rule since it's used to
1375 /// identify a temporary variable to hold the renderer function.
1376 unsigned RendererID;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001377
1378 unsigned getNumOperands() const {
1379 return TheDef.getValueAsDag("Operands")->getNumArgs();
1380 }
1381
1382public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001383 RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
1384 StringRef SymbolicName, unsigned RendererID)
1385 : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
Daniel Sanders2deea182017-04-22 15:11:04 +00001386 SymbolicName(SymbolicName), RendererID(RendererID) {}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001387
1388 static bool classof(const OperandRenderer *R) {
1389 return R->getKind() == OR_ComplexPattern;
1390 }
1391
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001392 void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
1393 Table << MatchTable::Opcode("GIR_ComplexRenderer")
1394 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1395 << MatchTable::Comment("RendererID")
1396 << MatchTable::IntValue(RendererID) << MatchTable::LineBreak;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001397 }
1398};
1399
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001400/// An action taken when all Matcher predicates succeeded for a parent rule.
1401///
1402/// Typical actions include:
1403/// * Changing the opcode of an instruction.
1404/// * Adding an operand to an instruction.
Daniel Sanders43c882c2017-02-01 10:53:10 +00001405class MatchAction {
1406public:
1407 virtual ~MatchAction() {}
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001408
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001409 /// Emit the MatchTable opcodes to implement the action.
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001410 ///
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001411 /// \param RecycleInsnID If given, it's an instruction to recycle. The
1412 /// requirements on the instruction vary from action to
1413 /// action.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001414 virtual void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1415 unsigned RecycleInsnID) const = 0;
Daniel Sanders43c882c2017-02-01 10:53:10 +00001416};
1417
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001418/// Generates a comment describing the matched rule being acted upon.
1419class DebugCommentAction : public MatchAction {
1420private:
1421 const PatternToMatch &P;
1422
1423public:
1424 DebugCommentAction(const PatternToMatch &P) : P(P) {}
1425
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001426 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1427 unsigned RecycleInsnID) const override {
1428 Table << MatchTable::Comment(llvm::to_string(*P.getSrcPattern()) + " => " +
1429 llvm::to_string(*P.getDstPattern()))
1430 << MatchTable::LineBreak;
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00001431 }
1432};
1433
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001434/// Generates code to build an instruction or mutate an existing instruction
1435/// into the desired instruction when this is possible.
1436class BuildMIAction : public MatchAction {
Daniel Sanders43c882c2017-02-01 10:53:10 +00001437private:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001438 unsigned InsnID;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001439 const CodeGenInstruction *I;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001440 const InstructionMatcher &Matched;
1441 std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
1442
1443 /// True if the instruction can be built solely by mutating the opcode.
1444 bool canMutate() const {
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001445 if (OperandRenderers.size() != Matched.getNumOperands())
1446 return false;
1447
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001448 for (const auto &Renderer : enumerate(OperandRenderers)) {
Zachary Turner309a0882017-03-13 16:24:10 +00001449 if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
Daniel Sanders3016d3c2017-04-22 14:31:28 +00001450 const OperandMatcher &OM = Matched.getOperand(Copy->getSymbolicName());
1451 if (&Matched != &OM.getInstructionMatcher() ||
1452 OM.getOperandIndex() != Renderer.index())
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001453 return false;
1454 } else
1455 return false;
1456 }
1457
1458 return true;
1459 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001460
Daniel Sanders43c882c2017-02-01 10:53:10 +00001461public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001462 BuildMIAction(unsigned InsnID, const CodeGenInstruction *I,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001463 const InstructionMatcher &Matched)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001464 : InsnID(InsnID), I(I), Matched(Matched) {}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001465
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001466 template <class Kind, class... Args>
1467 Kind &addRenderer(Args&&... args) {
1468 OperandRenderers.emplace_back(
1469 llvm::make_unique<Kind>(std::forward<Args>(args)...));
1470 return *static_cast<Kind *>(OperandRenderers.back().get());
1471 }
1472
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001473 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1474 unsigned RecycleInsnID) const override {
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001475 if (canMutate()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001476 Table << MatchTable::Opcode("GIR_MutateOpcode")
1477 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1478 << MatchTable::Comment("RecycleInsnID")
1479 << MatchTable::IntValue(RecycleInsnID)
1480 << MatchTable::Comment("Opcode")
1481 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1482 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001483
1484 if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
Tim Northover4340d642017-03-20 21:58:23 +00001485 for (auto Def : I->ImplicitDefs) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001486 auto Namespace = Def->getValue("Namespace")
1487 ? Def->getValueAsString("Namespace")
1488 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001489 Table << MatchTable::Opcode("GIR_AddImplicitDef")
1490 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1491 << MatchTable::NamedValue(Namespace, Def->getName())
1492 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001493 }
1494 for (auto Use : I->ImplicitUses) {
Diana Picus8abcbbb2017-05-02 09:40:49 +00001495 auto Namespace = Use->getValue("Namespace")
1496 ? Use->getValueAsString("Namespace")
1497 : "";
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001498 Table << MatchTable::Opcode("GIR_AddImplicitUse")
1499 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1500 << MatchTable::NamedValue(Namespace, Use->getName())
1501 << MatchTable::LineBreak;
Tim Northover4340d642017-03-20 21:58:23 +00001502 }
1503 }
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001504 return;
1505 }
1506
1507 // TODO: Simple permutation looks like it could be almost as common as
1508 // mutation due to commutative operations.
1509
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001510 Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
1511 << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
1512 << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
1513 << MatchTable::LineBreak;
Daniel Sanders066ebbf2017-02-24 15:43:30 +00001514 for (const auto &Renderer : OperandRenderers)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001515 Renderer->emitRenderOpcodes(Table, Rule);
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001516
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001517 if (I->mayLoad || I->mayStore) {
1518 Table << MatchTable::Opcode("GIR_MergeMemOperands")
1519 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1520 << MatchTable::Comment("MergeInsnID's");
1521 // Emit the ID's for all the instructions that are matched by this rule.
1522 // TODO: Limit this to matched instructions that mayLoad/mayStore or have
1523 // some other means of having a memoperand. Also limit this to
1524 // emitted instructions that expect to have a memoperand too. For
1525 // example, (G_SEXT (G_LOAD x)) that results in separate load and
1526 // sign-extend instructions shouldn't put the memoperand on the
1527 // sign-extend since it has no effect there.
1528 std::vector<unsigned> MergeInsnIDs;
1529 for (const auto &IDMatcherPair : Rule.defined_insn_vars())
1530 MergeInsnIDs.push_back(IDMatcherPair.second);
1531 std::sort(MergeInsnIDs.begin(), MergeInsnIDs.end());
1532 for (const auto &MergeInsnID : MergeInsnIDs)
1533 Table << MatchTable::IntValue(MergeInsnID);
Daniel Sanders05540042017-08-08 10:44:31 +00001534 Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
1535 << MatchTable::LineBreak;
Florian Hahn3bc3ec62017-08-03 14:48:22 +00001536 }
1537
1538 Table << MatchTable::Opcode("GIR_EraseFromParent")
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001539 << MatchTable::Comment("InsnID")
1540 << MatchTable::IntValue(RecycleInsnID) << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001541 }
1542};
1543
1544/// Generates code to constrain the operands of an output instruction to the
1545/// register classes specified by the definition of that instruction.
1546class ConstrainOperandsToDefinitionAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001547 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001548
1549public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001550 ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001551
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001552 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1553 unsigned RecycleInsnID) const override {
1554 Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
1555 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1556 << MatchTable::LineBreak;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001557 }
1558};
1559
1560/// Generates code to constrain the specified operand of an output instruction
1561/// to the specified register class.
1562class ConstrainOperandToRegClassAction : public MatchAction {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001563 unsigned InsnID;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001564 unsigned OpIdx;
1565 const CodeGenRegisterClass &RC;
1566
1567public:
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001568 ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001569 const CodeGenRegisterClass &RC)
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001570 : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00001571
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001572 void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule,
1573 unsigned RecycleInsnID) const override {
1574 Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
1575 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1576 << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
1577 << MatchTable::Comment("RC " + RC.getName())
1578 << MatchTable::IntValue(RC.EnumValue) << MatchTable::LineBreak;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001579 }
1580};
1581
Daniel Sanders05540042017-08-08 10:44:31 +00001582InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
1583 Matchers.emplace_back(new InstructionMatcher(SymbolicName));
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001584 return *Matchers.back();
1585}
Ahmed Bougacha56ca3a92017-02-04 00:47:10 +00001586
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001587void RuleMatcher::addRequiredFeature(Record *Feature) {
1588 RequiredFeatures.push_back(Feature);
1589}
1590
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001591const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
1592 return RequiredFeatures;
1593}
1594
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001595template <class Kind, class... Args>
1596Kind &RuleMatcher::addAction(Args &&... args) {
1597 Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
1598 return *static_cast<Kind *>(Actions.back().get());
1599}
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001600
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001601unsigned
1602RuleMatcher::implicitlyDefineInsnVar(const InstructionMatcher &Matcher) {
1603 unsigned NewInsnVarID = NextInsnVarID++;
1604 InsnVariableIDs[&Matcher] = NewInsnVarID;
1605 return NewInsnVarID;
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001606}
1607
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001608unsigned RuleMatcher::defineInsnVar(MatchTable &Table,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001609 const InstructionMatcher &Matcher,
1610 unsigned InsnID, unsigned OpIdx) {
1611 unsigned NewInsnVarID = implicitlyDefineInsnVar(Matcher);
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001612 Table << MatchTable::Opcode("GIM_RecordInsn")
1613 << MatchTable::Comment("DefineMI") << MatchTable::IntValue(NewInsnVarID)
1614 << MatchTable::Comment("MI") << MatchTable::IntValue(InsnID)
1615 << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
1616 << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
1617 << MatchTable::LineBreak;
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001618 return NewInsnVarID;
1619}
1620
1621unsigned RuleMatcher::getInsnVarID(const InstructionMatcher &InsnMatcher) const {
1622 const auto &I = InsnVariableIDs.find(&InsnMatcher);
1623 if (I != InsnVariableIDs.end())
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001624 return I->second;
1625 llvm_unreachable("Matched Insn was not captured in a local variable");
1626}
1627
Daniel Sanders05540042017-08-08 10:44:31 +00001628const InstructionMatcher &
1629RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
1630 for (const auto &I : InsnVariableIDs)
1631 if (I.first->getSymbolicName() == SymbolicName)
1632 return *I.first;
1633 llvm_unreachable(
1634 ("Failed to lookup instruction " + SymbolicName).str().c_str());
1635}
1636
Daniel Sanders9d662d22017-07-06 10:06:12 +00001637/// Emit MatchTable opcodes to check the shape of the match and capture
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001638/// instructions into local variables.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001639void RuleMatcher::emitCaptureOpcodes(MatchTable &Table) {
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001640 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001641 unsigned InsnVarID = implicitlyDefineInsnVar(*Matchers.front());
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001642 Matchers.front()->emitCaptureOpcodes(Table, *this, InsnVarID);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001643}
1644
Daniel Sanders8e82af22017-07-27 11:03:45 +00001645void RuleMatcher::emit(MatchTable &Table) {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001646 if (Matchers.empty())
1647 llvm_unreachable("Unexpected empty matcher!");
Daniel Sandersdc662ff2017-01-26 11:10:14 +00001648
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001649 // The representation supports rules that require multiple roots such as:
1650 // %ptr(p0) = ...
1651 // %elt0(s32) = G_LOAD %ptr
1652 // %1(p0) = G_ADD %ptr, 4
1653 // %elt1(s32) = G_LOAD p0 %1
1654 // which could be usefully folded into:
1655 // %ptr(p0) = ...
1656 // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
1657 // on some targets but we don't need to make use of that yet.
1658 assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001659
Daniel Sanders8e82af22017-07-27 11:03:45 +00001660 unsigned LabelID = Table.allocateLabelID();
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001661 Table << MatchTable::Opcode("GIM_Try", +1)
Daniel Sanders8e82af22017-07-27 11:03:45 +00001662 << MatchTable::Comment("On fail goto") << MatchTable::JumpTarget(LabelID)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001663 << MatchTable::LineBreak;
1664
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001665 if (!RequiredFeatures.empty()) {
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001666 Table << MatchTable::Opcode("GIM_CheckFeatures")
1667 << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
1668 << MatchTable::LineBreak;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001669 }
Daniel Sandersb96f40d2017-03-20 15:20:42 +00001670
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001671 emitCaptureOpcodes(Table);
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001672
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001673 Matchers.front()->emitPredicateOpcodes(Table, *this,
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001674 getInsnVarID(*Matchers.front()));
1675
Daniel Sandersbee57392017-04-04 13:25:23 +00001676 // We must also check if it's safe to fold the matched instructions.
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001677 if (InsnVariableIDs.size() >= 2) {
Galina Kistanova1754fee2017-05-25 01:51:53 +00001678 // Invert the map to create stable ordering (by var names)
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001679 SmallVector<unsigned, 2> InsnIDs;
1680 for (const auto &Pair : InsnVariableIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001681 // Skip the root node since it isn't moving anywhere. Everything else is
1682 // sinking to meet it.
1683 if (Pair.first == Matchers.front().get())
1684 continue;
1685
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001686 InsnIDs.push_back(Pair.second);
Galina Kistanova1754fee2017-05-25 01:51:53 +00001687 }
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001688 std::sort(InsnIDs.begin(), InsnIDs.end());
Galina Kistanova1754fee2017-05-25 01:51:53 +00001689
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00001690 for (const auto &InsnID : InsnIDs) {
Daniel Sandersbee57392017-04-04 13:25:23 +00001691 // Reject the difficult cases until we have a more accurate check.
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001692 Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
1693 << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
1694 << MatchTable::LineBreak;
Daniel Sandersbee57392017-04-04 13:25:23 +00001695
1696 // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
1697 // account for unsafe cases.
1698 //
1699 // Example:
1700 // MI1--> %0 = ...
1701 // %1 = ... %0
1702 // MI0--> %2 = ... %0
1703 // It's not safe to erase MI1. We currently handle this by not
1704 // erasing %0 (even when it's dead).
1705 //
1706 // Example:
1707 // MI1--> %0 = load volatile @a
1708 // %1 = load volatile @a
1709 // MI0--> %2 = ... %0
1710 // It's not safe to sink %0's def past %1. We currently handle
1711 // this by rejecting all loads.
1712 //
1713 // Example:
1714 // MI1--> %0 = load @a
1715 // %1 = store @a
1716 // MI0--> %2 = ... %0
1717 // It's not safe to sink %0's def past %1. We currently handle
1718 // this by rejecting all loads.
1719 //
1720 // Example:
1721 // G_CONDBR %cond, @BB1
1722 // BB0:
1723 // MI1--> %0 = load @a
1724 // G_BR @BB1
1725 // BB1:
1726 // MI0--> %2 = ... %0
1727 // It's not always safe to sink %0 across control flow. In this
1728 // case it may introduce a memory fault. We currentl handle this
1729 // by rejecting all loads.
1730 }
1731 }
1732
Daniel Sandersd93a35a2017-07-05 09:39:33 +00001733 for (const auto &MA : Actions)
Daniel Sanders7aac7cc2017-07-20 09:25:44 +00001734 MA->emitActionOpcodes(Table, *this, 0);
1735 Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
Daniel Sanders8e82af22017-07-27 11:03:45 +00001736 << MatchTable::Label(LabelID);
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001737}
Daniel Sanders43c882c2017-02-01 10:53:10 +00001738
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001739bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
1740 // Rules involving more match roots have higher priority.
1741 if (Matchers.size() > B.Matchers.size())
1742 return true;
1743 if (Matchers.size() < B.Matchers.size())
Daniel Sanders759ff412017-02-24 13:58:11 +00001744 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001745
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001746 for (const auto &Matcher : zip(Matchers, B.Matchers)) {
1747 if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
1748 return true;
1749 if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
1750 return false;
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001751 }
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001752
1753 return false;
Simon Pilgrima7d1da82017-03-15 22:50:47 +00001754}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001755
Daniel Sanders2deea182017-04-22 15:11:04 +00001756unsigned RuleMatcher::countRendererFns() const {
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001757 return std::accumulate(
1758 Matchers.begin(), Matchers.end(), 0,
1759 [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
Daniel Sanders2deea182017-04-22 15:11:04 +00001760 return A + Matcher->countRendererFns();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001761 });
1762}
1763
Daniel Sanders05540042017-08-08 10:44:31 +00001764bool OperandPredicateMatcher::isHigherPriorityThan(
1765 const OperandPredicateMatcher &B) const {
1766 // Generally speaking, an instruction is more important than an Int or a
1767 // LiteralInt because it can cover more nodes but theres an exception to
1768 // this. G_CONSTANT's are less important than either of those two because they
1769 // are more permissive.
1770 if (const InstructionOperandMatcher *AOM =
1771 dyn_cast<InstructionOperandMatcher>(this)) {
1772 if (AOM->getInsnMatcher().isConstantInstruction()) {
1773 if (B.Kind == OPM_Int) {
1774 return false;
1775 }
1776 }
1777 }
1778 if (const InstructionOperandMatcher *BOM =
1779 dyn_cast<InstructionOperandMatcher>(&B)) {
1780 if (BOM->getInsnMatcher().isConstantInstruction()) {
1781 if (Kind == OPM_Int) {
1782 return true;
1783 }
1784 }
1785 }
1786
1787 return Kind < B.Kind;
Daniel Sanders75b84fc2017-08-08 13:21:26 +00001788}
Daniel Sanders05540042017-08-08 10:44:31 +00001789
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001790//===- GlobalISelEmitter class --------------------------------------------===//
1791
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001792class GlobalISelEmitter {
1793public:
1794 explicit GlobalISelEmitter(RecordKeeper &RK);
1795 void run(raw_ostream &OS);
1796
1797private:
1798 const RecordKeeper &RK;
1799 const CodeGenDAGPatterns CGP;
1800 const CodeGenTarget &Target;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001801 CodeGenRegBank CGRegs;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001802
1803 /// Keep track of the equivalence between SDNodes and Instruction.
1804 /// This is defined using 'GINodeEquiv' in the target description.
1805 DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
1806
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001807 /// Keep track of the equivalence between ComplexPattern's and
1808 /// GIComplexOperandMatcher. Map entries are specified by subclassing
1809 /// GIComplexPatternEquiv.
1810 DenseMap<const Record *, const Record *> ComplexPatternEquivs;
1811
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001812 // Map of predicates to their subtarget features.
Daniel Sanderse9fdba32017-04-29 17:30:09 +00001813 SubtargetFeatureInfoMap SubtargetFeatures;
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001814
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001815 void gatherNodeEquivs();
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001816 const CodeGenInstruction *findNodeEquiv(Record *N) const;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001817
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001818 Error importRulePredicates(RuleMatcher &M, ArrayRef<Init *> Predicates);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001819 Expected<InstructionMatcher &>
Daniel Sandersc270c502017-03-30 09:36:33 +00001820 createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders57938df2017-07-11 10:40:18 +00001821 const TreePatternNode *Src,
1822 unsigned &TempOpIdx) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001823 Error importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001824 const TreePatternNode *SrcChild, unsigned OpIdx,
Daniel Sandersc270c502017-03-30 09:36:33 +00001825 unsigned &TempOpIdx) const;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001826 Expected<BuildMIAction &>
1827 createAndImportInstructionRenderer(RuleMatcher &M, const TreePatternNode *Dst,
1828 const InstructionMatcher &InsnMatcher);
Daniel Sandersc270c502017-03-30 09:36:33 +00001829 Error importExplicitUseRenderer(BuildMIAction &DstMIBuilder,
1830 TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001831 const InstructionMatcher &InsnMatcher) const;
Diana Picus382602f2017-05-17 08:57:28 +00001832 Error importDefaultOperandRenderers(BuildMIAction &DstMIBuilder,
1833 DagInit *DefaultOps) const;
Daniel Sandersc270c502017-03-30 09:36:33 +00001834 Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001835 importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
1836 const std::vector<Record *> &ImplicitDefs) const;
1837
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001838 /// Analyze pattern \p P, returning a matcher for it if possible.
1839 /// Otherwise, return an Error explaining why we don't support it.
1840 Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001841
1842 void declareSubtargetFeature(Record *Predicate);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00001843};
1844
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001845void GlobalISelEmitter::gatherNodeEquivs() {
1846 assert(NodeEquivs.empty());
1847 for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
1848 NodeEquivs[Equiv->getValueAsDef("Node")] =
1849 &Target.getInstruction(Equiv->getValueAsDef("I"));
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001850
1851 assert(ComplexPatternEquivs.empty());
1852 for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
1853 Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
1854 if (!SelDAGEquiv)
1855 continue;
1856 ComplexPatternEquivs[SelDAGEquiv] = Equiv;
1857 }
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001858}
1859
Daniel Sandersbdfebb82017-03-15 20:18:38 +00001860const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) const {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001861 return NodeEquivs.lookup(N);
1862}
1863
1864GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00001865 : RK(RK), CGP(RK), Target(CGP.getTargetInfo()), CGRegs(RK) {}
Ahmed Bougacha36f70352016-12-21 23:26:20 +00001866
1867//===- Emitter ------------------------------------------------------------===//
1868
Daniel Sandersc270c502017-03-30 09:36:33 +00001869Error
Daniel Sandersffc7d582017-03-29 15:37:18 +00001870GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
Daniel Sanderse7b0d662017-04-21 15:59:56 +00001871 ArrayRef<Init *> Predicates) {
1872 for (const Init *Predicate : Predicates) {
1873 const DefInit *PredicateDef = static_cast<const DefInit *>(Predicate);
1874 declareSubtargetFeature(PredicateDef->getDef());
1875 M.addRequiredFeature(PredicateDef->getDef());
1876 }
1877
Daniel Sandersc270c502017-03-30 09:36:33 +00001878 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001879}
Daniel Sanders8a4bae92017-03-14 21:32:08 +00001880
Daniel Sanders57938df2017-07-11 10:40:18 +00001881Expected<InstructionMatcher &>
1882GlobalISelEmitter::createAndImportSelDAGMatcher(InstructionMatcher &InsnMatcher,
1883 const TreePatternNode *Src,
1884 unsigned &TempOpIdx) const {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001885 const CodeGenInstruction *SrcGIOrNull = nullptr;
1886
Daniel Sandersffc7d582017-03-29 15:37:18 +00001887 // Start with the defined operands (i.e., the results of the root operator).
1888 if (Src->getExtTypes().size() > 1)
1889 return failedImport("Src pattern has multiple results");
1890
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001891 if (Src->isLeaf()) {
1892 Init *SrcInit = Src->getLeafValue();
Daniel Sanders3334cc02017-05-23 20:02:48 +00001893 if (isa<IntInit>(SrcInit)) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001894 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
1895 &Target.getInstruction(RK.getDef("G_CONSTANT")));
1896 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001897 return failedImport(
1898 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001899 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001900 SrcGIOrNull = findNodeEquiv(Src->getOperator());
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001901 if (!SrcGIOrNull)
1902 return failedImport("Pattern operator lacks an equivalent Instruction" +
1903 explainOperator(Src->getOperator()));
1904 auto &SrcGI = *SrcGIOrNull;
Daniel Sandersffc7d582017-03-29 15:37:18 +00001905
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001906 // The operators look good: match the opcode
1907 InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
1908 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001909
1910 unsigned OpIdx = 0;
1911 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
1912 auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
1913
1914 if (!OpTyOrNone)
1915 return failedImport(
1916 "Result of Src pattern operator has an unsupported type");
1917
1918 // Results don't have a name unless they are the root node. The caller will
1919 // set the name if appropriate.
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001920 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001921 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1922 }
1923
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001924 if (Src->isLeaf()) {
1925 Init *SrcInit = Src->getLeafValue();
1926 if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
1927 OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1928 OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
1929 } else
Daniel Sanders32291982017-06-28 13:50:04 +00001930 return failedImport(
1931 "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001932 } else {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001933 assert(SrcGIOrNull &&
1934 "Expected to have already found an equivalent Instruction");
Daniel Sanders05540042017-08-08 10:44:31 +00001935 if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT") {
1936 // imm still has an operand but we don't need to do anything with it
1937 // here since we don't support ImmLeaf predicates yet. However, we still
1938 // need to note the hidden operand to get GIM_CheckNumOperands correct.
1939 InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
1940 return InsnMatcher;
1941 }
1942
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001943 // Match the used operands (i.e. the children of the operator).
1944 for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001945 TreePatternNode *SrcChild = Src->getChild(i);
1946
1947 // For G_INTRINSIC, the operand immediately following the defs is an
1948 // intrinsic ID.
1949 if (SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" && i == 0) {
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001950 if (const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP)) {
Daniel Sanders85ffd362017-07-06 08:12:20 +00001951 OperandMatcher &OM =
1952 InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
Daniel Sandersfe12c0f2017-07-11 08:57:29 +00001953 OM.addPredicate<IntrinsicIDOperandMatcher>(II);
Daniel Sanders85ffd362017-07-06 08:12:20 +00001954 continue;
1955 }
1956
1957 return failedImport("Expected IntInit containing instrinsic ID)");
1958 }
1959
1960 if (auto Error =
1961 importChildMatcher(InsnMatcher, SrcChild, OpIdx++, TempOpIdx))
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001962 return std::move(Error);
1963 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001964 }
1965
1966 return InsnMatcher;
1967}
1968
Daniel Sandersc270c502017-03-30 09:36:33 +00001969Error GlobalISelEmitter::importChildMatcher(InstructionMatcher &InsnMatcher,
Daniel Sanders452c8ae2017-05-23 19:33:16 +00001970 const TreePatternNode *SrcChild,
Daniel Sandersc270c502017-03-30 09:36:33 +00001971 unsigned OpIdx,
1972 unsigned &TempOpIdx) const {
Daniel Sanders4f3eb242017-04-05 13:14:03 +00001973 OperandMatcher &OM =
1974 InsnMatcher.addOperand(OpIdx, SrcChild->getName(), TempOpIdx);
Daniel Sandersffc7d582017-03-29 15:37:18 +00001975
1976 if (SrcChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00001977 return failedImport("Src pattern child has predicate (" +
1978 explainPredicates(SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001979
1980 ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
1981 if (ChildTypes.size() != 1)
1982 return failedImport("Src pattern child has multiple results");
1983
1984 // Check MBB's before the type check since they are not a known type.
1985 if (!SrcChild->isLeaf()) {
1986 if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
1987 auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
1988 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
1989 OM.addPredicate<MBBOperandMatcher>();
Daniel Sandersc270c502017-03-30 09:36:33 +00001990 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00001991 }
1992 }
Daniel Sandersffc7d582017-03-29 15:37:18 +00001993 }
1994
1995 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
1996 if (!OpTyOrNone)
Daniel Sanders85ffd362017-07-06 08:12:20 +00001997 return failedImport("Src operand has an unsupported type (" + to_string(*SrcChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00001998 OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
1999
Daniel Sandersbee57392017-04-04 13:25:23 +00002000 // Check for nested instructions.
2001 if (!SrcChild->isLeaf()) {
2002 // Map the node to a gMIR instruction.
2003 InstructionOperandMatcher &InsnOperand =
Daniel Sanders05540042017-08-08 10:44:31 +00002004 OM.addPredicate<InstructionOperandMatcher>(SrcChild->getName());
Daniel Sanders57938df2017-07-11 10:40:18 +00002005 auto InsnMatcherOrError = createAndImportSelDAGMatcher(
2006 InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
Daniel Sandersbee57392017-04-04 13:25:23 +00002007 if (auto Error = InsnMatcherOrError.takeError())
2008 return Error;
2009
2010 return Error::success();
2011 }
2012
Daniel Sandersffc7d582017-03-29 15:37:18 +00002013 // Check for constant immediates.
2014 if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002015 OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
Daniel Sandersc270c502017-03-30 09:36:33 +00002016 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002017 }
2018
2019 // Check for def's like register classes or ComplexPattern's.
2020 if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
2021 auto *ChildRec = ChildDefInit->getDef();
2022
2023 // Check for register classes.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002024 if (ChildRec->isSubClassOf("RegisterClass") ||
2025 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002026 OM.addPredicate<RegisterBankOperandMatcher>(
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002027 Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
Daniel Sanders658541f2017-04-22 15:53:21 +00002028 return Error::success();
2029 }
2030
Daniel Sandersffc7d582017-03-29 15:37:18 +00002031 // Check for ComplexPattern's.
2032 if (ChildRec->isSubClassOf("ComplexPattern")) {
2033 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2034 if (ComplexPattern == ComplexPatternEquivs.end())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002035 return failedImport("SelectionDAG ComplexPattern (" +
2036 ChildRec->getName() + ") not mapped to GlobalISel");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002037
Daniel Sanders2deea182017-04-22 15:11:04 +00002038 OM.addPredicate<ComplexPatternOperandMatcher>(OM,
2039 *ComplexPattern->second);
2040 TempOpIdx++;
Daniel Sandersc270c502017-03-30 09:36:33 +00002041 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002042 }
2043
Daniel Sandersd0656a32017-04-13 09:45:37 +00002044 if (ChildRec->isSubClassOf("ImmLeaf")) {
2045 return failedImport(
2046 "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
2047 }
2048
Daniel Sandersffc7d582017-03-29 15:37:18 +00002049 return failedImport(
2050 "Src pattern child def is an unsupported tablegen class");
2051 }
2052
2053 return failedImport("Src pattern child is an unsupported kind");
2054}
2055
Daniel Sandersc270c502017-03-30 09:36:33 +00002056Error GlobalISelEmitter::importExplicitUseRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002057 BuildMIAction &DstMIBuilder, TreePatternNode *DstChild,
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002058 const InstructionMatcher &InsnMatcher) const {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002059 if (!DstChild->isLeaf()) {
Daniel Sanders05540042017-08-08 10:44:31 +00002060 // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
2061 // inline, but in MI it's just another operand.
Daniel Sandersffc7d582017-03-29 15:37:18 +00002062 if (DstChild->getOperator()->isSubClassOf("SDNode")) {
2063 auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
2064 if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002065 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
Daniel Sandersffc7d582017-03-29 15:37:18 +00002066 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002067 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002068 }
2069 }
Daniel Sanders05540042017-08-08 10:44:31 +00002070
2071 // Similarly, imm is an operator in TreePatternNode's view but must be
2072 // rendered as operands.
2073 // FIXME: The target should be able to choose sign-extended when appropriate
2074 // (e.g. on Mips).
2075 if (DstChild->getOperator()->getName() == "imm") {
2076 DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(0,
2077 DstChild->getName());
2078 return Error::success();
2079 }
2080
Daniel Sandersffc7d582017-03-29 15:37:18 +00002081 return failedImport("Dst pattern child isn't a leaf node or an MBB");
2082 }
2083
2084 // Otherwise, we're looking for a bog-standard RegisterClass operand.
2085 if (DstChild->hasAnyPredicate())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002086 return failedImport("Dst pattern child has predicate (" +
2087 explainPredicates(DstChild) + ")");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002088
2089 if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
2090 auto *ChildRec = ChildDefInit->getDef();
2091
2092 ArrayRef<EEVT::TypeSet> ChildTypes = DstChild->getExtTypes();
2093 if (ChildTypes.size() != 1)
2094 return failedImport("Dst pattern child has multiple results");
2095
2096 auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
2097 if (!OpTyOrNone)
2098 return failedImport("Dst operand has an unsupported type");
2099
2100 if (ChildRec->isSubClassOf("Register")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002101 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, ChildRec);
Daniel Sandersc270c502017-03-30 09:36:33 +00002102 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002103 }
2104
Daniel Sanders658541f2017-04-22 15:53:21 +00002105 if (ChildRec->isSubClassOf("RegisterClass") ||
2106 ChildRec->isSubClassOf("RegisterOperand")) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002107 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher,
2108 DstChild->getName());
Daniel Sandersc270c502017-03-30 09:36:33 +00002109 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002110 }
2111
2112 if (ChildRec->isSubClassOf("ComplexPattern")) {
2113 const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
2114 if (ComplexPattern == ComplexPatternEquivs.end())
2115 return failedImport(
2116 "SelectionDAG ComplexPattern not mapped to GlobalISel");
2117
Daniel Sanders4f3eb242017-04-05 13:14:03 +00002118 const OperandMatcher &OM = InsnMatcher.getOperand(DstChild->getName());
Daniel Sandersffc7d582017-03-29 15:37:18 +00002119 DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002120 0, *ComplexPattern->second, DstChild->getName(),
Daniel Sanders2deea182017-04-22 15:11:04 +00002121 OM.getAllocatedTemporariesBaseID());
Daniel Sandersc270c502017-03-30 09:36:33 +00002122 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002123 }
2124
Daniel Sandersd0656a32017-04-13 09:45:37 +00002125 if (ChildRec->isSubClassOf("SDNodeXForm"))
2126 return failedImport("Dst pattern child def is an unsupported tablegen "
2127 "class (SDNodeXForm)");
2128
Daniel Sandersffc7d582017-03-29 15:37:18 +00002129 return failedImport(
2130 "Dst pattern child def is an unsupported tablegen class");
2131 }
2132
2133 return failedImport("Dst pattern child is an unsupported kind");
2134}
2135
Daniel Sandersc270c502017-03-30 09:36:33 +00002136Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002137 RuleMatcher &M, const TreePatternNode *Dst,
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002138 const InstructionMatcher &InsnMatcher) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002139 Record *DstOp = Dst->getOperator();
Daniel Sandersd0656a32017-04-13 09:45:37 +00002140 if (!DstOp->isSubClassOf("Instruction")) {
2141 if (DstOp->isSubClassOf("ValueType"))
2142 return failedImport(
2143 "Pattern operator isn't an instruction (it's a ValueType)");
Daniel Sandersffc7d582017-03-29 15:37:18 +00002144 return failedImport("Pattern operator isn't an instruction");
Daniel Sandersd0656a32017-04-13 09:45:37 +00002145 }
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002146 CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002147
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002148 unsigned DstINumUses = DstI->Operands.size() - DstI->Operands.NumDefs;
2149 unsigned ExpectedDstINumUses = Dst->getNumChildren();
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002150 bool IsExtractSubReg = false;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002151
2152 // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002153 // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002154 if (DstI->TheDef->getName() == "COPY_TO_REGCLASS") {
2155 DstI = &Target.getInstruction(RK.getDef("COPY"));
2156 DstINumUses--; // Ignore the class constraint.
2157 ExpectedDstINumUses--;
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002158 } else if (DstI->TheDef->getName() == "EXTRACT_SUBREG") {
2159 DstI = &Target.getInstruction(RK.getDef("COPY"));
2160 IsExtractSubReg = true;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002161 }
2162
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002163 auto &DstMIBuilder = M.addAction<BuildMIAction>(0, DstI, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002164
2165 // Render the explicit defs.
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002166 for (unsigned I = 0; I < DstI->Operands.NumDefs; ++I) {
2167 const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[I];
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002168 DstMIBuilder.addRenderer<CopyRenderer>(0, InsnMatcher, DstIOperand.Name);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002169 }
2170
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002171 // EXTRACT_SUBREG needs to use a subregister COPY.
2172 if (IsExtractSubReg) {
2173 if (!Dst->getChild(0)->isLeaf())
2174 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2175
Daniel Sanders32291982017-06-28 13:50:04 +00002176 if (DefInit *SubRegInit =
2177 dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue())) {
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002178 CodeGenRegisterClass *RC = CGRegs.getRegClass(
2179 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue()));
2180 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
2181
2182 const auto &SrcRCDstRCPair =
2183 RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2184 if (SrcRCDstRCPair.hasValue()) {
2185 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
2186 if (SrcRCDstRCPair->first != RC)
2187 return failedImport("EXTRACT_SUBREG requires an additional COPY");
2188 }
2189
2190 DstMIBuilder.addRenderer<CopySubRegRenderer>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002191 0, InsnMatcher, Dst->getChild(0)->getName(), SubIdx);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002192 return DstMIBuilder;
2193 }
2194
2195 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
2196 }
2197
Daniel Sandersffc7d582017-03-29 15:37:18 +00002198 // Render the explicit uses.
Daniel Sanders0ed28822017-04-12 08:23:08 +00002199 unsigned Child = 0;
Diana Picus382602f2017-05-17 08:57:28 +00002200 unsigned NumDefaultOps = 0;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002201 for (unsigned I = 0; I != DstINumUses; ++I) {
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002202 const CGIOperandList::OperandInfo &DstIOperand =
2203 DstI->Operands[DstI->Operands.NumDefs + I];
Daniel Sanders0ed28822017-04-12 08:23:08 +00002204
Diana Picus382602f2017-05-17 08:57:28 +00002205 // If the operand has default values, introduce them now.
2206 // FIXME: Until we have a decent test case that dictates we should do
2207 // otherwise, we're going to assume that operands with default values cannot
2208 // be specified in the patterns. Therefore, adding them will not cause us to
2209 // end up with too many rendered operands.
2210 if (DstIOperand.Rec->isSubClassOf("OperandWithDefaultOps")) {
Daniel Sanders0ed28822017-04-12 08:23:08 +00002211 DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
Diana Picus382602f2017-05-17 08:57:28 +00002212 if (auto Error = importDefaultOperandRenderers(DstMIBuilder, DefaultOps))
2213 return std::move(Error);
2214 ++NumDefaultOps;
Daniel Sanders0ed28822017-04-12 08:23:08 +00002215 continue;
2216 }
2217
2218 if (auto Error = importExplicitUseRenderer(
2219 DstMIBuilder, Dst->getChild(Child), InsnMatcher))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002220 return std::move(Error);
Daniel Sanders0ed28822017-04-12 08:23:08 +00002221 ++Child;
Daniel Sandersffc7d582017-03-29 15:37:18 +00002222 }
2223
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002224 if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
Diana Picuseb2057c2017-05-17 09:25:08 +00002225 return failedImport("Expected " + llvm::to_string(DstINumUses) +
Diana Picus382602f2017-05-17 08:57:28 +00002226 " used operands but found " +
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002227 llvm::to_string(ExpectedDstINumUses) +
Diana Picuseb2057c2017-05-17 09:25:08 +00002228 " explicit ones and " + llvm::to_string(NumDefaultOps) +
Diana Picus382602f2017-05-17 08:57:28 +00002229 " default ones");
2230
Daniel Sandersffc7d582017-03-29 15:37:18 +00002231 return DstMIBuilder;
2232}
2233
Diana Picus382602f2017-05-17 08:57:28 +00002234Error GlobalISelEmitter::importDefaultOperandRenderers(
2235 BuildMIAction &DstMIBuilder, DagInit *DefaultOps) const {
Craig Topper481ff702017-05-29 21:49:34 +00002236 for (const auto *DefaultOp : DefaultOps->getArgs()) {
Diana Picus382602f2017-05-17 08:57:28 +00002237 // Look through ValueType operators.
2238 if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
2239 if (const DefInit *DefaultDagOperator =
2240 dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
2241 if (DefaultDagOperator->getDef()->isSubClassOf("ValueType"))
2242 DefaultOp = DefaultDagOp->getArg(0);
2243 }
2244 }
2245
2246 if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002247 DstMIBuilder.addRenderer<AddRegisterRenderer>(0, DefaultDefOp->getDef());
Diana Picus382602f2017-05-17 08:57:28 +00002248 continue;
2249 }
2250
2251 if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002252 DstMIBuilder.addRenderer<ImmRenderer>(0, DefaultIntOp->getValue());
Diana Picus382602f2017-05-17 08:57:28 +00002253 continue;
2254 }
2255
2256 return failedImport("Could not add default op");
2257 }
2258
2259 return Error::success();
2260}
2261
Daniel Sandersc270c502017-03-30 09:36:33 +00002262Error GlobalISelEmitter::importImplicitDefRenderers(
Daniel Sandersffc7d582017-03-29 15:37:18 +00002263 BuildMIAction &DstMIBuilder,
2264 const std::vector<Record *> &ImplicitDefs) const {
2265 if (!ImplicitDefs.empty())
2266 return failedImport("Pattern defines a physical register");
Daniel Sandersc270c502017-03-30 09:36:33 +00002267 return Error::success();
Daniel Sandersffc7d582017-03-29 15:37:18 +00002268}
2269
2270Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002271 // Keep track of the matchers and actions to emit.
Ahmed Bougacha9aa4c102017-02-04 00:47:08 +00002272 RuleMatcher M;
2273 M.addAction<DebugCommentAction>(P);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002274
Daniel Sandersc270c502017-03-30 09:36:33 +00002275 if (auto Error = importRulePredicates(M, P.getPredicates()->getValues()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002276 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002277
2278 // Next, analyze the pattern operators.
2279 TreePatternNode *Src = P.getSrcPattern();
2280 TreePatternNode *Dst = P.getDstPattern();
2281
2282 // If the root of either pattern isn't a simple operator, ignore it.
Daniel Sandersd0656a32017-04-13 09:45:37 +00002283 if (auto Err = isTrivialOperatorNode(Dst))
2284 return failedImport("Dst pattern root isn't a trivial operator (" +
2285 toString(std::move(Err)) + ")");
2286 if (auto Err = isTrivialOperatorNode(Src))
2287 return failedImport("Src pattern root isn't a trivial operator (" +
2288 toString(std::move(Err)) + ")");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002289
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00002290 if (Dst->isLeaf())
Daniel Sanders452c8ae2017-05-23 19:33:16 +00002291 return failedImport("Dst pattern root isn't a known leaf");
2292
Daniel Sandersbee57392017-04-04 13:25:23 +00002293 // Start with the defined operands (i.e., the results of the root operator).
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002294 Record *DstOp = Dst->getOperator();
2295 if (!DstOp->isSubClassOf("Instruction"))
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002296 return failedImport("Pattern operator isn't an instruction");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002297
2298 auto &DstI = Target.getInstruction(DstOp);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002299 if (DstI.Operands.NumDefs != Src->getExtTypes().size())
Daniel Sandersd0656a32017-04-13 09:45:37 +00002300 return failedImport("Src pattern results and dst MI defs are different (" +
2301 to_string(Src->getExtTypes().size()) + " def(s) vs " +
2302 to_string(DstI.Operands.NumDefs) + " def(s))");
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002303
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00002304 InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
2305 unsigned TempOpIdx = 0;
2306 auto InsnMatcherOrError =
2307 createAndImportSelDAGMatcher(InsnMatcherTemp, Src, TempOpIdx);
2308 if (auto Error = InsnMatcherOrError.takeError())
2309 return std::move(Error);
2310 InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
2311
Daniel Sandersffc7d582017-03-29 15:37:18 +00002312 // The root of the match also has constraints on the register bank so that it
2313 // matches the result instruction.
2314 unsigned OpIdx = 0;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002315 for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
Daniel Sandersffc7d582017-03-29 15:37:18 +00002316 (void)Ty;
2317
Daniel Sanders066ebbf2017-02-24 15:43:30 +00002318 const auto &DstIOperand = DstI.Operands[OpIdx];
2319 Record *DstIOpRec = DstIOperand.Rec;
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002320 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2321 DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2322
2323 if (DstIOpRec == nullptr)
2324 return failedImport(
2325 "COPY_TO_REGCLASS operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002326 } else if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2327 if (!Dst->getChild(0)->isLeaf())
2328 return failedImport("EXTRACT_SUBREG operand #0 isn't a leaf");
2329
Daniel Sanders32291982017-06-28 13:50:04 +00002330 // We can assume that a subregister is in the same bank as it's super
2331 // register.
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002332 DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
2333
2334 if (DstIOpRec == nullptr)
2335 return failedImport(
2336 "EXTRACT_SUBREG operand #0 isn't a register class");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002337 } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
Daniel Sanders658541f2017-04-22 15:53:21 +00002338 DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002339 else if (!DstIOpRec->isSubClassOf("RegisterClass"))
Daniel Sanders32291982017-06-28 13:50:04 +00002340 return failedImport("Dst MI def isn't a register class" +
2341 to_string(*Dst));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002342
Daniel Sandersffc7d582017-03-29 15:37:18 +00002343 OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
2344 OM.setSymbolicName(DstIOperand.Name);
Daniel Sandersdc662ff2017-01-26 11:10:14 +00002345 OM.addPredicate<RegisterBankOperandMatcher>(
2346 Target.getRegisterClass(DstIOpRec));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002347 ++OpIdx;
2348 }
2349
Daniel Sandersc270c502017-03-30 09:36:33 +00002350 auto DstMIBuilderOrError =
2351 createAndImportInstructionRenderer(M, Dst, InsnMatcher);
Daniel Sandersffc7d582017-03-29 15:37:18 +00002352 if (auto Error = DstMIBuilderOrError.takeError())
2353 return std::move(Error);
2354 BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002355
Daniel Sandersffc7d582017-03-29 15:37:18 +00002356 // Render the implicit defs.
2357 // These are only added to the root of the result.
Daniel Sandersc270c502017-03-30 09:36:33 +00002358 if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
Daniel Sandersffc7d582017-03-29 15:37:18 +00002359 return std::move(Error);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002360
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002361 // Constrain the registers to classes. This is normally derived from the
2362 // emitted instruction but a few instructions require special handling.
2363 if (DstI.TheDef->getName() == "COPY_TO_REGCLASS") {
2364 // COPY_TO_REGCLASS does not provide operand constraints itself but the
2365 // result is constrained to the class given by the second child.
2366 Record *DstIOpRec =
2367 getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
2368
2369 if (DstIOpRec == nullptr)
2370 return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
2371
2372 M.addAction<ConstrainOperandToRegClassAction>(
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002373 0, 0, Target.getRegisterClass(DstIOpRec));
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002374
2375 // We're done with this pattern! It's eligible for GISel emission; return
2376 // it.
2377 ++NumPatternImported;
2378 return std::move(M);
2379 }
2380
2381 if (DstI.TheDef->getName() == "EXTRACT_SUBREG") {
2382 // EXTRACT_SUBREG selects into a subregister COPY but unlike most
2383 // instructions, the result register class is controlled by the
2384 // subregisters of the operand. As a result, we must constrain the result
2385 // class rather than check that it's already the right one.
2386 if (!Dst->getChild(0)->isLeaf())
2387 return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
2388
Daniel Sanders320390b2017-06-28 15:16:03 +00002389 DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
2390 if (!SubRegInit)
2391 return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002392
Daniel Sanders320390b2017-06-28 15:16:03 +00002393 // Constrain the result to the same register bank as the operand.
2394 Record *DstIOpRec =
2395 getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002396
Daniel Sanders320390b2017-06-28 15:16:03 +00002397 if (DstIOpRec == nullptr)
2398 return failedImport("EXTRACT_SUBREG operand #1 isn't a register class");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002399
Daniel Sanders320390b2017-06-28 15:16:03 +00002400 CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002401 CodeGenRegisterClass *SrcRC = CGRegs.getRegClass(DstIOpRec);
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002402
Daniel Sanders320390b2017-06-28 15:16:03 +00002403 // It would be nice to leave this constraint implicit but we're required
2404 // to pick a register class so constrain the result to a register class
2405 // that can hold the correct MVT.
2406 //
2407 // FIXME: This may introduce an extra copy if the chosen class doesn't
2408 // actually contain the subregisters.
2409 assert(Src->getExtTypes().size() == 1 &&
2410 "Expected Src of EXTRACT_SUBREG to have one result type");
Daniel Sanderscc36dbf2017-06-27 10:11:39 +00002411
Daniel Sanders320390b2017-06-28 15:16:03 +00002412 const auto &SrcRCDstRCPair =
2413 SrcRC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
2414 assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
Daniel Sandersd93a35a2017-07-05 09:39:33 +00002415 M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
2416 M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
2417
2418 // We're done with this pattern! It's eligible for GISel emission; return
2419 // it.
2420 ++NumPatternImported;
2421 return std::move(M);
2422 }
2423
2424 M.addAction<ConstrainOperandsToDefinitionAction>(0);
Daniel Sandersa6e2ceb2017-06-20 12:36:34 +00002425
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002426 // We're done with this pattern! It's eligible for GISel emission; return it.
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002427 ++NumPatternImported;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002428 return std::move(M);
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002429}
2430
2431void GlobalISelEmitter::run(raw_ostream &OS) {
2432 // Track the GINodeEquiv definitions.
2433 gatherNodeEquivs();
2434
2435 emitSourceFileHeader(("Global Instruction Selector for the " +
2436 Target.getName() + " target").str(), OS);
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002437 std::vector<RuleMatcher> Rules;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002438 // Look through the SelectionDAG patterns we found, possibly emitting some.
2439 for (const PatternToMatch &Pat : CGP.ptms()) {
2440 ++NumPatternTotal;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002441 auto MatcherOrErr = runOnPattern(Pat);
2442
2443 // The pattern analysis can fail, indicating an unsupported pattern.
2444 // Report that if we've been asked to do so.
2445 if (auto Err = MatcherOrErr.takeError()) {
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002446 if (WarnOnSkippedPatterns) {
2447 PrintWarning(Pat.getSrcRecord()->getLoc(),
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002448 "Skipped pattern: " + toString(std::move(Err)));
2449 } else {
2450 consumeError(std::move(Err));
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002451 }
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002452 ++NumPatternImportsSkipped;
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002453 continue;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002454 }
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002455
Daniel Sandersb41ce2b2017-02-20 14:31:27 +00002456 Rules.push_back(std::move(MatcherOrErr.get()));
2457 }
2458
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00002459 std::stable_sort(Rules.begin(), Rules.end(),
2460 [&](const RuleMatcher &A, const RuleMatcher &B) {
2461 if (A.isHigherPriorityThan(B)) {
2462 assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
2463 "and less important at "
2464 "the same time");
2465 return true;
2466 }
2467 return false;
2468 });
Daniel Sanders759ff412017-02-24 13:58:11 +00002469
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002470 std::vector<Record *> ComplexPredicates =
2471 RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
2472 std::sort(ComplexPredicates.begin(), ComplexPredicates.end(),
2473 [](const Record *A, const Record *B) {
2474 if (A->getName() < B->getName())
2475 return true;
2476 return false;
2477 });
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002478 unsigned MaxTemporaries = 0;
2479 for (const auto &Rule : Rules)
Daniel Sanders2deea182017-04-22 15:11:04 +00002480 MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002481
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002482 OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
2483 << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
2484 << ";\n"
2485 << "using PredicateBitset = "
2486 "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
2487 << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
2488
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002489 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
2490 << " mutable MatcherState State;\n"
2491 << " typedef "
2492 "ComplexRendererFn("
2493 << Target.getName()
2494 << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
2495 << "const MatcherInfoTy<PredicateBitset, ComplexMatcherMemFn> "
2496 "MatcherInfo;\n"
2497 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002498
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002499 OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
2500 << ", State(" << MaxTemporaries << "),\n"
2501 << "MatcherInfo({TypeObjects, FeatureBitsets, {\n"
2502 << " nullptr, // GICP_Invalid\n";
2503 for (const auto &Record : ComplexPredicates)
2504 OS << " &" << Target.getName()
2505 << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
2506 << ", // " << Record->getName() << "\n";
2507 OS << "}})\n"
2508 << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002509
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002510 OS << "#ifdef GET_GLOBALISEL_IMPL\n";
2511 SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
2512 OS);
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002513
2514 // Separate subtarget features by how often they must be recomputed.
2515 SubtargetFeatureInfoMap ModuleFeatures;
2516 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2517 std::inserter(ModuleFeatures, ModuleFeatures.end()),
2518 [](const SubtargetFeatureInfoMap::value_type &X) {
2519 return !X.second.mustRecomputePerFunction();
2520 });
2521 SubtargetFeatureInfoMap FunctionFeatures;
2522 std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
2523 std::inserter(FunctionFeatures, FunctionFeatures.end()),
2524 [](const SubtargetFeatureInfoMap::value_type &X) {
2525 return X.second.mustRecomputePerFunction();
2526 });
2527
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002528 SubtargetFeatureInfo::emitComputeAvailableFeatures(
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002529 Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
2530 ModuleFeatures, OS);
2531 SubtargetFeatureInfo::emitComputeAvailableFeatures(
2532 Target.getName(), "InstructionSelector",
2533 "computeAvailableFunctionFeatures", FunctionFeatures, OS,
2534 "const MachineFunction *MF");
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002535
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002536 // Emit a table containing the LLT objects needed by the matcher and an enum
2537 // for the matcher to reference them with.
Daniel Sanderseb2f5f32017-08-15 15:10:31 +00002538 std::vector<LLTCodeGen> TypeObjects = {
2539 LLT::scalar(8), LLT::scalar(16), LLT::scalar(32),
2540 LLT::scalar(64), LLT::scalar(80), LLT::vector(8, 1),
2541 LLT::vector(16, 1), LLT::vector(32, 1), LLT::vector(64, 1),
2542 LLT::vector(8, 8), LLT::vector(16, 8), LLT::vector(32, 8),
2543 LLT::vector(64, 8), LLT::vector(4, 16), LLT::vector(8, 16),
2544 LLT::vector(16, 16), LLT::vector(32, 16), LLT::vector(2, 32),
2545 LLT::vector(4, 32), LLT::vector(8, 32), LLT::vector(16, 32),
2546 LLT::vector(2, 64), LLT::vector(4, 64), LLT::vector(8, 64),
2547 };
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002548 std::sort(TypeObjects.begin(), TypeObjects.end());
2549 OS << "enum {\n";
2550 for (const auto &TypeObject : TypeObjects) {
2551 OS << " ";
2552 TypeObject.emitCxxEnumValue(OS);
2553 OS << ",\n";
2554 }
2555 OS << "};\n"
2556 << "const static LLT TypeObjects[] = {\n";
2557 for (const auto &TypeObject : TypeObjects) {
2558 OS << " ";
2559 TypeObject.emitCxxConstructorCall(OS);
2560 OS << ",\n";
2561 }
2562 OS << "};\n\n";
2563
2564 // Emit a table containing the PredicateBitsets objects needed by the matcher
2565 // and an enum for the matcher to reference them with.
2566 std::vector<std::vector<Record *>> FeatureBitsets;
2567 for (auto &Rule : Rules)
2568 FeatureBitsets.push_back(Rule.getRequiredFeatures());
2569 std::sort(
2570 FeatureBitsets.begin(), FeatureBitsets.end(),
2571 [&](const std::vector<Record *> &A, const std::vector<Record *> &B) {
2572 if (A.size() < B.size())
2573 return true;
2574 if (A.size() > B.size())
2575 return false;
2576 for (const auto &Pair : zip(A, B)) {
2577 if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
2578 return true;
2579 if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
2580 return false;
2581 }
2582 return false;
2583 });
2584 FeatureBitsets.erase(
2585 std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
2586 FeatureBitsets.end());
2587 OS << "enum {\n"
2588 << " GIFBS_Invalid,\n";
2589 for (const auto &FeatureBitset : FeatureBitsets) {
2590 if (FeatureBitset.empty())
2591 continue;
2592 OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
2593 }
2594 OS << "};\n"
2595 << "const static PredicateBitset FeatureBitsets[] {\n"
2596 << " {}, // GIFBS_Invalid\n";
2597 for (const auto &FeatureBitset : FeatureBitsets) {
2598 if (FeatureBitset.empty())
2599 continue;
2600 OS << " {";
2601 for (const auto &Feature : FeatureBitset) {
2602 const auto &I = SubtargetFeatures.find(Feature);
2603 assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
2604 OS << I->second.getEnumBitName() << ", ";
2605 }
2606 OS << "},\n";
2607 }
2608 OS << "};\n\n";
2609
2610 // Emit complex predicate table and an enum to reference them with.
2611 OS << "enum {\n"
2612 << " GICP_Invalid,\n";
2613 for (const auto &Record : ComplexPredicates)
2614 OS << " GICP_" << Record->getName() << ",\n";
2615 OS << "};\n"
2616 << "// See constructor for table contents\n\n";
2617
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002618 OS << "bool " << Target.getName()
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002619 << "InstructionSelector::selectImpl(MachineInstr &I) const {\n"
2620 << " MachineFunction &MF = *I.getParent()->getParent();\n"
Daniel Sanders6ab0daa2017-07-04 14:35:06 +00002621 << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
Daniel Sanders32291982017-06-28 13:50:04 +00002622 << " // FIXME: This should be computed on a per-function basis rather "
2623 "than per-insn.\n"
2624 << " AvailableFunctionFeatures = computeAvailableFunctionFeatures(&STI, "
2625 "&MF);\n"
Daniel Sandersa6cfce62017-07-05 14:50:18 +00002626 << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
2627 << " NewMIVector OutMIs;\n"
2628 << " State.MIs.clear();\n"
2629 << " State.MIs.push_back(&I);\n\n";
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002630
Daniel Sanders8e82af22017-07-27 11:03:45 +00002631 MatchTable Table(0);
Daniel Sandersb96f40d2017-03-20 15:20:42 +00002632 for (auto &Rule : Rules) {
Daniel Sanders8e82af22017-07-27 11:03:45 +00002633 Rule.emit(Table);
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002634 ++NumPatternEmitted;
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002635 }
Daniel Sanders8e82af22017-07-27 11:03:45 +00002636 Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
2637 Table.emitDeclaration(OS);
2638 OS << " if (executeMatchTable(*this, OutMIs, State, MatcherInfo, ";
2639 Table.emitUse(OS);
2640 OS << ", TII, MRI, TRI, RBI, AvailableFeatures)) {\n"
2641 << " return true;\n"
2642 << " }\n\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002643
Daniel Sanders8a4bae92017-03-14 21:32:08 +00002644 OS << " return false;\n"
2645 << "}\n"
2646 << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
Daniel Sanderse9fdba32017-04-29 17:30:09 +00002647
2648 OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
2649 << "PredicateBitset AvailableModuleFeatures;\n"
2650 << "mutable PredicateBitset AvailableFunctionFeatures;\n"
2651 << "PredicateBitset getAvailableFeatures() const {\n"
2652 << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
2653 << "}\n"
2654 << "PredicateBitset\n"
2655 << "computeAvailableModuleFeatures(const " << Target.getName()
2656 << "Subtarget *Subtarget) const;\n"
2657 << "PredicateBitset\n"
2658 << "computeAvailableFunctionFeatures(const " << Target.getName()
2659 << "Subtarget *Subtarget,\n"
2660 << " const MachineFunction *MF) const;\n"
2661 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
2662
2663 OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
2664 << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
2665 << "AvailableFunctionFeatures()\n"
2666 << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002667}
2668
Daniel Sanderse7b0d662017-04-21 15:59:56 +00002669void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
2670 if (SubtargetFeatures.count(Predicate) == 0)
2671 SubtargetFeatures.emplace(
2672 Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
2673}
2674
Ahmed Bougacha982c5eb2017-02-10 04:00:17 +00002675} // end anonymous namespace
2676
Ahmed Bougacha36f70352016-12-21 23:26:20 +00002677//===----------------------------------------------------------------------===//
2678
2679namespace llvm {
2680void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
2681 GlobalISelEmitter(RK).run(OS);
2682}
2683} // End llvm namespace