1//===- DAGISelMatcherGen.cpp - Matcher generator --------------------------===//
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#include "DAGISelMatcher.h"
11#include "CodeGenDAGPatterns.h"
12#include "CodeGenRegisters.h"
13#include "llvm/TableGen/Record.h"
14#include "llvm/ADT/DenseMap.h"
15#include "llvm/ADT/SmallVector.h"
16#include "llvm/ADT/StringMap.h"
17#include <utility>
18using namespace llvm;
19
20
21/// getRegisterValueType - Look up and return the ValueType of the specified
22/// register. If the register is a member of multiple register classes which
23/// have different associated types, return MVT::Other.
24static MVT::SimpleValueType getRegisterValueType(Record *R,
25                                                 const CodeGenTarget &T) {
26  bool FoundRC = false;
27  MVT::SimpleValueType VT = MVT::Other;
28  const CodeGenRegister *Reg = T.getRegBank().getReg(R);
29  ArrayRef<CodeGenRegisterClass*> RCs = T.getRegBank().getRegClasses();
30
31  for (unsigned rc = 0, e = RCs.size(); rc != e; ++rc) {
32    const CodeGenRegisterClass &RC = *RCs[rc];
33    if (!RC.contains(Reg))
34      continue;
35
36    if (!FoundRC) {
37      FoundRC = true;
38      VT = RC.getValueTypeNum(0);
39      continue;
40    }
41
42    // If this occurs in multiple register classes, they all have to agree.
43    assert(VT == RC.getValueTypeNum(0));
44  }
45  return VT;
46}
47
48
49namespace {
50  class MatcherGen {
51    const PatternToMatch &Pattern;
52    const CodeGenDAGPatterns &CGP;
53
54    /// PatWithNoTypes - This is a clone of Pattern.getSrcPattern() that starts
55    /// out with all of the types removed.  This allows us to insert type checks
56    /// as we scan the tree.
57    TreePatternNode *PatWithNoTypes;
58
59    /// VariableMap - A map from variable names ('$dst') to the recorded operand
60    /// number that they were captured as.  These are biased by 1 to make
61    /// insertion easier.
62    StringMap<unsigned> VariableMap;
63
64    /// NextRecordedOperandNo - As we emit opcodes to record matched values in
65    /// the RecordedNodes array, this keeps track of which slot will be next to
66    /// record into.
67    unsigned NextRecordedOperandNo;
68
69    /// MatchedChainNodes - This maintains the position in the recorded nodes
70    /// array of all of the recorded input nodes that have chains.
71    SmallVector<unsigned, 2> MatchedChainNodes;
72
73    /// MatchedGlueResultNodes - This maintains the position in the recorded
74    /// nodes array of all of the recorded input nodes that have glue results.
75    SmallVector<unsigned, 2> MatchedGlueResultNodes;
76
77    /// MatchedComplexPatterns - This maintains a list of all of the
78    /// ComplexPatterns that we need to check.  The patterns are known to have
79    /// names which were recorded.  The second element of each pair is the first
80    /// slot number that the OPC_CheckComplexPat opcode drops the matched
81    /// results into.
82    SmallVector<std::pair<const TreePatternNode*,
83                          unsigned>, 2> MatchedComplexPatterns;
84
85    /// PhysRegInputs - List list has an entry for each explicitly specified
86    /// physreg input to the pattern.  The first elt is the Register node, the
87    /// second is the recorded slot number the input pattern match saved it in.
88    SmallVector<std::pair<Record*, unsigned>, 2> PhysRegInputs;
89
90    /// Matcher - This is the top level of the generated matcher, the result.
91    Matcher *TheMatcher;
92
93    /// CurPredicate - As we emit matcher nodes, this points to the latest check
94    /// which should have future checks stuck into its Next position.
95    Matcher *CurPredicate;
96  public:
97    MatcherGen(const PatternToMatch &pattern, const CodeGenDAGPatterns &cgp);
98
99    ~MatcherGen() {
100      delete PatWithNoTypes;
101    }
102
103    bool EmitMatcherCode(unsigned Variant);
104    void EmitResultCode();
105
106    Matcher *GetMatcher() const { return TheMatcher; }
107  private:
108    void AddMatcher(Matcher *NewNode);
109    void InferPossibleTypes();
110
111    // Matcher Generation.
112    void EmitMatchCode(const TreePatternNode *N, TreePatternNode *NodeNoTypes);
113    void EmitLeafMatchCode(const TreePatternNode *N);
114    void EmitOperatorMatchCode(const TreePatternNode *N,
115                               TreePatternNode *NodeNoTypes);
116
117    // Result Code Generation.
118    unsigned getNamedArgumentSlot(StringRef Name) {
119      unsigned VarMapEntry = VariableMap[Name];
120      assert(VarMapEntry != 0 &&
121             "Variable referenced but not defined and not caught earlier!");
122      return VarMapEntry-1;
123    }
124
125    /// GetInstPatternNode - Get the pattern for an instruction.
126    const TreePatternNode *GetInstPatternNode(const DAGInstruction &Ins,
127                                              const TreePatternNode *N);
128
129    void EmitResultOperand(const TreePatternNode *N,
130                           SmallVectorImpl<unsigned> &ResultOps);
131    void EmitResultOfNamedOperand(const TreePatternNode *N,
132                                  SmallVectorImpl<unsigned> &ResultOps);
133    void EmitResultLeafAsOperand(const TreePatternNode *N,
134                                 SmallVectorImpl<unsigned> &ResultOps);
135    void EmitResultInstructionAsOperand(const TreePatternNode *N,
136                                        SmallVectorImpl<unsigned> &ResultOps);
137    void EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
138                                        SmallVectorImpl<unsigned> &ResultOps);
139    };
140
141} // end anon namespace.
142
143MatcherGen::MatcherGen(const PatternToMatch &pattern,
144                       const CodeGenDAGPatterns &cgp)
145: Pattern(pattern), CGP(cgp), NextRecordedOperandNo(0),
146  TheMatcher(0), CurPredicate(0) {
147  // We need to produce the matcher tree for the patterns source pattern.  To do
148  // this we need to match the structure as well as the types.  To do the type
149  // matching, we want to figure out the fewest number of type checks we need to
150  // emit.  For example, if there is only one integer type supported by a
151  // target, there should be no type comparisons at all for integer patterns!
152  //
153  // To figure out the fewest number of type checks needed, clone the pattern,
154  // remove the types, then perform type inference on the pattern as a whole.
155  // If there are unresolved types, emit an explicit check for those types,
156  // apply the type to the tree, then rerun type inference.  Iterate until all
157  // types are resolved.
158  //
159  PatWithNoTypes = Pattern.getSrcPattern()->clone();
160  PatWithNoTypes->RemoveAllTypes();
161
162  // If there are types that are manifestly known, infer them.
163  InferPossibleTypes();
164}
165
166/// InferPossibleTypes - As we emit the pattern, we end up generating type
167/// checks and applying them to the 'PatWithNoTypes' tree.  As we do this, we
168/// want to propagate implied types as far throughout the tree as possible so
169/// that we avoid doing redundant type checks.  This does the type propagation.
170void MatcherGen::InferPossibleTypes() {
171  // TP - Get *SOME* tree pattern, we don't care which.  It is only used for
172  // diagnostics, which we know are impossible at this point.
173  TreePattern &TP = *CGP.pf_begin()->second;
174
175  try {
176    bool MadeChange = true;
177    while (MadeChange)
178      MadeChange = PatWithNoTypes->ApplyTypeConstraints(TP,
179                                                true/*Ignore reg constraints*/);
180  } catch (...) {
181    errs() << "Type constraint application shouldn't fail!";
182    abort();
183  }
184}
185
186
187/// AddMatcher - Add a matcher node to the current graph we're building.
188void MatcherGen::AddMatcher(Matcher *NewNode) {
189  if (CurPredicate != 0)
190    CurPredicate->setNext(NewNode);
191  else
192    TheMatcher = NewNode;
193  CurPredicate = NewNode;
194}
195
196
197//===----------------------------------------------------------------------===//
198// Pattern Match Generation
199//===----------------------------------------------------------------------===//
200
201/// EmitLeafMatchCode - Generate matching code for leaf nodes.
202void MatcherGen::EmitLeafMatchCode(const TreePatternNode *N) {
203  assert(N->isLeaf() && "Not a leaf?");
204
205  // Direct match against an integer constant.
206  if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
207    // If this is the root of the dag we're matching, we emit a redundant opcode
208    // check to ensure that this gets folded into the normal top-level
209    // OpcodeSwitch.
210    if (N == Pattern.getSrcPattern()) {
211      const SDNodeInfo &NI = CGP.getSDNodeInfo(CGP.getSDNodeNamed("imm"));
212      AddMatcher(new CheckOpcodeMatcher(NI));
213    }
214
215    return AddMatcher(new CheckIntegerMatcher(II->getValue()));
216  }
217
218  DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue());
219  if (DI == 0) {
220    errs() << "Unknown leaf kind: " << *N << "\n";
221    abort();
222  }
223
224  Record *LeafRec = DI->getDef();
225  if (// Handle register references.  Nothing to do here, they always match.
226      LeafRec->isSubClassOf("RegisterClass") ||
227      LeafRec->isSubClassOf("RegisterOperand") ||
228      LeafRec->isSubClassOf("PointerLikeRegClass") ||
229      LeafRec->isSubClassOf("SubRegIndex") ||
230      // Place holder for SRCVALUE nodes. Nothing to do here.
231      LeafRec->getName() == "srcvalue")
232    return;
233
234  // If we have a physreg reference like (mul gpr:$src, EAX) then we need to
235  // record the register
236  if (LeafRec->isSubClassOf("Register")) {
237    AddMatcher(new RecordMatcher("physreg input "+LeafRec->getName(),
238                                 NextRecordedOperandNo));
239    PhysRegInputs.push_back(std::make_pair(LeafRec, NextRecordedOperandNo++));
240    return;
241  }
242
243  if (LeafRec->isSubClassOf("ValueType"))
244    return AddMatcher(new CheckValueTypeMatcher(LeafRec->getName()));
245
246  if (LeafRec->isSubClassOf("CondCode"))
247    return AddMatcher(new CheckCondCodeMatcher(LeafRec->getName()));
248
249  if (LeafRec->isSubClassOf("ComplexPattern")) {
250    // We can't model ComplexPattern uses that don't have their name taken yet.
251    // The OPC_CheckComplexPattern operation implicitly records the results.
252    if (N->getName().empty()) {
253      errs() << "We expect complex pattern uses to have names: " << *N << "\n";
254      exit(1);
255    }
256
257    // Remember this ComplexPattern so that we can emit it after all the other
258    // structural matches are done.
259    MatchedComplexPatterns.push_back(std::make_pair(N, 0));
260    return;
261  }
262
263  errs() << "Unknown leaf kind: " << *N << "\n";
264  abort();
265}
266
267void MatcherGen::EmitOperatorMatchCode(const TreePatternNode *N,
268                                       TreePatternNode *NodeNoTypes) {
269  assert(!N->isLeaf() && "Not an operator?");
270  const SDNodeInfo &CInfo = CGP.getSDNodeInfo(N->getOperator());
271
272  // If this is an 'and R, 1234' where the operation is AND/OR and the RHS is
273  // a constant without a predicate fn that has more that one bit set, handle
274  // this as a special case.  This is usually for targets that have special
275  // handling of certain large constants (e.g. alpha with it's 8/16/32-bit
276  // handling stuff).  Using these instructions is often far more efficient
277  // than materializing the constant.  Unfortunately, both the instcombiner
278  // and the dag combiner can often infer that bits are dead, and thus drop
279  // them from the mask in the dag.  For example, it might turn 'AND X, 255'
280  // into 'AND X, 254' if it knows the low bit is set.  Emit code that checks
281  // to handle this.
282  if ((N->getOperator()->getName() == "and" ||
283       N->getOperator()->getName() == "or") &&
284      N->getChild(1)->isLeaf() && N->getChild(1)->getPredicateFns().empty() &&
285      N->getPredicateFns().empty()) {
286    if (IntInit *II = dynamic_cast<IntInit*>(N->getChild(1)->getLeafValue())) {
287      if (!isPowerOf2_32(II->getValue())) {  // Don't bother with single bits.
288        // If this is at the root of the pattern, we emit a redundant
289        // CheckOpcode so that the following checks get factored properly under
290        // a single opcode check.
291        if (N == Pattern.getSrcPattern())
292          AddMatcher(new CheckOpcodeMatcher(CInfo));
293
294        // Emit the CheckAndImm/CheckOrImm node.
295        if (N->getOperator()->getName() == "and")
296          AddMatcher(new CheckAndImmMatcher(II->getValue()));
297        else
298          AddMatcher(new CheckOrImmMatcher(II->getValue()));
299
300        // Match the LHS of the AND as appropriate.
301        AddMatcher(new MoveChildMatcher(0));
302        EmitMatchCode(N->getChild(0), NodeNoTypes->getChild(0));
303        AddMatcher(new MoveParentMatcher());
304        return;
305      }
306    }
307  }
308
309  // Check that the current opcode lines up.
310  AddMatcher(new CheckOpcodeMatcher(CInfo));
311
312  // If this node has memory references (i.e. is a load or store), tell the
313  // interpreter to capture them in the memref array.
314  if (N->NodeHasProperty(SDNPMemOperand, CGP))
315    AddMatcher(new RecordMemRefMatcher());
316
317  // If this node has a chain, then the chain is operand #0 is the SDNode, and
318  // the child numbers of the node are all offset by one.
319  unsigned OpNo = 0;
320  if (N->NodeHasProperty(SDNPHasChain, CGP)) {
321    // Record the node and remember it in our chained nodes list.
322    AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
323                                         "' chained node",
324                                 NextRecordedOperandNo));
325    // Remember all of the input chains our pattern will match.
326    MatchedChainNodes.push_back(NextRecordedOperandNo++);
327
328    // Don't look at the input chain when matching the tree pattern to the
329    // SDNode.
330    OpNo = 1;
331
332    // If this node is not the root and the subtree underneath it produces a
333    // chain, then the result of matching the node is also produce a chain.
334    // Beyond that, this means that we're also folding (at least) the root node
335    // into the node that produce the chain (for example, matching
336    // "(add reg, (load ptr))" as a add_with_memory on X86).  This is
337    // problematic, if the 'reg' node also uses the load (say, its chain).
338    // Graphically:
339    //
340    //         [LD]
341    //         ^  ^
342    //         |  \                              DAG's like cheese.
343    //        /    |
344    //       /    [YY]
345    //       |     ^
346    //      [XX]--/
347    //
348    // It would be invalid to fold XX and LD.  In this case, folding the two
349    // nodes together would induce a cycle in the DAG, making it a 'cyclic DAG'
350    // To prevent this, we emit a dynamic check for legality before allowing
351    // this to be folded.
352    //
353    const TreePatternNode *Root = Pattern.getSrcPattern();
354    if (N != Root) {                             // Not the root of the pattern.
355      // If there is a node between the root and this node, then we definitely
356      // need to emit the check.
357      bool NeedCheck = !Root->hasChild(N);
358
359      // If it *is* an immediate child of the root, we can still need a check if
360      // the root SDNode has multiple inputs.  For us, this means that it is an
361      // intrinsic, has multiple operands, or has other inputs like chain or
362      // glue).
363      if (!NeedCheck) {
364        const SDNodeInfo &PInfo = CGP.getSDNodeInfo(Root->getOperator());
365        NeedCheck =
366          Root->getOperator() == CGP.get_intrinsic_void_sdnode() ||
367          Root->getOperator() == CGP.get_intrinsic_w_chain_sdnode() ||
368          Root->getOperator() == CGP.get_intrinsic_wo_chain_sdnode() ||
369          PInfo.getNumOperands() > 1 ||
370          PInfo.hasProperty(SDNPHasChain) ||
371          PInfo.hasProperty(SDNPInGlue) ||
372          PInfo.hasProperty(SDNPOptInGlue);
373      }
374
375      if (NeedCheck)
376        AddMatcher(new CheckFoldableChainNodeMatcher());
377    }
378  }
379
380  // If this node has an output glue and isn't the root, remember it.
381  if (N->NodeHasProperty(SDNPOutGlue, CGP) &&
382      N != Pattern.getSrcPattern()) {
383    // TODO: This redundantly records nodes with both glues and chains.
384
385    // Record the node and remember it in our chained nodes list.
386    AddMatcher(new RecordMatcher("'" + N->getOperator()->getName() +
387                                         "' glue output node",
388                                 NextRecordedOperandNo));
389    // Remember all of the nodes with output glue our pattern will match.
390    MatchedGlueResultNodes.push_back(NextRecordedOperandNo++);
391  }
392
393  // If this node is known to have an input glue or if it *might* have an input
394  // glue, capture it as the glue input of the pattern.
395  if (N->NodeHasProperty(SDNPOptInGlue, CGP) ||
396      N->NodeHasProperty(SDNPInGlue, CGP))
397    AddMatcher(new CaptureGlueInputMatcher());
398
399  for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i, ++OpNo) {
400    // Get the code suitable for matching this child.  Move to the child, check
401    // it then move back to the parent.
402    AddMatcher(new MoveChildMatcher(OpNo));
403    EmitMatchCode(N->getChild(i), NodeNoTypes->getChild(i));
404    AddMatcher(new MoveParentMatcher());
405  }
406}
407
408
409void MatcherGen::EmitMatchCode(const TreePatternNode *N,
410                               TreePatternNode *NodeNoTypes) {
411  // If N and NodeNoTypes don't agree on a type, then this is a case where we
412  // need to do a type check.  Emit the check, apply the tyep to NodeNoTypes and
413  // reinfer any correlated types.
414  SmallVector<unsigned, 2> ResultsToTypeCheck;
415
416  for (unsigned i = 0, e = NodeNoTypes->getNumTypes(); i != e; ++i) {
417    if (NodeNoTypes->getExtType(i) == N->getExtType(i)) continue;
418    NodeNoTypes->setType(i, N->getExtType(i));
419    InferPossibleTypes();
420    ResultsToTypeCheck.push_back(i);
421  }
422
423  // If this node has a name associated with it, capture it in VariableMap. If
424  // we already saw this in the pattern, emit code to verify dagness.
425  if (!N->getName().empty()) {
426    unsigned &VarMapEntry = VariableMap[N->getName()];
427    if (VarMapEntry == 0) {
428      // If it is a named node, we must emit a 'Record' opcode.
429      AddMatcher(new RecordMatcher("$" + N->getName(), NextRecordedOperandNo));
430      VarMapEntry = ++NextRecordedOperandNo;
431    } else {
432      // If we get here, this is a second reference to a specific name.  Since
433      // we already have checked that the first reference is valid, we don't
434      // have to recursively match it, just check that it's the same as the
435      // previously named thing.
436      AddMatcher(new CheckSameMatcher(VarMapEntry-1));
437      return;
438    }
439  }
440
441  if (N->isLeaf())
442    EmitLeafMatchCode(N);
443  else
444    EmitOperatorMatchCode(N, NodeNoTypes);
445
446  // If there are node predicates for this node, generate their checks.
447  for (unsigned i = 0, e = N->getPredicateFns().size(); i != e; ++i)
448    AddMatcher(new CheckPredicateMatcher(N->getPredicateFns()[i]));
449
450  for (unsigned i = 0, e = ResultsToTypeCheck.size(); i != e; ++i)
451    AddMatcher(new CheckTypeMatcher(N->getType(ResultsToTypeCheck[i]),
452                                    ResultsToTypeCheck[i]));
453}
454
455/// EmitMatcherCode - Generate the code that matches the predicate of this
456/// pattern for the specified Variant.  If the variant is invalid this returns
457/// true and does not generate code, if it is valid, it returns false.
458bool MatcherGen::EmitMatcherCode(unsigned Variant) {
459  // If the root of the pattern is a ComplexPattern and if it is specified to
460  // match some number of root opcodes, these are considered to be our variants.
461  // Depending on which variant we're generating code for, emit the root opcode
462  // check.
463  if (const ComplexPattern *CP =
464                   Pattern.getSrcPattern()->getComplexPatternInfo(CGP)) {
465    const std::vector<Record*> &OpNodes = CP->getRootNodes();
466    assert(!OpNodes.empty() &&"Complex Pattern must specify what it can match");
467    if (Variant >= OpNodes.size()) return true;
468
469    AddMatcher(new CheckOpcodeMatcher(CGP.getSDNodeInfo(OpNodes[Variant])));
470  } else {
471    if (Variant != 0) return true;
472  }
473
474  // Emit the matcher for the pattern structure and types.
475  EmitMatchCode(Pattern.getSrcPattern(), PatWithNoTypes);
476
477  // If the pattern has a predicate on it (e.g. only enabled when a subtarget
478  // feature is around, do the check).
479  if (!Pattern.getPredicateCheck().empty())
480    AddMatcher(new CheckPatternPredicateMatcher(Pattern.getPredicateCheck()));
481
482  // Now that we've completed the structural type match, emit any ComplexPattern
483  // checks (e.g. addrmode matches).  We emit this after the structural match
484  // because they are generally more expensive to evaluate and more difficult to
485  // factor.
486  for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i) {
487    const TreePatternNode *N = MatchedComplexPatterns[i].first;
488
489    // Remember where the results of this match get stuck.
490    MatchedComplexPatterns[i].second = NextRecordedOperandNo;
491
492    // Get the slot we recorded the value in from the name on the node.
493    unsigned RecNodeEntry = VariableMap[N->getName()];
494    assert(!N->getName().empty() && RecNodeEntry &&
495           "Complex pattern should have a name and slot");
496    --RecNodeEntry;  // Entries in VariableMap are biased.
497
498    const ComplexPattern &CP =
499      CGP.getComplexPattern(((DefInit*)N->getLeafValue())->getDef());
500
501    // Emit a CheckComplexPat operation, which does the match (aborting if it
502    // fails) and pushes the matched operands onto the recorded nodes list.
503    AddMatcher(new CheckComplexPatMatcher(CP, RecNodeEntry,
504                                          N->getName(), NextRecordedOperandNo));
505
506    // Record the right number of operands.
507    NextRecordedOperandNo += CP.getNumOperands();
508    if (CP.hasProperty(SDNPHasChain)) {
509      // If the complex pattern has a chain, then we need to keep track of the
510      // fact that we just recorded a chain input.  The chain input will be
511      // matched as the last operand of the predicate if it was successful.
512      ++NextRecordedOperandNo; // Chained node operand.
513
514      // It is the last operand recorded.
515      assert(NextRecordedOperandNo > 1 &&
516             "Should have recorded input/result chains at least!");
517      MatchedChainNodes.push_back(NextRecordedOperandNo-1);
518    }
519
520    // TODO: Complex patterns can't have output glues, if they did, we'd want
521    // to record them.
522  }
523
524  return false;
525}
526
527
528//===----------------------------------------------------------------------===//
529// Node Result Generation
530//===----------------------------------------------------------------------===//
531
532void MatcherGen::EmitResultOfNamedOperand(const TreePatternNode *N,
533                                          SmallVectorImpl<unsigned> &ResultOps){
534  assert(!N->getName().empty() && "Operand not named!");
535
536  // A reference to a complex pattern gets all of the results of the complex
537  // pattern's match.
538  if (const ComplexPattern *CP = N->getComplexPatternInfo(CGP)) {
539    unsigned SlotNo = 0;
540    for (unsigned i = 0, e = MatchedComplexPatterns.size(); i != e; ++i)
541      if (MatchedComplexPatterns[i].first->getName() == N->getName()) {
542        SlotNo = MatchedComplexPatterns[i].second;
543        break;
544      }
545    assert(SlotNo != 0 && "Didn't get a slot number assigned?");
546
547    // The first slot entry is the node itself, the subsequent entries are the
548    // matched values.
549    for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
550      ResultOps.push_back(SlotNo+i);
551    return;
552  }
553
554  unsigned SlotNo = getNamedArgumentSlot(N->getName());
555
556  // If this is an 'imm' or 'fpimm' node, make sure to convert it to the target
557  // version of the immediate so that it doesn't get selected due to some other
558  // node use.
559  if (!N->isLeaf()) {
560    StringRef OperatorName = N->getOperator()->getName();
561    if (OperatorName == "imm" || OperatorName == "fpimm") {
562      AddMatcher(new EmitConvertToTargetMatcher(SlotNo));
563      ResultOps.push_back(NextRecordedOperandNo++);
564      return;
565    }
566  }
567
568  ResultOps.push_back(SlotNo);
569}
570
571void MatcherGen::EmitResultLeafAsOperand(const TreePatternNode *N,
572                                         SmallVectorImpl<unsigned> &ResultOps) {
573  assert(N->isLeaf() && "Must be a leaf");
574
575  if (IntInit *II = dynamic_cast<IntInit*>(N->getLeafValue())) {
576    AddMatcher(new EmitIntegerMatcher(II->getValue(), N->getType(0)));
577    ResultOps.push_back(NextRecordedOperandNo++);
578    return;
579  }
580
581  // If this is an explicit register reference, handle it.
582  if (DefInit *DI = dynamic_cast<DefInit*>(N->getLeafValue())) {
583    Record *Def = DI->getDef();
584    if (Def->isSubClassOf("Register")) {
585      const CodeGenRegister *Reg =
586        CGP.getTargetInfo().getRegBank().getReg(Def);
587      AddMatcher(new EmitRegisterMatcher(Reg, N->getType(0)));
588      ResultOps.push_back(NextRecordedOperandNo++);
589      return;
590    }
591
592    if (Def->getName() == "zero_reg") {
593      AddMatcher(new EmitRegisterMatcher(0, N->getType(0)));
594      ResultOps.push_back(NextRecordedOperandNo++);
595      return;
596    }
597
598    // Handle a reference to a register class. This is used
599    // in COPY_TO_SUBREG instructions.
600    if (Def->isSubClassOf("RegisterOperand"))
601      Def = Def->getValueAsDef("RegClass");
602    if (Def->isSubClassOf("RegisterClass")) {
603      std::string Value = getQualifiedName(Def) + "RegClassID";
604      AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
605      ResultOps.push_back(NextRecordedOperandNo++);
606      return;
607    }
608
609    // Handle a subregister index. This is used for INSERT_SUBREG etc.
610    if (Def->isSubClassOf("SubRegIndex")) {
611      std::string Value = getQualifiedName(Def);
612      AddMatcher(new EmitStringIntegerMatcher(Value, MVT::i32));
613      ResultOps.push_back(NextRecordedOperandNo++);
614      return;
615    }
616  }
617
618  errs() << "unhandled leaf node: \n";
619  N->dump();
620}
621
622/// GetInstPatternNode - Get the pattern for an instruction.
623///
624const TreePatternNode *MatcherGen::
625GetInstPatternNode(const DAGInstruction &Inst, const TreePatternNode *N) {
626  const TreePattern *InstPat = Inst.getPattern();
627
628  // FIXME2?: Assume actual pattern comes before "implicit".
629  TreePatternNode *InstPatNode;
630  if (InstPat)
631    InstPatNode = InstPat->getTree(0);
632  else if (/*isRoot*/ N == Pattern.getDstPattern())
633    InstPatNode = Pattern.getSrcPattern();
634  else
635    return 0;
636
637  if (InstPatNode && !InstPatNode->isLeaf() &&
638      InstPatNode->getOperator()->getName() == "set")
639    InstPatNode = InstPatNode->getChild(InstPatNode->getNumChildren()-1);
640
641  return InstPatNode;
642}
643
644static bool
645mayInstNodeLoadOrStore(const TreePatternNode *N,
646                       const CodeGenDAGPatterns &CGP) {
647  Record *Op = N->getOperator();
648  const CodeGenTarget &CGT = CGP.getTargetInfo();
649  CodeGenInstruction &II = CGT.getInstruction(Op);
650  return II.mayLoad || II.mayStore;
651}
652
653static unsigned
654numNodesThatMayLoadOrStore(const TreePatternNode *N,
655                           const CodeGenDAGPatterns &CGP) {
656  if (N->isLeaf())
657    return 0;
658
659  Record *OpRec = N->getOperator();
660  if (!OpRec->isSubClassOf("Instruction"))
661    return 0;
662
663  unsigned Count = 0;
664  if (mayInstNodeLoadOrStore(N, CGP))
665    ++Count;
666
667  for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
668    Count += numNodesThatMayLoadOrStore(N->getChild(i), CGP);
669
670  return Count;
671}
672
673void MatcherGen::
674EmitResultInstructionAsOperand(const TreePatternNode *N,
675                               SmallVectorImpl<unsigned> &OutputOps) {
676  Record *Op = N->getOperator();
677  const CodeGenTarget &CGT = CGP.getTargetInfo();
678  CodeGenInstruction &II = CGT.getInstruction(Op);
679  const DAGInstruction &Inst = CGP.getInstruction(Op);
680
681  // If we can, get the pattern for the instruction we're generating.  We derive
682  // a variety of information from this pattern, such as whether it has a chain.
683  //
684  // FIXME2: This is extremely dubious for several reasons, not the least of
685  // which it gives special status to instructions with patterns that Pat<>
686  // nodes can't duplicate.
687  const TreePatternNode *InstPatNode = GetInstPatternNode(Inst, N);
688
689  // NodeHasChain - Whether the instruction node we're creating takes chains.
690  bool NodeHasChain = InstPatNode &&
691                      InstPatNode->TreeHasProperty(SDNPHasChain, CGP);
692
693  // Instructions which load and store from memory should have a chain,
694  // regardless of whether they happen to have an internal pattern saying so.
695  if (Pattern.getSrcPattern()->TreeHasProperty(SDNPHasChain, CGP)
696      && (II.hasCtrlDep || II.mayLoad || II.mayStore || II.canFoldAsLoad ||
697          II.hasSideEffects))
698      NodeHasChain = true;
699
700  bool isRoot = N == Pattern.getDstPattern();
701
702  // TreeHasOutGlue - True if this tree has glue.
703  bool TreeHasInGlue = false, TreeHasOutGlue = false;
704  if (isRoot) {
705    const TreePatternNode *SrcPat = Pattern.getSrcPattern();
706    TreeHasInGlue = SrcPat->TreeHasProperty(SDNPOptInGlue, CGP) ||
707                    SrcPat->TreeHasProperty(SDNPInGlue, CGP);
708
709    // FIXME2: this is checking the entire pattern, not just the node in
710    // question, doing this just for the root seems like a total hack.
711    TreeHasOutGlue = SrcPat->TreeHasProperty(SDNPOutGlue, CGP);
712  }
713
714  // NumResults - This is the number of results produced by the instruction in
715  // the "outs" list.
716  unsigned NumResults = Inst.getNumResults();
717
718  // Loop over all of the operands of the instruction pattern, emitting code
719  // to fill them all in.  The node 'N' usually has number children equal to
720  // the number of input operands of the instruction.  However, in cases
721  // where there are predicate operands for an instruction, we need to fill
722  // in the 'execute always' values.  Match up the node operands to the
723  // instruction operands to do this.
724  SmallVector<unsigned, 8> InstOps;
725  for (unsigned ChildNo = 0, InstOpNo = NumResults, e = II.Operands.size();
726       InstOpNo != e; ++InstOpNo) {
727
728    // Determine what to emit for this operand.
729    Record *OperandNode = II.Operands[InstOpNo].Rec;
730    if (OperandNode->isSubClassOf("OperandWithDefaultOps") &&
731        !CGP.getDefaultOperand(OperandNode).DefaultOps.empty()) {
732      // This is a predicate or optional def operand; emit the
733      // 'default ops' operands.
734      const DAGDefaultOperand &DefaultOp
735        = CGP.getDefaultOperand(OperandNode);
736      for (unsigned i = 0, e = DefaultOp.DefaultOps.size(); i != e; ++i)
737        EmitResultOperand(DefaultOp.DefaultOps[i], InstOps);
738      continue;
739    }
740
741    const TreePatternNode *Child = N->getChild(ChildNo);
742
743    // Otherwise this is a normal operand or a predicate operand without
744    // 'execute always'; emit it.
745    unsigned BeforeAddingNumOps = InstOps.size();
746    EmitResultOperand(Child, InstOps);
747    assert(InstOps.size() > BeforeAddingNumOps && "Didn't add any operands");
748
749    // If the operand is an instruction and it produced multiple results, just
750    // take the first one.
751    if (!Child->isLeaf() && Child->getOperator()->isSubClassOf("Instruction"))
752      InstOps.resize(BeforeAddingNumOps+1);
753
754    ++ChildNo;
755  }
756
757  // If this node has input glue or explicitly specified input physregs, we
758  // need to add chained and glued copyfromreg nodes and materialize the glue
759  // input.
760  if (isRoot && !PhysRegInputs.empty()) {
761    // Emit all of the CopyToReg nodes for the input physical registers.  These
762    // occur in patterns like (mul:i8 AL:i8, GR8:i8:$src).
763    for (unsigned i = 0, e = PhysRegInputs.size(); i != e; ++i)
764      AddMatcher(new EmitCopyToRegMatcher(PhysRegInputs[i].second,
765                                          PhysRegInputs[i].first));
766    // Even if the node has no other glue inputs, the resultant node must be
767    // glued to the CopyFromReg nodes we just generated.
768    TreeHasInGlue = true;
769  }
770
771  // Result order: node results, chain, glue
772
773  // Determine the result types.
774  SmallVector<MVT::SimpleValueType, 4> ResultVTs;
775  for (unsigned i = 0, e = N->getNumTypes(); i != e; ++i)
776    ResultVTs.push_back(N->getType(i));
777
778  // If this is the root instruction of a pattern that has physical registers in
779  // its result pattern, add output VTs for them.  For example, X86 has:
780  //   (set AL, (mul ...))
781  // This also handles implicit results like:
782  //   (implicit EFLAGS)
783  if (isRoot && !Pattern.getDstRegs().empty()) {
784    // If the root came from an implicit def in the instruction handling stuff,
785    // don't re-add it.
786    Record *HandledReg = 0;
787    if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
788      HandledReg = II.ImplicitDefs[0];
789
790    for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
791      Record *Reg = Pattern.getDstRegs()[i];
792      if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
793      ResultVTs.push_back(getRegisterValueType(Reg, CGT));
794    }
795  }
796
797  // If this is the root of the pattern and the pattern we're matching includes
798  // a node that is variadic, mark the generated node as variadic so that it
799  // gets the excess operands from the input DAG.
800  int NumFixedArityOperands = -1;
801  if (isRoot &&
802      (Pattern.getSrcPattern()->NodeHasProperty(SDNPVariadic, CGP)))
803    NumFixedArityOperands = Pattern.getSrcPattern()->getNumChildren();
804
805  // If this is the root node and multiple matched nodes in the input pattern
806  // have MemRefs in them, have the interpreter collect them and plop them onto
807  // this node. If there is just one node with MemRefs, leave them on that node
808  // even if it is not the root.
809  //
810  // FIXME3: This is actively incorrect for result patterns with multiple
811  // memory-referencing instructions.
812  bool PatternHasMemOperands =
813    Pattern.getSrcPattern()->TreeHasProperty(SDNPMemOperand, CGP);
814
815  bool NodeHasMemRefs = false;
816  if (PatternHasMemOperands) {
817    unsigned NumNodesThatLoadOrStore =
818      numNodesThatMayLoadOrStore(Pattern.getDstPattern(), CGP);
819    bool NodeIsUniqueLoadOrStore = mayInstNodeLoadOrStore(N, CGP) &&
820                                   NumNodesThatLoadOrStore == 1;
821    NodeHasMemRefs =
822      NodeIsUniqueLoadOrStore || (isRoot && (mayInstNodeLoadOrStore(N, CGP) ||
823                                             NumNodesThatLoadOrStore != 1));
824  }
825
826  assert((!ResultVTs.empty() || TreeHasOutGlue || NodeHasChain) &&
827         "Node has no result");
828
829  AddMatcher(new EmitNodeMatcher(II.Namespace+"::"+II.TheDef->getName(),
830                                 ResultVTs.data(), ResultVTs.size(),
831                                 InstOps.data(), InstOps.size(),
832                                 NodeHasChain, TreeHasInGlue, TreeHasOutGlue,
833                                 NodeHasMemRefs, NumFixedArityOperands,
834                                 NextRecordedOperandNo));
835
836  // The non-chain and non-glue results of the newly emitted node get recorded.
837  for (unsigned i = 0, e = ResultVTs.size(); i != e; ++i) {
838    if (ResultVTs[i] == MVT::Other || ResultVTs[i] == MVT::Glue) break;
839    OutputOps.push_back(NextRecordedOperandNo++);
840  }
841}
842
843void MatcherGen::
844EmitResultSDNodeXFormAsOperand(const TreePatternNode *N,
845                               SmallVectorImpl<unsigned> &ResultOps) {
846  assert(N->getOperator()->isSubClassOf("SDNodeXForm") && "Not SDNodeXForm?");
847
848  // Emit the operand.
849  SmallVector<unsigned, 8> InputOps;
850
851  // FIXME2: Could easily generalize this to support multiple inputs and outputs
852  // to the SDNodeXForm.  For now we just support one input and one output like
853  // the old instruction selector.
854  assert(N->getNumChildren() == 1);
855  EmitResultOperand(N->getChild(0), InputOps);
856
857  // The input currently must have produced exactly one result.
858  assert(InputOps.size() == 1 && "Unexpected input to SDNodeXForm");
859
860  AddMatcher(new EmitNodeXFormMatcher(InputOps[0], N->getOperator()));
861  ResultOps.push_back(NextRecordedOperandNo++);
862}
863
864void MatcherGen::EmitResultOperand(const TreePatternNode *N,
865                                   SmallVectorImpl<unsigned> &ResultOps) {
866  // This is something selected from the pattern we matched.
867  if (!N->getName().empty())
868    return EmitResultOfNamedOperand(N, ResultOps);
869
870  if (N->isLeaf())
871    return EmitResultLeafAsOperand(N, ResultOps);
872
873  Record *OpRec = N->getOperator();
874  if (OpRec->isSubClassOf("Instruction"))
875    return EmitResultInstructionAsOperand(N, ResultOps);
876  if (OpRec->isSubClassOf("SDNodeXForm"))
877    return EmitResultSDNodeXFormAsOperand(N, ResultOps);
878  errs() << "Unknown result node to emit code for: " << *N << '\n';
879  throw std::string("Unknown node in result pattern!");
880}
881
882void MatcherGen::EmitResultCode() {
883  // Patterns that match nodes with (potentially multiple) chain inputs have to
884  // merge them together into a token factor.  This informs the generated code
885  // what all the chained nodes are.
886  if (!MatchedChainNodes.empty())
887    AddMatcher(new EmitMergeInputChainsMatcher
888               (MatchedChainNodes.data(), MatchedChainNodes.size()));
889
890  // Codegen the root of the result pattern, capturing the resulting values.
891  SmallVector<unsigned, 8> Ops;
892  EmitResultOperand(Pattern.getDstPattern(), Ops);
893
894  // At this point, we have however many values the result pattern produces.
895  // However, the input pattern might not need all of these.  If there are
896  // excess values at the end (such as implicit defs of condition codes etc)
897  // just lop them off.  This doesn't need to worry about glue or chains, just
898  // explicit results.
899  //
900  unsigned NumSrcResults = Pattern.getSrcPattern()->getNumTypes();
901
902  // If the pattern also has (implicit) results, count them as well.
903  if (!Pattern.getDstRegs().empty()) {
904    // If the root came from an implicit def in the instruction handling stuff,
905    // don't re-add it.
906    Record *HandledReg = 0;
907    const TreePatternNode *DstPat = Pattern.getDstPattern();
908    if (!DstPat->isLeaf() &&DstPat->getOperator()->isSubClassOf("Instruction")){
909      const CodeGenTarget &CGT = CGP.getTargetInfo();
910      CodeGenInstruction &II = CGT.getInstruction(DstPat->getOperator());
911
912      if (II.HasOneImplicitDefWithKnownVT(CGT) != MVT::Other)
913        HandledReg = II.ImplicitDefs[0];
914    }
915
916    for (unsigned i = 0; i != Pattern.getDstRegs().size(); ++i) {
917      Record *Reg = Pattern.getDstRegs()[i];
918      if (!Reg->isSubClassOf("Register") || Reg == HandledReg) continue;
919      ++NumSrcResults;
920    }
921  }
922
923  assert(Ops.size() >= NumSrcResults && "Didn't provide enough results");
924  Ops.resize(NumSrcResults);
925
926  // If the matched pattern covers nodes which define a glue result, emit a node
927  // that tells the matcher about them so that it can update their results.
928  if (!MatchedGlueResultNodes.empty())
929    AddMatcher(new MarkGlueResultsMatcher(MatchedGlueResultNodes.data(),
930                                          MatchedGlueResultNodes.size()));
931
932  AddMatcher(new CompleteMatchMatcher(Ops.data(), Ops.size(), Pattern));
933}
934
935
936/// ConvertPatternToMatcher - Create the matcher for the specified pattern with
937/// the specified variant.  If the variant number is invalid, this returns null.
938Matcher *llvm::ConvertPatternToMatcher(const PatternToMatch &Pattern,
939                                       unsigned Variant,
940                                       const CodeGenDAGPatterns &CGP) {
941  MatcherGen Gen(Pattern, CGP);
942
943  // Generate the code for the matcher.
944  if (Gen.EmitMatcherCode(Variant))
945    return 0;
946
947  // FIXME2: Kill extra MoveParent commands at the end of the matcher sequence.
948  // FIXME2: Split result code out to another table, and make the matcher end
949  // with an "Emit <index>" command.  This allows result generation stuff to be
950  // shared and factored?
951
952  // If the match succeeds, then we generate Pattern.
953  Gen.EmitResultCode();
954
955  // Unconditional match.
956  return Gen.GetMatcher();
957}
958