1 //===- InstrInfoEmitter.h - Generate a Instruction Set Desc. ----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This tablegen backend is responsible for emitting a description of the target
11 // instruction set for the code generator.
13 //===----------------------------------------------------------------------===//
15 #ifndef INSTRSELECTOR_EMITTER_H
16 #define INSTRSELECTOR_EMITTER_H
18 #include "TableGenBackend.h"
19 #include "CodeGenWrappers.h"
26 class InstrSelectorEmitter;
28 /// NodeType - Represents Information parsed from the DagNode entries.
32 Any, // No constraint on type
33 Val, // A non-void type
34 Arg0, // Value matches the type of Arg0
35 Arg1, // Value matches the type of Arg1
36 Ptr, // Tree node is the type of the target pointer
38 Void, // Tree node always returns void
41 ArgResultTypes ResultType;
42 std::vector<ArgResultTypes> ArgTypes;
44 NodeType(ArgResultTypes RT, std::vector<ArgResultTypes> &AT) : ResultType(RT){
48 NodeType() : ResultType(Val) {}
49 NodeType(const NodeType &N) : ResultType(N.ResultType), ArgTypes(N.ArgTypes){}
51 static ArgResultTypes Translate(Record *R);
56 /// TreePatternNode - Represent a node of the tree patterns.
58 class TreePatternNode {
59 /// Operator - The operation that this node represents... this is null if this
63 /// Type - The inferred value type...
67 /// Children - If this is not a leaf (Operator != 0), this is the subtrees
69 std::vector<std::pair<TreePatternNode*, std::string> > Children;
71 /// Value - If this node is a leaf, this indicates what the thing is.
75 TreePatternNode(Record *o, const std::vector<std::pair<TreePatternNode*,
77 : Operator(o), Type(MVT::Other), Children(c), Value(0) {}
78 TreePatternNode(Init *V) : Operator(0), Type(MVT::Other), Value(V) {}
80 Record *getOperator() const {
81 assert(Operator && "This is a leaf node!");
84 MVT::ValueType getType() const { return Type; }
85 void setType(MVT::ValueType T) { Type = T; }
87 bool isLeaf() const { return Operator == 0; }
89 unsigned getNumChildren() const { return Children.size(); }
90 TreePatternNode *getChild(unsigned c) const {
91 assert(Operator != 0 && "This is a leaf node!");
92 assert(c < Children.size() && "Child access out of range!");
93 return Children[c].first;
95 const std::string &getChildName(unsigned c) const {
96 assert(Operator != 0 && "This is a leaf node!");
97 assert(c < Children.size() && "Child access out of range!");
98 return Children[c].second;
101 Init *getValue() const {
102 assert(Operator == 0 && "This is not a leaf node!");
106 /// getValueRecord - Returns the value of this tree node as a record. For now
107 /// we only allow DefInit's as our leaf values, so this is used.
108 Record *getValueRecord() const;
110 /// clone - Make a copy of this tree and all of its children.
112 TreePatternNode *clone() const;
116 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
117 /// are not themselves completely resolved, clone the nonterminal and resolve
118 /// it with the using context we provide.
119 void InstantiateNonterminals(InstrSelectorEmitter &ISE);
121 /// UpdateNodeType - Set the node type of N to VT if VT contains information.
122 /// If N already contains a conflicting type, then throw an exception. This
123 /// returns true if any information was updated.
125 bool updateNodeType(MVT::ValueType VT, const std::string &RecName);
128 std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N);
132 /// Pattern - Represent a pattern of one form or another. Currently, three
133 /// types of patterns are possible: Instruction's, Nonterminals, and Expanders.
137 Nonterminal, Instruction, Expander
140 /// PTy - The type of pattern this is.
144 /// Tree - The tree pattern which corresponds to this pattern. Note that if
145 /// there was a (set) node on the outside level that it has been stripped off.
147 TreePatternNode *Tree;
149 /// Result - If this is an instruction or expander pattern, this is the
150 /// register result, specified with a (set) in the pattern.
152 std::string ResultName; // The name of the result value...
153 TreePatternNode *ResultNode; // The leaf node for the result register...
155 /// TheRecord - The actual TableGen record corresponding to this pattern.
159 /// Resolved - This is true of the pattern is useful in practice. In
160 /// particular, some non-terminals will have non-resolvable types. When a
161 /// user of the non-terminal is later found, they will have inferred a type
162 /// for the result of the non-terminal, which cause a clone of an unresolved
163 /// nonterminal to be made which is "resolved".
167 /// Args - This is a list of all of the arguments to this pattern, which are
168 /// the non-void leaf nodes in this pattern.
169 std::vector<std::pair<TreePatternNode*, std::string> > Args;
171 /// ISE - the instruction selector emitter coordinating this madness.
173 InstrSelectorEmitter &ISE;
176 /// Pattern constructor - Parse the specified DagInitializer into the current
178 Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
179 InstrSelectorEmitter &ise);
181 /// Pattern - Constructor used for cloning nonterminal patterns
182 Pattern(TreePatternNode *tree, Record *rec, bool res,
183 InstrSelectorEmitter &ise)
184 : PTy(Nonterminal), Tree(tree), ResultNode(0), TheRecord(rec),
185 Resolved(res), ISE(ise) {
186 calculateArgs(Tree, "");
189 /// getPatternType - Return what flavor of Record this pattern originated from
191 PatternType getPatternType() const { return PTy; }
193 /// getTree - Return the tree pattern which corresponds to this pattern.
195 TreePatternNode *getTree() const { return Tree; }
197 Record *getResult() const {
198 return ResultNode ? ResultNode->getValueRecord() : 0;
200 const std::string &getResultName() const { return ResultName; }
201 TreePatternNode *getResultNode() const { return ResultNode; }
203 /// getRecord - Return the actual TableGen record corresponding to this
206 Record *getRecord() const { return TheRecord; }
208 unsigned getNumArgs() const { return Args.size(); }
209 TreePatternNode *getArg(unsigned i) const {
210 assert(i < Args.size() && "Argument reference out of range!");
211 return Args[i].first;
213 Record *getArgRec(unsigned i) const {
214 return getArg(i)->getValueRecord();
216 Init *getArgVal(unsigned i) const {
217 return getArg(i)->getValue();
219 const std::string &getArgName(unsigned i) const {
220 assert(i < Args.size() && "Argument reference out of range!");
221 return Args[i].second;
224 bool isResolved() const { return Resolved; }
226 /// InferAllTypes - Runs the type inference engine on the current pattern,
227 /// stopping when nothing can be inferred, then updating the Resolved field.
228 void InferAllTypes();
230 /// InstantiateNonterminals - If this pattern refers to any nonterminals which
231 /// are not themselves completely resolved, clone the nonterminal and resolve
232 /// it with the using context we provide.
233 void InstantiateNonterminals() {
234 Tree->InstantiateNonterminals(ISE);
237 /// clone - This method is used to make an exact copy of the current pattern,
238 /// then change the "TheRecord" instance variable to the specified record.
240 Pattern *clone(Record *R) const;
242 /// error - Throw an exception, prefixing it with information about this
244 void error(const std::string &Msg) const;
246 /// getSlotName - If this is a leaf node, return the slot name that the
247 /// operand will update.
248 std::string getSlotName() const;
249 static std::string getSlotName(Record *R);
254 void calculateArgs(TreePatternNode *N, const std::string &Name);
255 MVT::ValueType getIntrinsicType(Record *R) const;
256 TreePatternNode *ParseTreePattern(DagInit *DI);
257 bool InferTypes(TreePatternNode *N, bool &MadeChange);
260 std::ostream &operator<<(std::ostream &OS, const Pattern &P);
263 /// PatternOrganizer - This class represents all of the patterns which are
264 /// useful for the instruction selector, neatly catagorized in a hierarchical
266 struct PatternOrganizer {
267 /// PatternsForNode - The list of patterns which can produce a value of a
268 /// particular slot type, given a particular root node in the tree. All of
269 /// the patterns in this vector produce the same value type and have the same
271 typedef std::vector<Pattern*> PatternsForNode;
273 /// NodesForSlot - This map keeps track of all of the root DAG nodes which can
274 /// lead to the production of a value for this slot. All of the patterns in
275 /// this data structure produces values of the same slot.
276 typedef std::map<Record*, PatternsForNode> NodesForSlot;
278 /// AllPatterns - This data structure contains all patterns in the instruction
280 std::map<std::string, NodesForSlot> AllPatterns;
282 // Forwarding functions...
283 typedef std::map<std::string, NodesForSlot>::iterator iterator;
284 iterator begin() { return AllPatterns.begin(); }
285 iterator end() { return AllPatterns.end(); }
288 /// addPattern - Add the specified pattern to the appropriate location in the
290 void addPattern(Pattern *P);
294 /// InstrSelectorEmitter - The top-level class which coordinates construction
295 /// and emission of the instruction selector.
297 class InstrSelectorEmitter : public TableGenBackend {
298 RecordKeeper &Records;
299 CodeGenTarget Target;
301 std::map<Record*, NodeType> NodeTypes;
303 /// Patterns - a list of all of the patterns defined by the target description
305 std::map<Record*, Pattern*> Patterns;
307 /// InstantiatedNTs - A data structure to keep track of which nonterminals
308 /// have been instantiated already...
310 std::map<std::pair<Pattern*,MVT::ValueType>, Record*> InstantiatedNTs;
312 /// ComputableValues - This map indicates which patterns can be used to
313 /// generate a value that is used by the selector. The keys of this map
314 /// implicitly define the values that are used by the selector.
316 PatternOrganizer ComputableValues;
319 InstrSelectorEmitter(RecordKeeper &R) : Records(R) {}
321 // run - Output the instruction set description, returning true on failure.
322 void run(std::ostream &OS);
324 const CodeGenTarget &getTarget() const { return Target; }
325 std::map<Record*, NodeType> &getNodeTypes() { return NodeTypes; }
326 const NodeType &getNodeType(Record *R) const {
327 std::map<Record*, NodeType>::const_iterator I = NodeTypes.find(R);
328 assert(I != NodeTypes.end() && "Unknown node type!");
332 /// getPattern - return the pattern corresponding to the specified record, or
333 /// null if there is none.
334 Pattern *getPattern(Record *R) const {
335 std::map<Record*, Pattern*>::const_iterator I = Patterns.find(R);
336 return I != Patterns.end() ? I->second : 0;
339 /// ReadNonterminal - This method parses the specified record as a
340 /// nonterminal, but only if it hasn't been read in already.
341 Pattern *ReadNonterminal(Record *R);
343 /// InstantiateNonterminal - This method takes the nonterminal specified by
344 /// NT, which should not be completely resolved, clones it, applies ResultTy
345 /// to its root, then runs the type inference stuff on it. This should
346 /// produce a newly resolved nonterminal, which we make a record for and
347 /// return. To be extra fancy and efficient, this only makes one clone for
348 /// each type it is instantiated with.
349 Record *InstantiateNonterminal(Pattern *NT, MVT::ValueType ResultTy);
352 // ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
353 // turning them into the more accessible NodeTypes data structure.
354 void ReadNodeTypes();
356 // ReadNonTerminals - Read in all nonterminals and incorporate them into our
358 void ReadNonterminals();
360 // ReadInstructionPatterns - Read in all subclasses of Instruction, and
361 // process those with a useful Pattern field.
362 void ReadInstructionPatterns();
364 // ReadExpanderPatterns - Read in all of the expanded patterns.
365 void ReadExpanderPatterns();
367 // InstantiateNonterminals - Instantiate any unresolved nonterminals with
368 // information from the context that they are used in.
369 void InstantiateNonterminals();
371 // CalculateComputableValues - Fill in the ComputableValues map through
372 // analysis of the patterns we are playing with.
373 void CalculateComputableValues();
375 // EmitMatchCosters - Given a list of patterns, which all have the same root
376 // pattern operator, emit an efficient decision tree to decide which one to
377 // pick. This is structured this way to avoid reevaluations of non-obvious
379 void EmitMatchCosters(std::ostream &OS,
380 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
381 const std::string &VarPrefix, unsigned Indent);
383 /// PrintExpanderOperand - Print out Arg as part of the instruction emission
384 /// process for the expander pattern P. This argument may be referencing some
385 /// values defined in P, or may just be physical register references or
386 /// something like that. If PrintArg is true, we are printing out arguments
387 /// to the BuildMI call. If it is false, we are printing the result register
389 void PrintExpanderOperand(Init *Arg, const std::string &NameVar,
390 TreePatternNode *ArgDecl, Pattern *P,
391 bool PrintArg, std::ostream &OS);