1 //===- CodeGenDAGPatterns.h - Read DAG patterns from .td file ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file declares the CodeGenDAGPatterns class, which is used to read and
11 // represent the patterns present in a .td file for instructions.
13 //===----------------------------------------------------------------------===//
15 #ifndef CODEGEN_DAGPATTERNS_H
16 #define CODEGEN_DAGPATTERNS_H
20 #include "TableGenBackend.h"
21 #include "CodeGenTarget.h"
22 #include "CodeGenIntrinsics.h"
31 class TreePatternNode;
32 class CodeGenDAGPatterns;
35 /// MVT::DAGISelGenValueType - These are some extended forms of MVT::ValueType
36 /// that we use as lattice values during type inferrence.
38 enum DAGISelGenValueType {
39 isFP = MVT::LAST_VALUETYPE,
44 /// isExtIntegerVT - Return true if the specified extended value type vector
45 /// contains isInt or an integer value type.
46 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs);
48 /// isExtFloatingPointVT - Return true if the specified extended value type
49 /// vector contains isFP or a FP value type.
50 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs);
53 /// Set type used to track multiply used variables in patterns
54 typedef std::set<std::string> MultipleUseVarSet;
56 /// SDTypeConstraint - This is a discriminated union of constraints,
57 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
58 struct SDTypeConstraint {
59 SDTypeConstraint(Record *R);
61 unsigned OperandNo; // The operand # this constraint applies to.
63 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
64 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
68 union { // The discriminated union.
73 unsigned OtherOperandNum;
76 unsigned OtherOperandNum;
77 } SDTCisVTSmallerThanOp_Info;
79 unsigned BigOperandNum;
80 } SDTCisOpSmallerThanOp_Info;
82 unsigned OtherOperandNum;
83 } SDTCisIntVectorOfSameSize_Info;
85 unsigned OtherOperandNum;
86 } SDTCisEltOfVec_Info;
89 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
90 /// constraint to the nodes operands. This returns true if it makes a
91 /// change, false otherwise. If a type contradiction is found, throw an
93 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
94 TreePattern &TP) const;
96 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
97 /// N, which has NumResults results.
98 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
99 unsigned NumResults) const;
102 /// SDNodeInfo - One of these records is created for each SDNode instance in
103 /// the target .td file. This represents the various dag nodes we will be
107 std::string EnumName;
108 std::string SDClassName;
112 std::vector<SDTypeConstraint> TypeConstraints;
114 SDNodeInfo(Record *R); // Parse the specified record.
116 unsigned getNumResults() const { return NumResults; }
117 int getNumOperands() const { return NumOperands; }
118 Record *getRecord() const { return Def; }
119 const std::string &getEnumName() const { return EnumName; }
120 const std::string &getSDClassName() const { return SDClassName; }
122 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
123 return TypeConstraints;
126 /// hasProperty - Return true if this node has the specified property.
128 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
130 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
131 /// constraints for this node to the operands of the node. This returns
132 /// true if it makes a change, false otherwise. If a type contradiction is
133 /// found, throw an exception.
134 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
135 bool MadeChange = false;
136 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
137 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
142 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
143 /// patterns), and as such should be ref counted. We currently just leak all
144 /// TreePatternNode objects!
145 class TreePatternNode {
146 /// The inferred type for this node, or MVT::isUnknown if it hasn't
147 /// been determined yet.
148 std::vector<unsigned char> Types;
150 /// Operator - The Record for the operator if this is an interior node (not
154 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
158 /// Name - The name given to this node with the :$foo notation.
162 /// PredicateFn - The predicate function to execute on this node to check
163 /// for a match. If this string is empty, no predicate is involved.
164 std::string PredicateFn;
166 /// TransformFn - The transformation function to execute on this node before
167 /// it can be substituted into the resulting instruction on a pattern match.
170 std::vector<TreePatternNode*> Children;
172 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
173 : Types(), Operator(Op), Val(0), TransformFn(0),
174 Children(Ch) { Types.push_back(MVT::isUnknown); }
175 TreePatternNode(Init *val) // leaf ctor
176 : Types(), Operator(0), Val(val), TransformFn(0) {
177 Types.push_back(MVT::isUnknown);
181 const std::string &getName() const { return Name; }
182 void setName(const std::string &N) { Name = N; }
184 bool isLeaf() const { return Val != 0; }
185 bool hasTypeSet() const {
186 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR);
188 bool isTypeCompletelyUnknown() const {
189 return Types[0] == MVT::isUnknown;
191 bool isTypeDynamicallyResolved() const {
192 return Types[0] == MVT::iPTR;
194 MVT::ValueType getTypeNum(unsigned Num) const {
195 assert(hasTypeSet() && "Doesn't have a type yet!");
196 assert(Types.size() > Num && "Type num out of range!");
197 return (MVT::ValueType)Types[Num];
199 unsigned char getExtTypeNum(unsigned Num) const {
200 assert(Types.size() > Num && "Extended type num out of range!");
203 const std::vector<unsigned char> &getExtTypes() const { return Types; }
204 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
205 void removeTypes() { Types = std::vector<unsigned char>(1,MVT::isUnknown); }
207 Init *getLeafValue() const { assert(isLeaf()); return Val; }
208 Record *getOperator() const { assert(!isLeaf()); return Operator; }
210 unsigned getNumChildren() const { return Children.size(); }
211 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
212 void setChild(unsigned i, TreePatternNode *N) {
216 const std::string &getPredicateFn() const { return PredicateFn; }
217 void setPredicateFn(const std::string &Fn) { PredicateFn = Fn; }
219 Record *getTransformFn() const { return TransformFn; }
220 void setTransformFn(Record *Fn) { TransformFn = Fn; }
222 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
223 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
224 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
226 void print(std::ostream &OS) const;
229 public: // Higher level manipulation routines.
231 /// clone - Return a new copy of this tree.
233 TreePatternNode *clone() const;
235 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
236 /// the specified node. For this comparison, all of the state of the node
237 /// is considered, except for the assigned name. Nodes with differing names
238 /// that are otherwise identical are considered isomorphic.
239 bool isIsomorphicTo(const TreePatternNode *N,
240 const MultipleUseVarSet &DepVars) const;
242 /// SubstituteFormalArguments - Replace the formal arguments in this tree
243 /// with actual values specified by ArgMap.
244 void SubstituteFormalArguments(std::map<std::string,
245 TreePatternNode*> &ArgMap);
247 /// InlinePatternFragments - If this pattern refers to any pattern
248 /// fragments, inline them into place, giving us a pattern without any
249 /// PatFrag references.
250 TreePatternNode *InlinePatternFragments(TreePattern &TP);
252 /// ApplyTypeConstraints - Apply all of the type constraints relevent to
253 /// this node and its children in the tree. This returns true if it makes a
254 /// change, false otherwise. If a type contradiction is found, throw an
256 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
258 /// UpdateNodeType - Set the node type of N to VT if VT contains
259 /// information. If N already contains a conflicting type, then throw an
260 /// exception. This returns true if any information was updated.
262 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
264 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
265 std::vector<unsigned char> ExtVTs(1, ExtVT);
266 return UpdateNodeType(ExtVTs, TP);
269 /// ContainsUnresolvedType - Return true if this tree contains any
270 /// unresolved types.
271 bool ContainsUnresolvedType() const {
272 if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
273 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
274 if (getChild(i)->ContainsUnresolvedType()) return true;
278 /// canPatternMatch - If it is impossible for this pattern to match on this
279 /// target, fill in Reason and return false. Otherwise, return true.
280 bool canPatternMatch(std::string &Reason, CodeGenDAGPatterns &CDP);
284 /// TreePattern - Represent a pattern, used for instructions, pattern
288 /// Trees - The list of pattern trees which corresponds to this pattern.
289 /// Note that PatFrag's only have a single tree.
291 std::vector<TreePatternNode*> Trees;
293 /// TheRecord - The actual TableGen record corresponding to this pattern.
297 /// Args - This is a list of all of the arguments to this pattern (for
298 /// PatFrag patterns), which are the 'node' markers in this pattern.
299 std::vector<std::string> Args;
301 /// CDP - the top-level object coordinating this madness.
303 CodeGenDAGPatterns &CDP;
305 /// isInputPattern - True if this is an input pattern, something to match.
306 /// False if this is an output pattern, something to emit.
310 /// TreePattern constructor - Parse the specified DagInits into the
312 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
313 CodeGenDAGPatterns &ise);
314 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
315 CodeGenDAGPatterns &ise);
316 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
317 CodeGenDAGPatterns &ise);
319 /// getTrees - Return the tree patterns which corresponds to this pattern.
321 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
322 unsigned getNumTrees() const { return Trees.size(); }
323 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
324 TreePatternNode *getOnlyTree() const {
325 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
329 /// getRecord - Return the actual TableGen record corresponding to this
332 Record *getRecord() const { return TheRecord; }
334 unsigned getNumArgs() const { return Args.size(); }
335 const std::string &getArgName(unsigned i) const {
336 assert(i < Args.size() && "Argument reference out of range!");
339 std::vector<std::string> &getArgList() { return Args; }
341 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
343 /// InlinePatternFragments - If this pattern refers to any pattern
344 /// fragments, inline them into place, giving us a pattern without any
345 /// PatFrag references.
346 void InlinePatternFragments() {
347 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
348 Trees[i] = Trees[i]->InlinePatternFragments(*this);
351 /// InferAllTypes - Infer/propagate as many types throughout the expression
352 /// patterns as possible. Return true if all types are infered, false
353 /// otherwise. Throw an exception if a type contradiction is found.
354 bool InferAllTypes();
356 /// error - Throw an exception, prefixing it with information about this
358 void error(const std::string &Msg) const;
360 void print(std::ostream &OS) const;
364 TreePatternNode *ParseTreePattern(DagInit *DI);
367 /// DAGDefaultOperand - One of these is created for each PredicateOperand
368 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
369 struct DAGDefaultOperand {
370 std::vector<TreePatternNode*> DefaultOps;
373 class DAGInstruction {
374 TreePattern *Pattern;
375 std::vector<Record*> Results;
376 std::vector<Record*> Operands;
377 std::vector<Record*> ImpResults;
378 std::vector<Record*> ImpOperands;
379 TreePatternNode *ResultPattern;
381 DAGInstruction(TreePattern *TP,
382 const std::vector<Record*> &results,
383 const std::vector<Record*> &operands,
384 const std::vector<Record*> &impresults,
385 const std::vector<Record*> &impoperands)
386 : Pattern(TP), Results(results), Operands(operands),
387 ImpResults(impresults), ImpOperands(impoperands),
390 const TreePattern *getPattern() const { return Pattern; }
391 unsigned getNumResults() const { return Results.size(); }
392 unsigned getNumOperands() const { return Operands.size(); }
393 unsigned getNumImpResults() const { return ImpResults.size(); }
394 unsigned getNumImpOperands() const { return ImpOperands.size(); }
395 const std::vector<Record*>& getImpResults() const { return ImpResults; }
397 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
399 Record *getResult(unsigned RN) const {
400 assert(RN < Results.size());
404 Record *getOperand(unsigned ON) const {
405 assert(ON < Operands.size());
409 Record *getImpResult(unsigned RN) const {
410 assert(RN < ImpResults.size());
411 return ImpResults[RN];
414 Record *getImpOperand(unsigned ON) const {
415 assert(ON < ImpOperands.size());
416 return ImpOperands[ON];
419 TreePatternNode *getResultPattern() const { return ResultPattern; }
422 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
423 /// processed to produce isel.
424 struct PatternToMatch {
425 PatternToMatch(ListInit *preds,
426 TreePatternNode *src, TreePatternNode *dst,
427 const std::vector<Record*> &dstregs,
428 unsigned complexity):
429 Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
430 AddedComplexity(complexity) {};
432 ListInit *Predicates; // Top level predicate conditions to match.
433 TreePatternNode *SrcPattern; // Source pattern to match.
434 TreePatternNode *DstPattern; // Resulting pattern.
435 std::vector<Record*> Dstregs; // Physical register defs being matched.
436 unsigned AddedComplexity; // Add to matching pattern complexity.
438 ListInit *getPredicates() const { return Predicates; }
439 TreePatternNode *getSrcPattern() const { return SrcPattern; }
440 TreePatternNode *getDstPattern() const { return DstPattern; }
441 const std::vector<Record*> &getDstRegs() const { return Dstregs; }
442 unsigned getAddedComplexity() const { return AddedComplexity; }
446 class CodeGenDAGPatterns {
447 RecordKeeper &Records;
448 CodeGenTarget Target;
449 std::vector<CodeGenIntrinsic> Intrinsics;
451 std::map<Record*, SDNodeInfo> SDNodes;
452 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
453 std::map<Record*, ComplexPattern> ComplexPatterns;
454 std::map<Record*, TreePattern*> PatternFragments;
455 std::map<Record*, DAGDefaultOperand> DefaultOperands;
456 std::map<Record*, DAGInstruction> Instructions;
458 // Specific SDNode definitions:
459 Record *intrinsic_void_sdnode;
460 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
462 /// PatternsToMatch - All of the things we are matching on the DAG. The first
463 /// value is the pattern to match, the second pattern is the result to
465 std::vector<PatternToMatch> PatternsToMatch;
467 CodeGenDAGPatterns(RecordKeeper &R);
468 ~CodeGenDAGPatterns();
470 const CodeGenTarget &getTargetInfo() const { return Target; }
472 Record *getSDNodeNamed(const std::string &Name) const;
474 const SDNodeInfo &getSDNodeInfo(Record *R) const {
475 assert(SDNodes.count(R) && "Unknown node!");
476 return SDNodes.find(R)->second;
479 // Node transformation lookups.
480 typedef std::pair<Record*, std::string> NodeXForm;
481 const NodeXForm &getSDNodeTransform(Record *R) const {
482 assert(SDNodeXForms.count(R) && "Invalid transform!");
483 return SDNodeXForms.find(R)->second;
486 typedef std::map<Record*, NodeXForm>::const_iterator nx_iterator;
487 nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
488 nx_iterator nx_end() const { return SDNodeXForms.end(); }
491 const ComplexPattern &getComplexPattern(Record *R) const {
492 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
493 return ComplexPatterns.find(R)->second;
496 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
497 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
498 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
499 assert(0 && "Unknown intrinsic!");
503 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
504 assert(IID-1 < Intrinsics.size() && "Bad intrinsic ID!");
505 return Intrinsics[IID-1];
508 unsigned getIntrinsicID(Record *R) const {
509 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
510 if (Intrinsics[i].TheDef == R) return i;
511 assert(0 && "Unknown intrinsic!");
515 const DAGDefaultOperand &getDefaultOperand(Record *R) {
516 assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
517 return DefaultOperands.find(R)->second;
520 // Pattern Fragment information.
521 TreePattern *getPatternFragment(Record *R) const {
522 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
523 return PatternFragments.find(R)->second;
525 typedef std::map<Record*, TreePattern*>::const_iterator pf_iterator;
526 pf_iterator pf_begin() const { return PatternFragments.begin(); }
527 pf_iterator pf_end() const { return PatternFragments.end(); }
529 // Patterns to match information.
530 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
531 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
532 ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
536 const DAGInstruction &getInstruction(Record *R) const {
537 assert(Instructions.count(R) && "Unknown instruction!");
538 return Instructions.find(R)->second;
541 Record *get_intrinsic_void_sdnode() const {
542 return intrinsic_void_sdnode;
544 Record *get_intrinsic_w_chain_sdnode() const {
545 return intrinsic_w_chain_sdnode;
547 Record *get_intrinsic_wo_chain_sdnode() const {
548 return intrinsic_wo_chain_sdnode;
552 void ParseNodeInfo();
553 void ParseNodeTransforms();
554 void ParseComplexPatterns();
555 void ParsePatternFragments();
556 void ParseDefaultOperands();
557 void ParseInstructions();
558 void ParsePatterns();
559 void GenerateVariants();
561 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
562 std::map<std::string,
563 TreePatternNode*> &InstInputs,
564 std::map<std::string,
565 TreePatternNode*> &InstResults,
566 std::vector<Record*> &InstImpInputs,
567 std::vector<Record*> &InstImpResults);
569 } // end namespace llvm