1 //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 /// This tablegen backend emits code for use by the GlobalISel instruction
12 /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
13 ///
14 /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
15 /// backend, filters out the ones that are unsupported, maps
16 /// SelectionDAG-specific constructs to their GlobalISel counterpart
17 /// (when applicable: MVT to LLT;  SDNode to generic Instruction).
18 ///
19 /// Not all patterns are supported: pass the tablegen invocation
20 /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
21 /// as well as why.
22 ///
23 /// The generated file defines a single method:
24 ///     bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
25 /// intended to be used in InstructionSelector::select as the first-step
26 /// selector for the patterns that don't require complex C++.
27 ///
28 /// FIXME: We'll probably want to eventually define a base
29 /// "TargetGenInstructionSelector" class.
30 ///
31 //===----------------------------------------------------------------------===//
32 
33 #include "CodeGenDAGPatterns.h"
34 #include "llvm/ADT/Optional.h"
35 #include "llvm/ADT/Statistic.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/TableGen/Error.h"
39 #include "llvm/TableGen/Record.h"
40 #include "llvm/TableGen/TableGenBackend.h"
41 #include <string>
42 using namespace llvm;
43 
44 #define DEBUG_TYPE "gisel-emitter"
45 
46 STATISTIC(NumPatternTotal, "Total number of patterns");
47 STATISTIC(NumPatternSkipped, "Number of patterns skipped");
48 STATISTIC(NumPatternEmitted, "Number of patterns emitted");
49 
50 static cl::opt<bool> WarnOnSkippedPatterns(
51     "warn-on-skipped-patterns",
52     cl::desc("Explain why a pattern was skipped for inclusion "
53              "in the GlobalISel selector"),
54     cl::init(false));
55 
56 namespace {
57 
58 class GlobalISelEmitter {
59 public:
60   explicit GlobalISelEmitter(RecordKeeper &RK);
61   void run(raw_ostream &OS);
62 
63 private:
64   const RecordKeeper &RK;
65   const CodeGenDAGPatterns CGP;
66   const CodeGenTarget &Target;
67 
68   /// Keep track of the equivalence between SDNodes and Instruction.
69   /// This is defined using 'GINodeEquiv' in the target description.
70   DenseMap<Record *, const CodeGenInstruction *> NodeEquivs;
71 
72   void gatherNodeEquivs();
73   const CodeGenInstruction *findNodeEquiv(Record *N);
74 
75   struct SkipReason {
76     std::string Reason;
77   };
78 
79   /// Analyze pattern \p P, possibly emitting matching code for it to \p OS.
80   /// Otherwise, return a reason why this pattern was skipped for emission.
81   Optional<SkipReason> runOnPattern(const PatternToMatch &P,
82                                     raw_ostream &OS);
83 };
84 
85 } // end anonymous namespace
86 
87 //===- Helper functions ---------------------------------------------------===//
88 
89 /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
90 /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
91 static Optional<std::string> MVTToLLT(MVT::SimpleValueType SVT) {
92   std::string TyStr;
93   raw_string_ostream OS(TyStr);
94   MVT VT(SVT);
95   if (VT.isVector() && VT.getVectorNumElements() != 1) {
96     OS << "LLT::vector(" << VT.getVectorNumElements() << ", "
97        << VT.getScalarSizeInBits() << ")";
98   } else if (VT.isInteger() || VT.isFloatingPoint()) {
99     OS << "LLT::scalar(" << VT.getSizeInBits() << ")";
100   } else {
101     return None;
102   }
103   OS.flush();
104   return TyStr;
105 }
106 
107 static bool isTrivialOperatorNode(const TreePatternNode *N) {
108   return !N->isLeaf() && !N->hasAnyPredicate() && !N->getTransformFn();
109 }
110 
111 //===- Matchers -----------------------------------------------------------===//
112 
113 template <class PredicateTy> class PredicateListMatcher {
114 private:
115   typedef std::vector<std::unique_ptr<PredicateTy>> PredicateVec;
116   PredicateVec Predicates;
117 
118 public:
119   /// Construct a new operand predicate and add it to the matcher.
120   template <class Kind, class... Args>
121   Kind &addPredicate(Args&&... args) {
122     Predicates.emplace_back(
123         llvm::make_unique<Kind>(std::forward<Args>(args)...));
124     return *static_cast<Kind *>(Predicates.back().get());
125   }
126 
127   typename PredicateVec::const_iterator predicates_begin() const { return Predicates.begin(); }
128   typename PredicateVec::const_iterator predicates_end() const { return Predicates.end(); }
129   iterator_range<typename PredicateVec::const_iterator> predicates() const {
130     return make_range(predicates_begin(), predicates_end());
131   }
132 
133   /// Emit a C++ expression that tests whether all the predicates are met.
134   template <class... Args>
135   void emitCxxPredicateListExpr(raw_ostream &OS, Args &&... args) const {
136     if (Predicates.empty()) {
137       OS << "true";
138       return;
139     }
140 
141     StringRef Separator = "";
142     for (const auto &Predicate : predicates()) {
143       OS << Separator << "(";
144       Predicate->emitCxxPredicateExpr(OS, std::forward<Args>(args)...);
145       OS << ")";
146       Separator = " &&\n";
147     }
148   }
149 };
150 
151 /// Generates code to check a predicate of an operand.
152 ///
153 /// Typical predicates include:
154 /// * Operand is a particular register.
155 /// * Operand is assigned a particular register bank.
156 /// * Operand is an MBB.
157 class OperandPredicateMatcher {
158 public:
159   virtual ~OperandPredicateMatcher() {}
160 
161   /// Emit a C++ expression that checks the predicate for the OpIdx operand of
162   /// the instruction given in InsnVarName.
163   virtual void emitCxxPredicateExpr(raw_ostream &OS,
164                                     const StringRef InsnVarName,
165                                     unsigned OpIdx) const = 0;
166 };
167 
168 /// Generates code to check that an operand is a particular LLT.
169 class LLTOperandMatcher : public OperandPredicateMatcher {
170 protected:
171   std::string Ty;
172 
173 public:
174   LLTOperandMatcher(std::string Ty) : Ty(Ty) {}
175 
176   void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName,
177                             unsigned OpIdx) const override {
178     OS << "MRI.getType(" << InsnVarName << ".getOperand(" << OpIdx
179        << ").getReg()) == (" << Ty << ")";
180   }
181 };
182 
183 /// Generates code to check that an operand is in a particular register bank.
184 class RegisterBankOperandMatcher : public OperandPredicateMatcher {
185 protected:
186   const CodeGenRegisterClass &RC;
187 
188 public:
189   RegisterBankOperandMatcher(const CodeGenRegisterClass &RC) : RC(RC) {}
190 
191   void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName,
192                             unsigned OpIdx) const override {
193     OS << "(&RBI.getRegBankFromRegClass(" << RC.getQualifiedName()
194        << "RegClass) == RBI.getRegBank(" << InsnVarName << ".getOperand("
195        << OpIdx << ").getReg(), MRI, TRI))";
196   }
197 };
198 
199 /// Generates code to check that an operand is a basic block.
200 class MBBOperandMatcher : public OperandPredicateMatcher {
201 public:
202   void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName,
203                             unsigned OpIdx) const override {
204     OS << InsnVarName << ".getOperand(" << OpIdx << ").isMBB()";
205   }
206 };
207 
208 /// Generates code to check that a set of predicates match for a particular
209 /// operand.
210 class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
211 protected:
212   unsigned OpIdx;
213 
214 public:
215   OperandMatcher(unsigned OpIdx) : OpIdx(OpIdx) {}
216 
217   /// Emit a C++ expression that tests whether the instruction named in
218   /// InsnVarName matches all the predicate and all the operands.
219   void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName) const {
220     OS << "(";
221     emitCxxPredicateListExpr(OS, InsnVarName, OpIdx);
222     OS << ")";
223   }
224 };
225 
226 /// Generates code to check a predicate on an instruction.
227 ///
228 /// Typical predicates include:
229 /// * The opcode of the instruction is a particular value.
230 /// * The nsw/nuw flag is/isn't set.
231 class InstructionPredicateMatcher {
232 public:
233   virtual ~InstructionPredicateMatcher() {}
234 
235   /// Emit a C++ expression that tests whether the instruction named in
236   /// InsnVarName matches the predicate.
237   virtual void emitCxxPredicateExpr(raw_ostream &OS,
238                                     const StringRef InsnVarName) const = 0;
239 };
240 
241 /// Generates code to check the opcode of an instruction.
242 class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
243 protected:
244   const CodeGenInstruction *I;
245 
246 public:
247   InstructionOpcodeMatcher(const CodeGenInstruction *I) : I(I) {}
248 
249   void emitCxxPredicateExpr(raw_ostream &OS,
250                             const StringRef InsnVarName) const override {
251     OS << InsnVarName << ".getOpcode() == " << I->Namespace
252        << "::" << I->TheDef->getName();
253   }
254 };
255 
256 /// Generates code to check that a set of predicates and operands match for a
257 /// particular instruction.
258 ///
259 /// Typical predicates include:
260 /// * Has a specific opcode.
261 /// * Has an nsw/nuw flag or doesn't.
262 class InstructionMatcher
263     : public PredicateListMatcher<InstructionPredicateMatcher> {
264 protected:
265   std::vector<OperandMatcher> Operands;
266 
267 public:
268   /// Add an operand to the matcher.
269   OperandMatcher &addOperand(unsigned OpIdx) {
270     Operands.emplace_back(OpIdx);
271     return Operands.back();
272   }
273 
274   /// Emit a C++ expression that tests whether the instruction named in
275   /// InsnVarName matches all the predicates and all the operands.
276   void emitCxxPredicateExpr(raw_ostream &OS, const StringRef InsnVarName) const {
277     emitCxxPredicateListExpr(OS, InsnVarName);
278     for (const auto &Operand : Operands) {
279       OS << " &&\n(";
280       Operand.emitCxxPredicateExpr(OS, InsnVarName);
281       OS << ")";
282     }
283   }
284 };
285 
286 //===- Actions ------------------------------------------------------------===//
287 
288 /// An action taken when all Matcher predicates succeeded for a parent rule.
289 ///
290 /// Typical actions include:
291 /// * Changing the opcode of an instruction.
292 /// * Adding an operand to an instruction.
293 class MatchAction {
294 public:
295   virtual ~MatchAction() {}
296   virtual void emitCxxActionStmts(raw_ostream &OS) const = 0;
297 };
298 
299 /// Generates a comment describing the matched rule being acted upon.
300 class DebugCommentAction : public MatchAction {
301 private:
302   const PatternToMatch &P;
303 
304 public:
305   DebugCommentAction(const PatternToMatch &P) : P(P) {}
306 
307   virtual void emitCxxActionStmts(raw_ostream &OS) const {
308     OS << "// " << *P.getSrcPattern() << "  =>  " << *P.getDstPattern();
309   }
310 };
311 
312 /// Generates code to set the opcode (really, the MCInstrDesc) of a matched
313 /// instruction to a given Instruction.
314 class MutateOpcodeAction : public MatchAction {
315 private:
316   const CodeGenInstruction *I;
317 
318 public:
319   MutateOpcodeAction(const CodeGenInstruction *I) : I(I) {}
320 
321   virtual void emitCxxActionStmts(raw_ostream &OS) const {
322     OS << "I.setDesc(TII.get(" << I->Namespace << "::" << I->TheDef->getName()
323        << "));";
324   }
325 };
326 
327 /// Generates code to check that a match rule matches.
328 class RuleMatcher {
329   /// A list of matchers that all need to succeed for the current rule to match.
330   /// FIXME: This currently supports a single match position but could be
331   /// extended to support multiple positions to support div/rem fusion or
332   /// load-multiple instructions.
333   std::vector<std::unique_ptr<InstructionMatcher>> Matchers;
334 
335   /// A list of actions that need to be taken when all predicates in this rule
336   /// have succeeded.
337   std::vector<std::unique_ptr<MatchAction>> Actions;
338 
339 public:
340   RuleMatcher() {}
341 
342   InstructionMatcher &addInstructionMatcher() {
343     Matchers.emplace_back(new InstructionMatcher());
344     return *Matchers.back();
345   }
346 
347   template <class Kind, class... Args>
348   Kind &addAction(Args&&... args) {
349     Actions.emplace_back(llvm::make_unique<Kind>(std::forward<Args>(args)...));
350     return *static_cast<Kind *>(Actions.back().get());
351   }
352 
353   void emit(raw_ostream &OS) {
354     if (Matchers.empty())
355       llvm_unreachable("Unexpected empty matcher!");
356 
357     // The representation supports rules that require multiple roots such as:
358     //    %ptr(p0) = ...
359     //    %elt0(s32) = G_LOAD %ptr
360     //    %1(p0) = G_ADD %ptr, 4
361     //    %elt1(s32) = G_LOAD p0 %1
362     // which could be usefully folded into:
363     //    %ptr(p0) = ...
364     //    %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
365     // on some targets but we don't need to make use of that yet.
366     assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
367     OS << "  if (";
368     Matchers.front()->emitCxxPredicateExpr(OS, "I");
369     OS << ") {\n";
370 
371     for (const auto &MA : Actions) {
372       OS << "    ";
373       MA->emitCxxActionStmts(OS);
374       OS << "\n";
375     }
376 
377     OS << "    constrainSelectedInstRegOperands(I, TII, TRI, RBI);\n";
378     OS << "    return true;\n";
379     OS << "  }\n\n";
380   }
381 };
382 
383 //===- GlobalISelEmitter class --------------------------------------------===//
384 
385 void GlobalISelEmitter::gatherNodeEquivs() {
386   assert(NodeEquivs.empty());
387   for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
388     NodeEquivs[Equiv->getValueAsDef("Node")] =
389         &Target.getInstruction(Equiv->getValueAsDef("I"));
390 }
391 
392 const CodeGenInstruction *GlobalISelEmitter::findNodeEquiv(Record *N) {
393   return NodeEquivs.lookup(N);
394 }
395 
396 GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
397     : RK(RK), CGP(RK), Target(CGP.getTargetInfo()) {}
398 
399 //===- Emitter ------------------------------------------------------------===//
400 
401 Optional<GlobalISelEmitter::SkipReason>
402 GlobalISelEmitter::runOnPattern(const PatternToMatch &P, raw_ostream &OS) {
403 
404   // Keep track of the matchers and actions to emit.
405   RuleMatcher M;
406   M.addAction<DebugCommentAction>(P);
407 
408   // First, analyze the whole pattern.
409   // If the entire pattern has a predicate (e.g., target features), ignore it.
410   if (!P.getPredicates()->getValues().empty())
411     return SkipReason{"Pattern has a predicate"};
412 
413   // Physreg imp-defs require additional logic.  Ignore the pattern.
414   if (!P.getDstRegs().empty())
415     return SkipReason{"Pattern defines a physical register"};
416 
417   // Next, analyze the pattern operators.
418   TreePatternNode *Src = P.getSrcPattern();
419   TreePatternNode *Dst = P.getDstPattern();
420 
421   // If the root of either pattern isn't a simple operator, ignore it.
422   if (!isTrivialOperatorNode(Dst))
423     return SkipReason{"Dst pattern root isn't a trivial operator"};
424   if (!isTrivialOperatorNode(Src))
425     return SkipReason{"Src pattern root isn't a trivial operator"};
426 
427   Record *DstOp = Dst->getOperator();
428   if (!DstOp->isSubClassOf("Instruction"))
429     return SkipReason{"Pattern operator isn't an instruction"};
430 
431   auto &DstI = Target.getInstruction(DstOp);
432 
433   auto SrcGIOrNull = findNodeEquiv(Src->getOperator());
434   if (!SrcGIOrNull)
435     return SkipReason{"Pattern operator lacks an equivalent Instruction"};
436   auto &SrcGI = *SrcGIOrNull;
437 
438   // The operators look good: match the opcode and mutate it to the new one.
439   InstructionMatcher &InsnMatcher = M.addInstructionMatcher();
440   InsnMatcher.addPredicate<InstructionOpcodeMatcher>(&SrcGI);
441   M.addAction<MutateOpcodeAction>(&DstI);
442 
443   // Next, analyze the children, only accepting patterns that don't require
444   // any change to operands.
445   if (Src->getNumChildren() != Dst->getNumChildren())
446     return SkipReason{"Src/dst patterns have a different # of children"};
447 
448   unsigned OpIdx = 0;
449 
450   // Start with the defined operands (i.e., the results of the root operator).
451   if (DstI.Operands.NumDefs != Src->getExtTypes().size())
452     return SkipReason{"Src pattern results and dst MI defs are different"};
453 
454   for (const EEVT::TypeSet &Ty : Src->getExtTypes()) {
455     Record *DstIOpRec = DstI.Operands[OpIdx].Rec;
456     if (!DstIOpRec->isSubClassOf("RegisterClass"))
457       return SkipReason{"Dst MI def isn't a register class"};
458 
459     auto OpTyOrNone = MVTToLLT(Ty.getConcrete());
460     if (!OpTyOrNone)
461       return SkipReason{"Dst operand has an unsupported type"};
462 
463     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
464     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
465     OM.addPredicate<RegisterBankOperandMatcher>(
466         Target.getRegisterClass(DstIOpRec));
467     ++OpIdx;
468   }
469 
470   // Finally match the used operands (i.e., the children of the root operator).
471   for (unsigned i = 0, e = Src->getNumChildren(); i != e; ++i) {
472     auto *SrcChild = Src->getChild(i);
473     auto *DstChild = Dst->getChild(i);
474 
475     // Patterns can reorder operands.  Ignore those for now.
476     if (SrcChild->getName() != DstChild->getName())
477       return SkipReason{"Src/dst pattern children not in same order"};
478 
479     // The only non-leaf child we accept is 'bb': it's an operator because
480     // BasicBlockSDNode isn't inline, but in MI it's just another operand.
481     if (!SrcChild->isLeaf()) {
482       if (DstChild->isLeaf() ||
483           SrcChild->getOperator() != DstChild->getOperator())
484         return SkipReason{"Src/dst pattern child operator mismatch"};
485 
486       if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
487         auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
488         if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
489           InsnMatcher.addOperand(OpIdx++).addPredicate<MBBOperandMatcher>();
490           continue;
491         }
492       }
493       return SkipReason{"Src pattern child isn't a leaf node"};
494     }
495 
496     if (SrcChild->getLeafValue() != DstChild->getLeafValue())
497       return SkipReason{"Src/dst pattern child leaf mismatch"};
498 
499     // Otherwise, we're looking for a bog-standard RegisterClass operand.
500     if (SrcChild->hasAnyPredicate())
501       return SkipReason{"Src pattern child has predicate"};
502     auto *ChildRec = cast<DefInit>(SrcChild->getLeafValue())->getDef();
503     if (!ChildRec->isSubClassOf("RegisterClass"))
504       return SkipReason{"Src pattern child isn't a RegisterClass"};
505 
506     ArrayRef<EEVT::TypeSet> ChildTypes = SrcChild->getExtTypes();
507     if (ChildTypes.size() != 1)
508       return SkipReason{"Src pattern child has multiple results"};
509 
510     auto OpTyOrNone = MVTToLLT(ChildTypes.front().getConcrete());
511     if (!OpTyOrNone)
512       return SkipReason{"Src operand has an unsupported type"};
513 
514     OperandMatcher &OM = InsnMatcher.addOperand(OpIdx);
515     OM.addPredicate<LLTOperandMatcher>(*OpTyOrNone);
516     OM.addPredicate<RegisterBankOperandMatcher>(
517         Target.getRegisterClass(ChildRec));
518     ++OpIdx;
519   }
520 
521   // We're done with this pattern!  Emit the processed result.
522   M.emit(OS);
523   ++NumPatternEmitted;
524   return None;
525 }
526 
527 void GlobalISelEmitter::run(raw_ostream &OS) {
528   // Track the GINodeEquiv definitions.
529   gatherNodeEquivs();
530 
531   emitSourceFileHeader(("Global Instruction Selector for the " +
532                        Target.getName() + " target").str(), OS);
533   OS << "bool " << Target.getName()
534      << "InstructionSelector::selectImpl"
535         "(MachineInstr &I) const {\n  const MachineRegisterInfo &MRI = "
536         "I.getParent()->getParent()->getRegInfo();\n\n";
537 
538   // Look through the SelectionDAG patterns we found, possibly emitting some.
539   for (const PatternToMatch &Pat : CGP.ptms()) {
540     ++NumPatternTotal;
541     if (auto SkipReason = runOnPattern(Pat, OS)) {
542       if (WarnOnSkippedPatterns) {
543         PrintWarning(Pat.getSrcRecord()->getLoc(),
544                      "Skipped pattern: " + SkipReason->Reason);
545       }
546       ++NumPatternSkipped;
547     }
548   }
549 
550   OS << "  return false;\n}\n";
551 }
552 
553 //===----------------------------------------------------------------------===//
554 
555 namespace llvm {
556 void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
557   GlobalISelEmitter(RK).run(OS);
558 }
559 } // End llvm namespace
560