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
22 #include "CodeGenTarget.h"
23 #include "CodeGenIntrinsics.h"
32 class TreePatternNode;
33 class CodeGenDAGPatterns;
36 /// EMVT::DAGISelGenValueType - These are some extended forms of
37 /// MVT::SimpleValueType that we use as lattice values during type inference.
39 enum DAGISelGenValueType {
40 isFP = MVT::LAST_VALUETYPE,
45 /// isExtIntegerVT - Return true if the specified extended value type vector
46 /// contains isInt or an integer value type.
47 bool isExtIntegerInVTs(const std::vector<unsigned char> &EVTs);
49 /// isExtFloatingPointVT - Return true if the specified extended value type
50 /// vector contains isFP or a FP value type.
51 bool isExtFloatingPointInVTs(const std::vector<unsigned char> &EVTs);
54 /// Set type used to track multiply used variables in patterns
55 typedef std::set<std::string> MultipleUseVarSet;
57 /// SDTypeConstraint - This is a discriminated union of constraints,
58 /// corresponding to the SDTypeConstraint tablegen class in Target.td.
59 struct SDTypeConstraint {
60 SDTypeConstraint(Record *R);
62 unsigned OperandNo; // The operand # this constraint applies to.
64 SDTCisVT, SDTCisPtrTy, SDTCisInt, SDTCisFP, SDTCisSameAs,
65 SDTCisVTSmallerThanOp, SDTCisOpSmallerThanOp, SDTCisIntVectorOfSameSize,
69 union { // The discriminated union.
74 unsigned OtherOperandNum;
77 unsigned OtherOperandNum;
78 } SDTCisVTSmallerThanOp_Info;
80 unsigned BigOperandNum;
81 } SDTCisOpSmallerThanOp_Info;
83 unsigned OtherOperandNum;
84 } SDTCisIntVectorOfSameSize_Info;
86 unsigned OtherOperandNum;
87 } SDTCisEltOfVec_Info;
90 /// ApplyTypeConstraint - Given a node in a pattern, apply this type
91 /// constraint to the nodes operands. This returns true if it makes a
92 /// change, false otherwise. If a type contradiction is found, throw an
94 bool ApplyTypeConstraint(TreePatternNode *N, const SDNodeInfo &NodeInfo,
95 TreePattern &TP) const;
97 /// getOperandNum - Return the node corresponding to operand #OpNo in tree
98 /// N, which has NumResults results.
99 TreePatternNode *getOperandNum(unsigned OpNo, TreePatternNode *N,
100 unsigned NumResults) const;
103 /// SDNodeInfo - One of these records is created for each SDNode instance in
104 /// the target .td file. This represents the various dag nodes we will be
108 std::string EnumName;
109 std::string SDClassName;
113 std::vector<SDTypeConstraint> TypeConstraints;
115 SDNodeInfo(Record *R); // Parse the specified record.
117 unsigned getNumResults() const { return NumResults; }
118 int getNumOperands() const { return NumOperands; }
119 Record *getRecord() const { return Def; }
120 const std::string &getEnumName() const { return EnumName; }
121 const std::string &getSDClassName() const { return SDClassName; }
123 const std::vector<SDTypeConstraint> &getTypeConstraints() const {
124 return TypeConstraints;
127 /// hasProperty - Return true if this node has the specified property.
129 bool hasProperty(enum SDNP Prop) const { return Properties & (1 << Prop); }
131 /// ApplyTypeConstraints - Given a node in a pattern, apply the type
132 /// constraints for this node to the operands of the node. This returns
133 /// true if it makes a change, false otherwise. If a type contradiction is
134 /// found, throw an exception.
135 bool ApplyTypeConstraints(TreePatternNode *N, TreePattern &TP) const {
136 bool MadeChange = false;
137 for (unsigned i = 0, e = TypeConstraints.size(); i != e; ++i)
138 MadeChange |= TypeConstraints[i].ApplyTypeConstraint(N, *this, TP);
143 /// FIXME: TreePatternNode's can be shared in some cases (due to dag-shaped
144 /// patterns), and as such should be ref counted. We currently just leak all
145 /// TreePatternNode objects!
146 class TreePatternNode {
147 /// The inferred type for this node, or EMVT::isUnknown if it hasn't
148 /// been determined yet. This is a std::vector because during inference
149 /// there may be multiple possible types.
150 std::vector<unsigned char> Types;
152 /// Operator - The Record for the operator if this is an interior node (not
156 /// Val - The init value (e.g. the "GPRC" record, or "7") for a leaf.
160 /// Name - The name given to this node with the :$foo notation.
164 /// PredicateFns - The predicate functions to execute on this node to check
165 /// for a match. If this list is empty, no predicate is involved.
166 std::vector<std::string> PredicateFns;
168 /// TransformFn - The transformation function to execute on this node before
169 /// it can be substituted into the resulting instruction on a pattern match.
172 std::vector<TreePatternNode*> Children;
174 TreePatternNode(Record *Op, const std::vector<TreePatternNode*> &Ch)
175 : Types(), Operator(Op), Val(0), TransformFn(0),
176 Children(Ch) { Types.push_back(EMVT::isUnknown); }
177 TreePatternNode(Init *val) // leaf ctor
178 : Types(), Operator(0), Val(val), TransformFn(0) {
179 Types.push_back(EMVT::isUnknown);
183 const std::string &getName() const { return Name; }
184 void setName(const std::string &N) { Name = N; }
186 bool isLeaf() const { return Val != 0; }
187 bool hasTypeSet() const {
188 return (Types[0] < MVT::LAST_VALUETYPE) || (Types[0] == MVT::iPTR) ||
189 (Types[0] == MVT::iPTRAny);
191 bool isTypeCompletelyUnknown() const {
192 return Types[0] == EMVT::isUnknown;
194 bool isTypeDynamicallyResolved() const {
195 return (Types[0] == MVT::iPTR) || (Types[0] == MVT::iPTRAny);
197 MVT::SimpleValueType getTypeNum(unsigned Num) const {
198 assert(hasTypeSet() && "Doesn't have a type yet!");
199 assert(Types.size() > Num && "Type num out of range!");
200 return (MVT::SimpleValueType)Types[Num];
202 unsigned char getExtTypeNum(unsigned Num) const {
203 assert(Types.size() > Num && "Extended type num out of range!");
206 const std::vector<unsigned char> &getExtTypes() const { return Types; }
207 void setTypes(const std::vector<unsigned char> &T) { Types = T; }
208 void removeTypes() { Types = std::vector<unsigned char>(1, EMVT::isUnknown); }
210 Init *getLeafValue() const { assert(isLeaf()); return Val; }
211 Record *getOperator() const { assert(!isLeaf()); return Operator; }
213 unsigned getNumChildren() const { return Children.size(); }
214 TreePatternNode *getChild(unsigned N) const { return Children[N]; }
215 void setChild(unsigned i, TreePatternNode *N) {
219 const std::vector<std::string> &getPredicateFns() const { return PredicateFns; }
220 void clearPredicateFns() { PredicateFns.clear(); }
221 void setPredicateFns(const std::vector<std::string> &Fns) {
222 assert(PredicateFns.empty() && "Overwriting non-empty predicate list!");
225 void addPredicateFn(const std::string &Fn) {
226 assert(!Fn.empty() && "Empty predicate string!");
227 if (std::find(PredicateFns.begin(), PredicateFns.end(), Fn) ==
229 PredicateFns.push_back(Fn);
232 Record *getTransformFn() const { return TransformFn; }
233 void setTransformFn(Record *Fn) { TransformFn = Fn; }
235 /// getIntrinsicInfo - If this node corresponds to an intrinsic, return the
236 /// CodeGenIntrinsic information for it, otherwise return a null pointer.
237 const CodeGenIntrinsic *getIntrinsicInfo(const CodeGenDAGPatterns &CDP) const;
239 /// isCommutativeIntrinsic - Return true if the node is an intrinsic which is
240 /// marked isCommutative.
241 bool isCommutativeIntrinsic(const CodeGenDAGPatterns &CDP) const;
243 void print(std::ostream &OS) const;
246 public: // Higher level manipulation routines.
248 /// clone - Return a new copy of this tree.
250 TreePatternNode *clone() const;
252 /// isIsomorphicTo - Return true if this node is recursively isomorphic to
253 /// the specified node. For this comparison, all of the state of the node
254 /// is considered, except for the assigned name. Nodes with differing names
255 /// that are otherwise identical are considered isomorphic.
256 bool isIsomorphicTo(const TreePatternNode *N,
257 const MultipleUseVarSet &DepVars) const;
259 /// SubstituteFormalArguments - Replace the formal arguments in this tree
260 /// with actual values specified by ArgMap.
261 void SubstituteFormalArguments(std::map<std::string,
262 TreePatternNode*> &ArgMap);
264 /// InlinePatternFragments - If this pattern refers to any pattern
265 /// fragments, inline them into place, giving us a pattern without any
266 /// PatFrag references.
267 TreePatternNode *InlinePatternFragments(TreePattern &TP);
269 /// ApplyTypeConstraints - Apply all of the type constraints relevant to
270 /// this node and its children in the tree. This returns true if it makes a
271 /// change, false otherwise. If a type contradiction is found, throw an
273 bool ApplyTypeConstraints(TreePattern &TP, bool NotRegisters);
275 /// UpdateNodeType - Set the node type of N to VT if VT contains
276 /// information. If N already contains a conflicting type, then throw an
277 /// exception. This returns true if any information was updated.
279 bool UpdateNodeType(const std::vector<unsigned char> &ExtVTs,
281 bool UpdateNodeType(unsigned char ExtVT, TreePattern &TP) {
282 std::vector<unsigned char> ExtVTs(1, ExtVT);
283 return UpdateNodeType(ExtVTs, TP);
286 /// ContainsUnresolvedType - Return true if this tree contains any
287 /// unresolved types.
288 bool ContainsUnresolvedType() const {
289 if (!hasTypeSet() && !isTypeDynamicallyResolved()) return true;
290 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
291 if (getChild(i)->ContainsUnresolvedType()) return true;
295 /// canPatternMatch - If it is impossible for this pattern to match on this
296 /// target, fill in Reason and return false. Otherwise, return true.
297 bool canPatternMatch(std::string &Reason, const CodeGenDAGPatterns &CDP);
301 /// TreePattern - Represent a pattern, used for instructions, pattern
305 /// Trees - The list of pattern trees which corresponds to this pattern.
306 /// Note that PatFrag's only have a single tree.
308 std::vector<TreePatternNode*> Trees;
310 /// TheRecord - The actual TableGen record corresponding to this pattern.
314 /// Args - This is a list of all of the arguments to this pattern (for
315 /// PatFrag patterns), which are the 'node' markers in this pattern.
316 std::vector<std::string> Args;
318 /// CDP - the top-level object coordinating this madness.
320 CodeGenDAGPatterns &CDP;
322 /// isInputPattern - True if this is an input pattern, something to match.
323 /// False if this is an output pattern, something to emit.
327 /// TreePattern constructor - Parse the specified DagInits into the
329 TreePattern(Record *TheRec, ListInit *RawPat, bool isInput,
330 CodeGenDAGPatterns &ise);
331 TreePattern(Record *TheRec, DagInit *Pat, bool isInput,
332 CodeGenDAGPatterns &ise);
333 TreePattern(Record *TheRec, TreePatternNode *Pat, bool isInput,
334 CodeGenDAGPatterns &ise);
336 /// getTrees - Return the tree patterns which corresponds to this pattern.
338 const std::vector<TreePatternNode*> &getTrees() const { return Trees; }
339 unsigned getNumTrees() const { return Trees.size(); }
340 TreePatternNode *getTree(unsigned i) const { return Trees[i]; }
341 TreePatternNode *getOnlyTree() const {
342 assert(Trees.size() == 1 && "Doesn't have exactly one pattern!");
346 /// getRecord - Return the actual TableGen record corresponding to this
349 Record *getRecord() const { return TheRecord; }
351 unsigned getNumArgs() const { return Args.size(); }
352 const std::string &getArgName(unsigned i) const {
353 assert(i < Args.size() && "Argument reference out of range!");
356 std::vector<std::string> &getArgList() { return Args; }
358 CodeGenDAGPatterns &getDAGPatterns() const { return CDP; }
360 /// InlinePatternFragments - If this pattern refers to any pattern
361 /// fragments, inline them into place, giving us a pattern without any
362 /// PatFrag references.
363 void InlinePatternFragments() {
364 for (unsigned i = 0, e = Trees.size(); i != e; ++i)
365 Trees[i] = Trees[i]->InlinePatternFragments(*this);
368 /// InferAllTypes - Infer/propagate as many types throughout the expression
369 /// patterns as possible. Return true if all types are inferred, false
370 /// otherwise. Throw an exception if a type contradiction is found.
371 bool InferAllTypes();
373 /// error - Throw an exception, prefixing it with information about this
375 void error(const std::string &Msg) const;
377 void print(std::ostream &OS) const;
381 TreePatternNode *ParseTreePattern(DagInit *DI);
384 /// DAGDefaultOperand - One of these is created for each PredicateOperand
385 /// or OptionalDefOperand that has a set ExecuteAlways / DefaultOps field.
386 struct DAGDefaultOperand {
387 std::vector<TreePatternNode*> DefaultOps;
390 class DAGInstruction {
391 TreePattern *Pattern;
392 std::vector<Record*> Results;
393 std::vector<Record*> Operands;
394 std::vector<Record*> ImpResults;
395 std::vector<Record*> ImpOperands;
396 TreePatternNode *ResultPattern;
398 DAGInstruction(TreePattern *TP,
399 const std::vector<Record*> &results,
400 const std::vector<Record*> &operands,
401 const std::vector<Record*> &impresults,
402 const std::vector<Record*> &impoperands)
403 : Pattern(TP), Results(results), Operands(operands),
404 ImpResults(impresults), ImpOperands(impoperands),
407 const TreePattern *getPattern() const { return Pattern; }
408 unsigned getNumResults() const { return Results.size(); }
409 unsigned getNumOperands() const { return Operands.size(); }
410 unsigned getNumImpResults() const { return ImpResults.size(); }
411 unsigned getNumImpOperands() const { return ImpOperands.size(); }
412 const std::vector<Record*>& getImpResults() const { return ImpResults; }
414 void setResultPattern(TreePatternNode *R) { ResultPattern = R; }
416 Record *getResult(unsigned RN) const {
417 assert(RN < Results.size());
421 Record *getOperand(unsigned ON) const {
422 assert(ON < Operands.size());
426 Record *getImpResult(unsigned RN) const {
427 assert(RN < ImpResults.size());
428 return ImpResults[RN];
431 Record *getImpOperand(unsigned ON) const {
432 assert(ON < ImpOperands.size());
433 return ImpOperands[ON];
436 TreePatternNode *getResultPattern() const { return ResultPattern; }
439 /// PatternToMatch - Used by CodeGenDAGPatterns to keep tab of patterns
440 /// processed to produce isel.
441 struct PatternToMatch {
442 PatternToMatch(ListInit *preds,
443 TreePatternNode *src, TreePatternNode *dst,
444 const std::vector<Record*> &dstregs,
445 unsigned complexity):
446 Predicates(preds), SrcPattern(src), DstPattern(dst), Dstregs(dstregs),
447 AddedComplexity(complexity) {};
449 ListInit *Predicates; // Top level predicate conditions to match.
450 TreePatternNode *SrcPattern; // Source pattern to match.
451 TreePatternNode *DstPattern; // Resulting pattern.
452 std::vector<Record*> Dstregs; // Physical register defs being matched.
453 unsigned AddedComplexity; // Add to matching pattern complexity.
455 ListInit *getPredicates() const { return Predicates; }
456 TreePatternNode *getSrcPattern() const { return SrcPattern; }
457 TreePatternNode *getDstPattern() const { return DstPattern; }
458 const std::vector<Record*> &getDstRegs() const { return Dstregs; }
459 unsigned getAddedComplexity() const { return AddedComplexity; }
461 std::string getPredicateCheck() const;
465 class CodeGenDAGPatterns {
466 RecordKeeper &Records;
467 CodeGenTarget Target;
468 std::vector<CodeGenIntrinsic> Intrinsics;
469 std::vector<CodeGenIntrinsic> TgtIntrinsics;
471 std::map<Record*, SDNodeInfo> SDNodes;
472 std::map<Record*, std::pair<Record*, std::string> > SDNodeXForms;
473 std::map<Record*, ComplexPattern> ComplexPatterns;
474 std::map<Record*, TreePattern*> PatternFragments;
475 std::map<Record*, DAGDefaultOperand> DefaultOperands;
476 std::map<Record*, DAGInstruction> Instructions;
478 // Specific SDNode definitions:
479 Record *intrinsic_void_sdnode;
480 Record *intrinsic_w_chain_sdnode, *intrinsic_wo_chain_sdnode;
482 /// PatternsToMatch - All of the things we are matching on the DAG. The first
483 /// value is the pattern to match, the second pattern is the result to
485 std::vector<PatternToMatch> PatternsToMatch;
487 CodeGenDAGPatterns(RecordKeeper &R);
488 ~CodeGenDAGPatterns();
490 CodeGenTarget &getTargetInfo() { return Target; }
491 const CodeGenTarget &getTargetInfo() const { return Target; }
493 Record *getSDNodeNamed(const std::string &Name) const;
495 const SDNodeInfo &getSDNodeInfo(Record *R) const {
496 assert(SDNodes.count(R) && "Unknown node!");
497 return SDNodes.find(R)->second;
500 // Node transformation lookups.
501 typedef std::pair<Record*, std::string> NodeXForm;
502 const NodeXForm &getSDNodeTransform(Record *R) const {
503 assert(SDNodeXForms.count(R) && "Invalid transform!");
504 return SDNodeXForms.find(R)->second;
507 typedef std::map<Record*, NodeXForm>::const_iterator nx_iterator;
508 nx_iterator nx_begin() const { return SDNodeXForms.begin(); }
509 nx_iterator nx_end() const { return SDNodeXForms.end(); }
512 const ComplexPattern &getComplexPattern(Record *R) const {
513 assert(ComplexPatterns.count(R) && "Unknown addressing mode!");
514 return ComplexPatterns.find(R)->second;
517 const CodeGenIntrinsic &getIntrinsic(Record *R) const {
518 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
519 if (Intrinsics[i].TheDef == R) return Intrinsics[i];
520 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
521 if (TgtIntrinsics[i].TheDef == R) return TgtIntrinsics[i];
522 assert(0 && "Unknown intrinsic!");
526 const CodeGenIntrinsic &getIntrinsicInfo(unsigned IID) const {
527 if (IID-1 < Intrinsics.size())
528 return Intrinsics[IID-1];
529 if (IID-Intrinsics.size()-1 < TgtIntrinsics.size())
530 return TgtIntrinsics[IID-Intrinsics.size()-1];
531 assert(0 && "Bad intrinsic ID!");
535 unsigned getIntrinsicID(Record *R) const {
536 for (unsigned i = 0, e = Intrinsics.size(); i != e; ++i)
537 if (Intrinsics[i].TheDef == R) return i;
538 for (unsigned i = 0, e = TgtIntrinsics.size(); i != e; ++i)
539 if (TgtIntrinsics[i].TheDef == R) return i + Intrinsics.size();
540 assert(0 && "Unknown intrinsic!");
544 const DAGDefaultOperand &getDefaultOperand(Record *R) {
545 assert(DefaultOperands.count(R) &&"Isn't an analyzed default operand!");
546 return DefaultOperands.find(R)->second;
549 // Pattern Fragment information.
550 TreePattern *getPatternFragment(Record *R) const {
551 assert(PatternFragments.count(R) && "Invalid pattern fragment request!");
552 return PatternFragments.find(R)->second;
554 typedef std::map<Record*, TreePattern*>::const_iterator pf_iterator;
555 pf_iterator pf_begin() const { return PatternFragments.begin(); }
556 pf_iterator pf_end() const { return PatternFragments.end(); }
558 // Patterns to match information.
559 typedef std::vector<PatternToMatch>::const_iterator ptm_iterator;
560 ptm_iterator ptm_begin() const { return PatternsToMatch.begin(); }
561 ptm_iterator ptm_end() const { return PatternsToMatch.end(); }
565 const DAGInstruction &getInstruction(Record *R) const {
566 assert(Instructions.count(R) && "Unknown instruction!");
567 return Instructions.find(R)->second;
570 Record *get_intrinsic_void_sdnode() const {
571 return intrinsic_void_sdnode;
573 Record *get_intrinsic_w_chain_sdnode() const {
574 return intrinsic_w_chain_sdnode;
576 Record *get_intrinsic_wo_chain_sdnode() const {
577 return intrinsic_wo_chain_sdnode;
581 void ParseNodeInfo();
582 void ParseNodeTransforms();
583 void ParseComplexPatterns();
584 void ParsePatternFragments();
585 void ParseDefaultOperands();
586 void ParseInstructions();
587 void ParsePatterns();
588 void InferInstructionFlags();
589 void GenerateVariants();
591 void FindPatternInputsAndOutputs(TreePattern *I, TreePatternNode *Pat,
592 std::map<std::string,
593 TreePatternNode*> &InstInputs,
594 std::map<std::string,
595 TreePatternNode*> &InstResults,
596 std::vector<Record*> &InstImpInputs,
597 std::vector<Record*> &InstImpResults);
599 } // end namespace llvm