blob: a3c535cad4e34ba90c5f2ca58abb07927fd97e35 [file] [log] [blame]
Chris Lattnerf5bd1b72003-10-05 19:27:59 +00001//===- InstrInfoEmitter.cpp - Generate a Instruction Set Desc. ------------===//
2//
3// This tablegen backend is responsible for emitting a description of the target
4// instruction set for the code generator.
5//
6//===----------------------------------------------------------------------===//
7
8#include "InstrSelectorEmitter.h"
9#include "CodeGenWrappers.h"
10#include "Record.h"
11#include "Support/Debug.h"
12#include "Support/StringExtras.h"
13#include <set>
14
15NodeType::ArgResultTypes NodeType::Translate(Record *R) {
16 const std::string &Name = R->getName();
17 if (Name == "DNVT_any") return Any;
18 if (Name == "DNVT_void") return Void;
19 if (Name == "DNVT_val" ) return Val;
20 if (Name == "DNVT_arg0") return Arg0;
21 if (Name == "DNVT_arg1") return Arg1;
22 if (Name == "DNVT_ptr" ) return Ptr;
23 if (Name == "DNVT_i8" ) return I8;
24 throw "Unknown DagNodeValType '" + Name + "'!";
25}
26
27
28//===----------------------------------------------------------------------===//
29// TreePatternNode implementation
30//
31
32/// getValueRecord - Returns the value of this tree node as a record. For now
33/// we only allow DefInit's as our leaf values, so this is used.
34Record *TreePatternNode::getValueRecord() const {
35 DefInit *DI = dynamic_cast<DefInit*>(getValue());
36 assert(DI && "Instruction Selector does not yet support non-def leaves!");
37 return DI->getDef();
38}
39
40
41// updateNodeType - Set the node type of N to VT if VT contains information. If
42// N already contains a conflicting type, then throw an exception
43//
44bool TreePatternNode::updateNodeType(MVT::ValueType VT,
45 const std::string &RecName) {
46 if (VT == MVT::Other || getType() == VT) return false;
47 if (getType() == MVT::Other) {
48 setType(VT);
49 return true;
50 }
51
52 throw "Type inferfence contradiction found for pattern " + RecName;
53}
54
55/// InstantiateNonterminals - If this pattern refers to any nonterminals which
56/// are not themselves completely resolved, clone the nonterminal and resolve it
57/// with the using context we provide.
58///
59void TreePatternNode::InstantiateNonterminals(InstrSelectorEmitter &ISE) {
60 if (!isLeaf()) {
61 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
62 getChild(i)->InstantiateNonterminals(ISE);
63 return;
64 }
65
66 // If this is a leaf, it might be a reference to a nonterminal! Check now.
67 Record *R = getValueRecord();
68 if (R->isSubClassOf("Nonterminal")) {
69 Pattern *NT = ISE.getPattern(R);
70 if (!NT->isResolved()) {
71 // We found an unresolved nonterminal reference. Ask the ISE to clone
72 // it for us, then update our reference to the fresh, new, resolved,
73 // nonterminal.
74
75 Value = new DefInit(ISE.InstantiateNonterminal(NT, getType()));
76 }
77 }
78}
79
80
81/// clone - Make a copy of this tree and all of its children.
82///
83TreePatternNode *TreePatternNode::clone() const {
84 TreePatternNode *New;
85 if (isLeaf()) {
86 New = new TreePatternNode(Value);
87 } else {
88 std::vector<std::pair<TreePatternNode*, std::string> > CChildren;
89 CChildren.reserve(Children.size());
90 for (unsigned i = 0, e = getNumChildren(); i != e; ++i)
91 CChildren.push_back(std::make_pair(getChild(i)->clone(),getChildName(i)));
92 New = new TreePatternNode(Operator, CChildren);
93 }
94 New->setType(Type);
95 return New;
96}
97
98std::ostream &operator<<(std::ostream &OS, const TreePatternNode &N) {
99 if (N.isLeaf())
100 return OS << N.getType() << ":" << *N.getValue();
101 OS << "(" << N.getType() << ":";
102 OS << N.getOperator()->getName();
103
104 if (N.getNumChildren() != 0) {
105 OS << " " << *N.getChild(0);
106 for (unsigned i = 1, e = N.getNumChildren(); i != e; ++i)
107 OS << ", " << *N.getChild(i);
108 }
109 return OS << ")";
110}
111
112void TreePatternNode::dump() const { std::cerr << *this; }
113
114//===----------------------------------------------------------------------===//
115// Pattern implementation
116//
117
118// Parse the specified DagInit into a TreePattern which we can use.
119//
120Pattern::Pattern(PatternType pty, DagInit *RawPat, Record *TheRec,
121 InstrSelectorEmitter &ise)
122 : PTy(pty), ResultNode(0), TheRecord(TheRec), ISE(ise) {
123
124 // First, parse the pattern...
125 Tree = ParseTreePattern(RawPat);
126
127 // Run the type-inference engine...
128 InferAllTypes();
129
130 if (PTy == Instruction || PTy == Expander) {
131 // Check to make sure there is not any unset types in the tree pattern...
132 if (!isResolved()) {
133 std::cerr << "In pattern: " << *Tree << "\n";
134 error("Could not infer all types!");
135 }
136
137 // Check to see if we have a top-level (set) of a register.
138 if (Tree->getOperator()->getName() == "set") {
139 assert(Tree->getNumChildren() == 2 && "Set with != 2 arguments?");
140 if (!Tree->getChild(0)->isLeaf())
141 error("Arg #0 of set should be a register or register class!");
142 ResultNode = Tree->getChild(0);
143 ResultName = Tree->getChildName(0);
144 Tree = Tree->getChild(1);
145 }
146 }
147
148 calculateArgs(Tree, "");
149}
150
151void Pattern::error(const std::string &Msg) const {
152 std::string M = "In ";
153 switch (PTy) {
154 case Nonterminal: M += "nonterminal "; break;
155 case Instruction: M += "instruction "; break;
156 case Expander : M += "expander "; break;
157 }
158 throw M + TheRecord->getName() + ": " + Msg;
159}
160
161/// calculateArgs - Compute the list of all of the arguments to this pattern,
162/// which are the non-void leaf nodes in this pattern.
163///
164void Pattern::calculateArgs(TreePatternNode *N, const std::string &Name) {
165 if (N->isLeaf() || N->getNumChildren() == 0) {
166 if (N->getType() != MVT::isVoid)
167 Args.push_back(std::make_pair(N, Name));
168 } else {
169 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i)
170 calculateArgs(N->getChild(i), N->getChildName(i));
171 }
172}
173
174/// getIntrinsicType - Check to see if the specified record has an intrinsic
175/// type which should be applied to it. This infer the type of register
176/// references from the register file information, for example.
177///
178MVT::ValueType Pattern::getIntrinsicType(Record *R) const {
179 // Check to see if this is a register or a register class...
180 if (R->isSubClassOf("RegisterClass"))
181 return getValueType(R->getValueAsDef("RegType"));
182 else if (R->isSubClassOf("Nonterminal"))
183 return ISE.ReadNonterminal(R)->getTree()->getType();
184 else if (R->isSubClassOf("Register")) {
185 std::cerr << "WARNING: Explicit registers not handled yet!\n";
186 return MVT::Other;
187 }
188
189 error("Unknown value used: " + R->getName());
190 return MVT::Other;
191}
192
193TreePatternNode *Pattern::ParseTreePattern(DagInit *Dag) {
194 Record *Operator = Dag->getNodeType();
195
196 if (Operator->isSubClassOf("ValueType")) {
197 // If the operator is a ValueType, then this must be "type cast" of a leaf
198 // node.
199 if (Dag->getNumArgs() != 1)
200 error("Type cast only valid for a leaf node!");
201
202 Init *Arg = Dag->getArg(0);
203 TreePatternNode *New;
204 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
205 New = new TreePatternNode(DI);
206 // If it's a regclass or something else known, set the type.
207 New->setType(getIntrinsicType(DI->getDef()));
208 } else if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
209 New = ParseTreePattern(DI);
210 } else {
211 Arg->dump();
212 error("Unknown leaf value for tree pattern!");
213 return 0;
214 }
215
216 // Apply the type cast...
217 New->updateNodeType(getValueType(Operator), TheRecord->getName());
218 return New;
219 }
220
221 if (!ISE.getNodeTypes().count(Operator))
222 error("Unrecognized node '" + Operator->getName() + "'!");
223
224 std::vector<std::pair<TreePatternNode*, std::string> > Children;
225
226 for (unsigned i = 0, e = Dag->getNumArgs(); i != e; ++i) {
227 Init *Arg = Dag->getArg(i);
228 if (DagInit *DI = dynamic_cast<DagInit*>(Arg)) {
229 Children.push_back(std::make_pair(ParseTreePattern(DI),
230 Dag->getArgName(i)));
231 } else if (DefInit *DefI = dynamic_cast<DefInit*>(Arg)) {
232 Record *R = DefI->getDef();
233 // Direct reference to a leaf DagNode? Turn it into a DagNode if its own.
234 if (R->isSubClassOf("DagNode")) {
235 Dag->setArg(i, new DagInit(R,
236 std::vector<std::pair<Init*, std::string> >()));
237 --i; // Revisit this node...
238 } else {
239 Children.push_back(std::make_pair(new TreePatternNode(DefI),
240 Dag->getArgName(i)));
241 // If it's a regclass or something else known, set the type.
242 Children.back().first->setType(getIntrinsicType(R));
243 }
244 } else {
245 Arg->dump();
246 error("Unknown leaf value for tree pattern!");
247 }
248 }
249
250 return new TreePatternNode(Operator, Children);
251}
252
253void Pattern::InferAllTypes() {
254 bool MadeChange, AnyUnset;
255 do {
256 MadeChange = false;
257 AnyUnset = InferTypes(Tree, MadeChange);
258 } while ((AnyUnset || MadeChange) && !(AnyUnset && !MadeChange));
259 Resolved = !AnyUnset;
260}
261
262
263// InferTypes - Perform type inference on the tree, returning true if there
264// are any remaining untyped nodes and setting MadeChange if any changes were
265// made.
266bool Pattern::InferTypes(TreePatternNode *N, bool &MadeChange) {
267 if (N->isLeaf()) return N->getType() == MVT::Other;
268
269 bool AnyUnset = false;
270 Record *Operator = N->getOperator();
271 const NodeType &NT = ISE.getNodeType(Operator);
272
273 // Check to see if we can infer anything about the argument types from the
274 // return types...
275 if (N->getNumChildren() != NT.ArgTypes.size())
276 error("Incorrect number of children for " + Operator->getName() + " node!");
277
278 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
279 TreePatternNode *Child = N->getChild(i);
280 AnyUnset |= InferTypes(Child, MadeChange);
281
282 switch (NT.ArgTypes[i]) {
283 case NodeType::Any: break;
284 case NodeType::I8:
285 MadeChange |= Child->updateNodeType(MVT::i1, TheRecord->getName());
286 break;
287 case NodeType::Arg0:
288 MadeChange |= Child->updateNodeType(N->getChild(0)->getType(),
289 TheRecord->getName());
290 break;
291 case NodeType::Arg1:
292 MadeChange |= Child->updateNodeType(N->getChild(1)->getType(),
293 TheRecord->getName());
294 break;
295 case NodeType::Val:
296 if (Child->getType() == MVT::isVoid)
297 error("Inferred a void node in an illegal place!");
298 break;
299 case NodeType::Ptr:
300 MadeChange |= Child->updateNodeType(ISE.getTarget().getPointerType(),
301 TheRecord->getName());
302 break;
303 case NodeType::Void:
304 MadeChange |= Child->updateNodeType(MVT::isVoid, TheRecord->getName());
305 break;
306 default: assert(0 && "Invalid argument ArgType!");
307 }
308 }
309
310 // See if we can infer anything about the return type now...
311 switch (NT.ResultType) {
312 case NodeType::Any: break;
313 case NodeType::Void:
314 MadeChange |= N->updateNodeType(MVT::isVoid, TheRecord->getName());
315 break;
316 case NodeType::I8:
317 MadeChange |= N->updateNodeType(MVT::i1, TheRecord->getName());
318 break;
319 case NodeType::Arg0:
320 MadeChange |= N->updateNodeType(N->getChild(0)->getType(),
321 TheRecord->getName());
322 break;
323 case NodeType::Arg1:
324 MadeChange |= N->updateNodeType(N->getChild(1)->getType(),
325 TheRecord->getName());
326 break;
327 case NodeType::Ptr:
328 MadeChange |= N->updateNodeType(ISE.getTarget().getPointerType(),
329 TheRecord->getName());
330 break;
331 case NodeType::Val:
332 if (N->getType() == MVT::isVoid)
333 error("Inferred a void node in an illegal place!");
334 break;
335 default:
336 assert(0 && "Unhandled type constraint!");
337 break;
338 }
339
340 return AnyUnset | N->getType() == MVT::Other;
341}
342
343/// clone - This method is used to make an exact copy of the current pattern,
344/// then change the "TheRecord" instance variable to the specified record.
345///
346Pattern *Pattern::clone(Record *R) const {
347 assert(PTy == Nonterminal && "Can only clone nonterminals");
348 return new Pattern(Tree->clone(), R, Resolved, ISE);
349}
350
351
352
353std::ostream &operator<<(std::ostream &OS, const Pattern &P) {
354 switch (P.getPatternType()) {
355 case Pattern::Nonterminal: OS << "Nonterminal pattern "; break;
356 case Pattern::Instruction: OS << "Instruction pattern "; break;
357 case Pattern::Expander: OS << "Expander pattern "; break;
358 }
359
360 OS << P.getRecord()->getName() << ":\t";
361
362 if (Record *Result = P.getResult())
363 OS << Result->getName() << " = ";
364 OS << *P.getTree();
365
366 if (!P.isResolved())
367 OS << " [not completely resolved]";
368 return OS;
369}
370
371void Pattern::dump() const { std::cerr << *this; }
372
373
374
375/// getSlotName - If this is a leaf node, return the slot name that the operand
376/// will update.
377std::string Pattern::getSlotName() const {
378 if (getPatternType() == Pattern::Nonterminal) {
379 // Just use the nonterminal name, which will already include the type if
380 // it has been cloned.
381 return getRecord()->getName();
382 } else {
383 std::string SlotName;
384 if (getResult())
385 SlotName = getResult()->getName()+"_";
386 else
387 SlotName = "Void_";
388 return SlotName + getName(getTree()->getType());
389 }
390}
391
392/// getSlotName - If this is a leaf node, return the slot name that the
393/// operand will update.
394std::string Pattern::getSlotName(Record *R) {
395 if (R->isSubClassOf("Nonterminal")) {
396 // Just use the nonterminal name, which will already include the type if
397 // it has been cloned.
398 return R->getName();
399 } else if (R->isSubClassOf("RegisterClass")) {
400 MVT::ValueType Ty = getValueType(R->getValueAsDef("RegType"));
401 return R->getName() + "_" + getName(Ty);
402 } else {
403 assert(0 && "Don't know how to get a slot name for this!");
404 }
405 return "";
406}
407
408//===----------------------------------------------------------------------===//
409// PatternOrganizer implementation
410//
411
412/// addPattern - Add the specified pattern to the appropriate location in the
413/// collection.
414void PatternOrganizer::addPattern(Pattern *P) {
415 NodesForSlot &Nodes = AllPatterns[P->getSlotName()];
416 if (!P->getTree()->isLeaf())
417 Nodes[P->getTree()->getOperator()].push_back(P);
418 else {
419 // Right now we only support DefInit's with node types...
420 Nodes[P->getTree()->getValueRecord()].push_back(P);
421 }
422}
423
424
425
426//===----------------------------------------------------------------------===//
427// InstrSelectorEmitter implementation
428//
429
430/// ReadNodeTypes - Read in all of the node types in the current RecordKeeper,
431/// turning them into the more accessible NodeTypes data structure.
432///
433void InstrSelectorEmitter::ReadNodeTypes() {
434 std::vector<Record*> Nodes = Records.getAllDerivedDefinitions("DagNode");
435 DEBUG(std::cerr << "Getting node types: ");
436 for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
437 Record *Node = Nodes[i];
438
439 // Translate the return type...
440 NodeType::ArgResultTypes RetTy =
441 NodeType::Translate(Node->getValueAsDef("RetType"));
442
443 // Translate the arguments...
444 ListInit *Args = Node->getValueAsListInit("ArgTypes");
445 std::vector<NodeType::ArgResultTypes> ArgTypes;
446
447 for (unsigned a = 0, e = Args->getSize(); a != e; ++a) {
448 if (DefInit *DI = dynamic_cast<DefInit*>(Args->getElement(a)))
449 ArgTypes.push_back(NodeType::Translate(DI->getDef()));
450 else
451 throw "In node " + Node->getName() + ", argument is not a Def!";
452
453 if (a == 0 && ArgTypes.back() == NodeType::Arg0)
454 throw "In node " + Node->getName() + ", arg 0 cannot have type 'arg0'!";
455 if (a == 1 && ArgTypes.back() == NodeType::Arg1)
456 throw "In node " + Node->getName() + ", arg 1 cannot have type 'arg1'!";
457 }
458 if ((RetTy == NodeType::Arg0 && Args->getSize() == 0) ||
459 (RetTy == NodeType::Arg1 && Args->getSize() < 2))
460 throw "In node " + Node->getName() +
461 ", invalid return type for node with this many operands!";
462
463 // Add the node type mapping now...
464 NodeTypes[Node] = NodeType(RetTy, ArgTypes);
465 DEBUG(std::cerr << Node->getName() << ", ");
466 }
467 DEBUG(std::cerr << "DONE!\n");
468}
469
470Pattern *InstrSelectorEmitter::ReadNonterminal(Record *R) {
471 Pattern *&P = Patterns[R];
472 if (P) return P; // Don't reread it!
473
474 DagInit *DI = R->getValueAsDag("Pattern");
475 P = new Pattern(Pattern::Nonterminal, DI, R, *this);
476 DEBUG(std::cerr << "Parsed " << *P << "\n");
477 return P;
478}
479
480
481// ReadNonTerminals - Read in all nonterminals and incorporate them into our
482// pattern database.
483void InstrSelectorEmitter::ReadNonterminals() {
484 std::vector<Record*> NTs = Records.getAllDerivedDefinitions("Nonterminal");
485 for (unsigned i = 0, e = NTs.size(); i != e; ++i)
486 ReadNonterminal(NTs[i]);
487}
488
489
490/// ReadInstructionPatterns - Read in all subclasses of Instruction, and process
491/// those with a useful Pattern field.
492///
493void InstrSelectorEmitter::ReadInstructionPatterns() {
494 std::vector<Record*> Insts = Records.getAllDerivedDefinitions("Instruction");
495 for (unsigned i = 0, e = Insts.size(); i != e; ++i) {
496 Record *Inst = Insts[i];
497 if (DagInit *DI = dynamic_cast<DagInit*>(Inst->getValueInit("Pattern"))) {
498 Patterns[Inst] = new Pattern(Pattern::Instruction, DI, Inst, *this);
499 DEBUG(std::cerr << "Parsed " << *Patterns[Inst] << "\n");
500 }
501 }
502}
503
504/// ReadExpanderPatterns - Read in all expander patterns...
505///
506void InstrSelectorEmitter::ReadExpanderPatterns() {
507 std::vector<Record*> Expanders = Records.getAllDerivedDefinitions("Expander");
508 for (unsigned i = 0, e = Expanders.size(); i != e; ++i) {
509 Record *Expander = Expanders[i];
510 DagInit *DI = Expander->getValueAsDag("Pattern");
511 Patterns[Expander] = new Pattern(Pattern::Expander, DI, Expander, *this);
512 DEBUG(std::cerr << "Parsed " << *Patterns[Expander] << "\n");
513 }
514}
515
516
517// InstantiateNonterminals - Instantiate any unresolved nonterminals with
518// information from the context that they are used in.
519//
520void InstrSelectorEmitter::InstantiateNonterminals() {
521 DEBUG(std::cerr << "Instantiating nonterminals:\n");
522 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
523 E = Patterns.end(); I != E; ++I)
524 if (I->second->isResolved())
525 I->second->InstantiateNonterminals();
526}
527
528/// InstantiateNonterminal - This method takes the nonterminal specified by
529/// NT, which should not be completely resolved, clones it, applies ResultTy
530/// to its root, then runs the type inference stuff on it. This should
531/// produce a newly resolved nonterminal, which we make a record for and
532/// return. To be extra fancy and efficient, this only makes one clone for
533/// each type it is instantiated with.
534Record *InstrSelectorEmitter::InstantiateNonterminal(Pattern *NT,
535 MVT::ValueType ResultTy) {
536 assert(!NT->isResolved() && "Nonterminal is already resolved!");
537
538 // Check to see if we have already instantiated this pair...
539 Record* &Slot = InstantiatedNTs[std::make_pair(NT, ResultTy)];
540 if (Slot) return Slot;
541
542 Record *New = new Record(NT->getRecord()->getName()+"_"+getName(ResultTy));
543
544 // Copy over the superclasses...
545 const std::vector<Record*> &SCs = NT->getRecord()->getSuperClasses();
546 for (unsigned i = 0, e = SCs.size(); i != e; ++i)
547 New->addSuperClass(SCs[i]);
548
549 DEBUG(std::cerr << " Nonterminal '" << NT->getRecord()->getName()
550 << "' for type '" << getName(ResultTy) << "', producing '"
551 << New->getName() << "'\n");
552
553 // Copy the pattern...
554 Pattern *NewPat = NT->clone(New);
555
556 // Apply the type to the root...
557 NewPat->getTree()->updateNodeType(ResultTy, New->getName());
558
559 // Infer types...
560 NewPat->InferAllTypes();
561
562 // Make sure everything is good to go now...
563 if (!NewPat->isResolved())
564 NewPat->error("Instantiating nonterminal did not resolve all types!");
565
566 // Add the pattern to the patterns map, add the record to the RecordKeeper,
567 // return the new record.
568 Patterns[New] = NewPat;
569 Records.addDef(New);
570 return Slot = New;
571}
572
573// CalculateComputableValues - Fill in the ComputableValues map through
574// analysis of the patterns we are playing with.
575void InstrSelectorEmitter::CalculateComputableValues() {
576 // Loop over all of the patterns, adding them to the ComputableValues map
577 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
578 E = Patterns.end(); I != E; ++I)
579 if (I->second->isResolved()) {
580 // We don't want to add patterns like R32 = R32. This is a hack working
581 // around a special case of a general problem, but for now we explicitly
582 // forbid these patterns. They can never match anyway.
583 Pattern *P = I->second;
584 if (!P->getResult() || !P->getTree()->isLeaf() ||
585 P->getResult() != P->getTree()->getValueRecord())
586 ComputableValues.addPattern(P);
587 }
588}
589
590#if 0
591// MoveIdenticalPatterns - Given a tree pattern 'P', move all of the tree
592// patterns which have the same top-level structure as P from the 'From' list to
593// the 'To' list.
594static void MoveIdenticalPatterns(TreePatternNode *P,
595 std::vector<std::pair<Pattern*, TreePatternNode*> > &From,
596 std::vector<std::pair<Pattern*, TreePatternNode*> > &To) {
597 assert(!P->isLeaf() && "All leaves are identical!");
598
599 const std::vector<TreePatternNode*> &PChildren = P->getChildren();
600 for (unsigned i = 0; i != From.size(); ++i) {
601 TreePatternNode *N = From[i].second;
602 assert(P->getOperator() == N->getOperator() &&"Differing operators?");
603 assert(PChildren.size() == N->getChildren().size() &&
604 "Nodes with different arity??");
605 bool isDifferent = false;
606 for (unsigned c = 0, e = PChildren.size(); c != e; ++c) {
607 TreePatternNode *PC = PChildren[c];
608 TreePatternNode *NC = N->getChild(c);
609 if (PC->isLeaf() != NC->isLeaf()) {
610 isDifferent = true;
611 break;
612 }
613
614 if (!PC->isLeaf()) {
615 if (PC->getOperator() != NC->getOperator()) {
616 isDifferent = true;
617 break;
618 }
619 } else { // It's a leaf!
620 if (PC->getValueRecord() != NC->getValueRecord()) {
621 isDifferent = true;
622 break;
623 }
624 }
625 }
626 // If it's the same as the reference one, move it over now...
627 if (!isDifferent) {
628 To.push_back(std::make_pair(From[i].first, N));
629 From.erase(From.begin()+i);
630 --i; // Don't skip an entry...
631 }
632 }
633}
634#endif
635
636static std::string getNodeName(Record *R) {
637 RecordVal *RV = R->getValue("EnumName");
638 if (RV)
639 if (Init *I = RV->getValue())
640 if (StringInit *SI = dynamic_cast<StringInit*>(I))
641 return SI->getValue();
642 return R->getName();
643}
644
645
646static void EmitPatternPredicates(TreePatternNode *Tree,
647 const std::string &VarName, std::ostream &OS){
648 OS << " && " << VarName << "->getNodeType() == ISD::"
649 << getNodeName(Tree->getOperator());
650
651 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
652 if (!Tree->getChild(c)->isLeaf())
653 EmitPatternPredicates(Tree->getChild(c),
654 VarName + "->getUse(" + utostr(c)+")", OS);
655}
656
657static void EmitPatternCosts(TreePatternNode *Tree, const std::string &VarName,
658 std::ostream &OS) {
659 for (unsigned c = 0, e = Tree->getNumChildren(); c != e; ++c)
660 if (Tree->getChild(c)->isLeaf()) {
661 OS << " + Match_"
662 << Pattern::getSlotName(Tree->getChild(c)->getValueRecord()) << "("
663 << VarName << "->getUse(" << c << "))";
664 } else {
665 EmitPatternCosts(Tree->getChild(c),
666 VarName + "->getUse(" + utostr(c) + ")", OS);
667 }
668}
669
670
671// EmitMatchCosters - Given a list of patterns, which all have the same root
672// pattern operator, emit an efficient decision tree to decide which one to
673// pick. This is structured this way to avoid reevaluations of non-obvious
674// subexpressions.
675void InstrSelectorEmitter::EmitMatchCosters(std::ostream &OS,
676 const std::vector<std::pair<Pattern*, TreePatternNode*> > &Patterns,
677 const std::string &VarPrefix,
678 unsigned IndentAmt) {
679 assert(!Patterns.empty() && "No patterns to emit matchers for!");
680 std::string Indent(IndentAmt, ' ');
681
682 // Load all of the operands of the root node into scalars for fast access
683 const NodeType &ONT = getNodeType(Patterns[0].second->getOperator());
684 for (unsigned i = 0, e = ONT.ArgTypes.size(); i != e; ++i)
685 OS << Indent << "SelectionDAGNode *" << VarPrefix << "_Op" << i
686 << " = N->getUse(" << i << ");\n";
687
688 // Compute the costs of computing the various nonterminals/registers, which
689 // are directly used at this level.
690 OS << "\n" << Indent << "// Operand matching costs...\n";
691 std::set<std::string> ComputedValues; // Avoid duplicate computations...
692 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
693 TreePatternNode *NParent = Patterns[i].second;
694 for (unsigned c = 0, e = NParent->getNumChildren(); c != e; ++c) {
695 TreePatternNode *N = NParent->getChild(c);
696 if (N->isLeaf()) {
697 Record *VR = N->getValueRecord();
698 const std::string &LeafName = VR->getName();
699 std::string OpName = VarPrefix + "_Op" + utostr(c);
700 std::string ValName = OpName + "_" + LeafName + "_Cost";
701 if (!ComputedValues.count(ValName)) {
702 OS << Indent << "unsigned " << ValName << " = Match_"
703 << Pattern::getSlotName(VR) << "(" << OpName << ");\n";
704 ComputedValues.insert(ValName);
705 }
706 }
707 }
708 }
709 OS << "\n";
710
711
712 std::string LocCostName = VarPrefix + "_Cost";
713 OS << Indent << "unsigned " << LocCostName << "Min = ~0U >> 1;\n"
714 << Indent << "unsigned " << VarPrefix << "_PatternMin = NoMatchPattern;\n";
715
716#if 0
717 // Separate out all of the patterns into groups based on what their top-level
718 // signature looks like...
719 std::vector<std::pair<Pattern*, TreePatternNode*> > PatternsLeft(Patterns);
720 while (!PatternsLeft.empty()) {
721 // Process all of the patterns that have the same signature as the last
722 // element...
723 std::vector<std::pair<Pattern*, TreePatternNode*> > Group;
724 MoveIdenticalPatterns(PatternsLeft.back().second, PatternsLeft, Group);
725 assert(!Group.empty() && "Didn't at least pick the source pattern?");
726
727#if 0
728 OS << "PROCESSING GROUP:\n";
729 for (unsigned i = 0, e = Group.size(); i != e; ++i)
730 OS << " " << *Group[i].first << "\n";
731 OS << "\n\n";
732#endif
733
734 OS << Indent << "{ // ";
735
736 if (Group.size() != 1) {
737 OS << Group.size() << " size group...\n";
738 OS << Indent << " unsigned " << VarPrefix << "_Pattern = NoMatch;\n";
739 } else {
740 OS << *Group[0].first << "\n";
741 OS << Indent << " unsigned " << VarPrefix << "_Pattern = "
742 << Group[0].first->getRecord()->getName() << "_Pattern;\n";
743 }
744
745 OS << Indent << " unsigned " << LocCostName << " = ";
746 if (Group.size() == 1)
747 OS << "1;\n"; // Add inst cost if at individual rec
748 else
749 OS << "0;\n";
750
751 // Loop over all of the operands, adding in their costs...
752 TreePatternNode *N = Group[0].second;
753 const std::vector<TreePatternNode*> &Children = N->getChildren();
754
755 // If necessary, emit conditionals to check for the appropriate tree
756 // structure here...
757 for (unsigned i = 0, e = Children.size(); i != e; ++i) {
758 TreePatternNode *C = Children[i];
759 if (C->isLeaf()) {
760 // We already calculated the cost for this leaf, add it in now...
761 OS << Indent << " " << LocCostName << " += "
762 << VarPrefix << "_Op" << utostr(i) << "_"
763 << C->getValueRecord()->getName() << "_Cost;\n";
764 } else {
765 // If it's not a leaf, we have to check to make sure that the current
766 // node has the appropriate structure, then recurse into it...
767 OS << Indent << " if (" << VarPrefix << "_Op" << i
768 << "->getNodeType() == ISD::" << getNodeName(C->getOperator())
769 << ") {\n";
770 std::vector<std::pair<Pattern*, TreePatternNode*> > SubPatterns;
771 for (unsigned n = 0, e = Group.size(); n != e; ++n)
772 SubPatterns.push_back(std::make_pair(Group[n].first,
773 Group[n].second->getChild(i)));
774 EmitMatchCosters(OS, SubPatterns, VarPrefix+"_Op"+utostr(i),
775 IndentAmt + 4);
776 OS << Indent << " }\n";
777 }
778 }
779
780 // If the cost for this match is less than the minimum computed cost so far,
781 // update the minimum cost and selected pattern.
782 OS << Indent << " if (" << LocCostName << " < " << LocCostName << "Min) { "
783 << LocCostName << "Min = " << LocCostName << "; " << VarPrefix
784 << "_PatternMin = " << VarPrefix << "_Pattern; }\n";
785
786 OS << Indent << "}\n";
787 }
788#endif
789
790 for (unsigned i = 0, e = Patterns.size(); i != e; ++i) {
791 Pattern *P = Patterns[i].first;
792 TreePatternNode *PTree = P->getTree();
793 unsigned PatternCost = 1;
794
795 // Check to see if there are any non-leaf elements in the pattern. If so,
796 // we need to emit a predicate for this match.
797 bool AnyNonLeaf = false;
798 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
799 if (!PTree->getChild(c)->isLeaf()) {
800 AnyNonLeaf = true;
801 break;
802 }
803
804 if (!AnyNonLeaf) { // No predicate necessary, just output a scope...
805 OS << " {// " << *P << "\n";
806 } else {
807 // We need to emit a predicate to make sure the tree pattern matches, do
808 // so now...
809 OS << " if (1";
810 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
811 if (!PTree->getChild(c)->isLeaf())
812 EmitPatternPredicates(PTree->getChild(c),
813 VarPrefix + "_Op" + utostr(c), OS);
814
815 OS << ") {\n // " << *P << "\n";
816 }
817
818 OS << " unsigned PatCost = " << PatternCost;
819
820 for (unsigned c = 0, e = PTree->getNumChildren(); c != e; ++c)
821 if (PTree->getChild(c)->isLeaf()) {
822 OS << " + " << VarPrefix << "_Op" << c << "_"
823 << PTree->getChild(c)->getValueRecord()->getName() << "_Cost";
824 } else {
825 EmitPatternCosts(PTree->getChild(c), VarPrefix + "_Op" + utostr(c), OS);
826 }
827 OS << ";\n";
828 OS << " if (PatCost < MinCost) { MinCost = PatCost; Pattern = "
829 << P->getRecord()->getName() << "_Pattern; }\n"
830 << " }\n";
831 }
832}
833
834static void ReduceAllOperands(TreePatternNode *N, const std::string &Name,
835 std::vector<std::pair<TreePatternNode*, std::string> > &Operands,
836 std::ostream &OS) {
837 if (N->isLeaf()) {
838 // If this is a leaf, register or nonterminal reference...
839 std::string SlotName = Pattern::getSlotName(N->getValueRecord());
840 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = Reduce_"
841 << SlotName << "(" << Name << ", MBB);\n";
842 Operands.push_back(std::make_pair(N, Name+"Val"));
843 } else if (N->getNumChildren() == 0) {
844 // This is a reference to a leaf tree node, like an immediate or frame
845 // index.
846 if (N->getType() != MVT::isVoid) {
847 std::string SlotName =
848 getNodeName(N->getOperator()) + "_" + getName(N->getType());
849 OS << " ReducedValue_" << SlotName << " *" << Name << "Val = "
850 << Name << "->getValue<ReducedValue_" << SlotName << ">(ISD::"
851 << SlotName << "_Slot);\n";
852 Operands.push_back(std::make_pair(N, Name+"Val"));
853 }
854 } else {
855 // Otherwise this is an interior node...
856 for (unsigned i = 0, e = N->getNumChildren(); i != e; ++i) {
857 std::string ChildName = Name + "_Op" + utostr(i);
858 OS << " SelectionDAGNode *" << ChildName << " = " << Name
859 << "->getUse(" << i << ");\n";
860 ReduceAllOperands(N->getChild(i), ChildName, Operands, OS);
861 }
862 }
863}
864
865/// PrintExpanderOperand - Print out Arg as part of the instruction emission
866/// process for the expander pattern P. This argument may be referencing some
867/// values defined in P, or may just be physical register references or
868/// something like that. If PrintArg is true, we are printing out arguments to
869/// the BuildMI call. If it is false, we are printing the result register
870/// name.
871void InstrSelectorEmitter::PrintExpanderOperand(Init *Arg,
872 const std::string &NameVar,
873 TreePatternNode *ArgDeclNode,
874 Pattern *P, bool PrintArg,
875 std::ostream &OS) {
876 if (DefInit *DI = dynamic_cast<DefInit*>(Arg)) {
877 Record *Arg = DI->getDef();
878 if (!ArgDeclNode->isLeaf() && ArgDeclNode->getNumChildren() != 0)
879 P->error("Expected leaf node as argument!");
880 Record *ArgDecl = ArgDeclNode->isLeaf() ? ArgDeclNode->getValueRecord() :
881 ArgDeclNode->getOperator();
882 if (Arg->isSubClassOf("Register")) {
883 // This is a physical register reference... make sure that the instruction
884 // requested a register!
885 if (!ArgDecl->isSubClassOf("RegisterClass"))
886 P->error("Argument mismatch for instruction pattern!");
887
888 // FIXME: This should check to see if the register is in the specified
889 // register class!
890 if (PrintArg) OS << ".addReg(";
891 OS << getQualifiedName(Arg);
892 if (PrintArg) OS << ")";
893 return;
894 } else if (Arg->isSubClassOf("RegisterClass")) {
895 // If this is a symbolic register class reference, we must be using a
896 // named value.
897 if (NameVar.empty()) P->error("Did not specify WHICH register to pass!");
898 if (Arg != ArgDecl) P->error("Instruction pattern mismatch!");
899
900 if (PrintArg) OS << ".addReg(";
901 OS << NameVar;
902 if (PrintArg) OS << ")";
903 return;
904 } else if (Arg->getName() == "frameidx") {
905 if (!PrintArg) P->error("Cannot define a new frameidx value!");
906 OS << ".addFrameIndex(" << NameVar << ")";
907 return;
908 } else if (Arg->getName() == "basicblock") {
909 if (!PrintArg) P->error("Cannot define a new basicblock value!");
910 OS << ".addMBB(" << NameVar << ")";
911 return;
912 }
913 P->error("Unknown operand type '" + Arg->getName() + "' to expander!");
914 } else if (IntInit *II = dynamic_cast<IntInit*>(Arg)) {
915 if (!NameVar.empty())
916 P->error("Illegal to specify a name for a constant initializer arg!");
917
918 // Hack this check to allow R32 values with 0 as the initializer for memory
919 // references... FIXME!
920 if (ArgDeclNode->isLeaf() && II->getValue() == 0 &&
921 ArgDeclNode->getValueRecord()->getName() == "R32") {
922 OS << ".addReg(0)";
923 } else {
924 if (ArgDeclNode->isLeaf() || ArgDeclNode->getOperator()->getName()!="imm")
925 P->error("Illegal immediate int value '" + itostr(II->getValue()) +
926 "' operand!");
927 OS << ".addZImm(" << II->getValue() << ")";
928 }
929 return;
930 }
931 P->error("Unknown operand type to expander!");
932}
933
934static std::string getArgName(Pattern *P, const std::string &ArgName,
935 const std::vector<std::pair<TreePatternNode*, std::string> > &Operands) {
936 assert(P->getNumArgs() == Operands.size() &&"Argument computation mismatch!");
937 if (ArgName.empty()) return "";
938
939 for (unsigned i = 0, e = P->getNumArgs(); i != e; ++i)
940 if (P->getArgName(i) == ArgName)
941 return Operands[i].second + "->Val";
942
943 if (ArgName == P->getResultName())
944 return "NewReg";
945 P->error("Pattern does not define a value named $" + ArgName + "!");
946 return "";
947}
948
949
950void InstrSelectorEmitter::run(std::ostream &OS) {
951 // Type-check all of the node types to ensure we "understand" them.
952 ReadNodeTypes();
953
954 // Read in all of the nonterminals, instructions, and expanders...
955 ReadNonterminals();
956 ReadInstructionPatterns();
957 ReadExpanderPatterns();
958
959 // Instantiate any unresolved nonterminals with information from the context
960 // that they are used in.
961 InstantiateNonterminals();
962
963 // Clear InstantiatedNTs, we don't need it anymore...
964 InstantiatedNTs.clear();
965
966 DEBUG(std::cerr << "Patterns acquired:\n");
967 for (std::map<Record*, Pattern*>::iterator I = Patterns.begin(),
968 E = Patterns.end(); I != E; ++I)
969 if (I->second->isResolved())
970 DEBUG(std::cerr << " " << *I->second << "\n");
971
972 CalculateComputableValues();
973
974 EmitSourceFileHeader("Instruction Selector for the " + Target.getName() +
975 " target", OS);
976 OS << "#include \"llvm/CodeGen/MachineInstrBuilder.h\"\n";
977
978 // Output the slot number enums...
979 OS << "\nenum { // Slot numbers...\n"
980 << " LastBuiltinSlot = ISD::NumBuiltinSlots-1, // Start numbering here\n";
981 for (PatternOrganizer::iterator I = ComputableValues.begin(),
982 E = ComputableValues.end(); I != E; ++I)
983 OS << " " << I->first << "_Slot,\n";
984 OS << " NumSlots\n};\n\n// Reduction value typedefs...\n";
985
986 // Output the reduction value typedefs...
987 for (PatternOrganizer::iterator I = ComputableValues.begin(),
988 E = ComputableValues.end(); I != E; ++I) {
989
990 OS << "typedef ReducedValue<unsigned, " << I->first
991 << "_Slot> ReducedValue_" << I->first << ";\n";
992 }
993
994 // Output the pattern enums...
995 OS << "\n\n"
996 << "enum { // Patterns...\n"
997 << " NotComputed = 0,\n"
998 << " NoMatchPattern, \n";
999 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1000 E = ComputableValues.end(); I != E; ++I) {
1001 OS << " // " << I->first << " patterns...\n";
1002 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1003 E = I->second.end(); J != E; ++J)
1004 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1005 OS << " " << J->second[i]->getRecord()->getName() << "_Pattern,\n";
1006 }
1007 OS << "};\n\n";
1008
1009 //===--------------------------------------------------------------------===//
1010 // Emit the class definition...
1011 //
1012 OS << "namespace {\n"
1013 << " class " << Target.getName() << "ISel {\n"
1014 << " SelectionDAG &DAG;\n"
1015 << " public:\n"
1016 << " X86ISel(SelectionDAG &D) : DAG(D) {}\n"
1017 << " void generateCode();\n"
1018 << " private:\n"
1019 << " unsigned makeAnotherReg(const TargetRegisterClass *RC) {\n"
1020 << " return DAG.getMachineFunction().getSSARegMap()->createVirt"
1021 "ualRegister(RC);\n"
1022 << " }\n\n"
1023 << " // DAG matching methods for classes... all of these methods"
1024 " return the cost\n"
1025 << " // of producing a value of the specified class and type, which"
1026 " also gets\n"
1027 << " // added to the DAG node.\n";
1028
1029 // Output all of the matching prototypes for slots...
1030 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1031 E = ComputableValues.end(); I != E; ++I)
1032 OS << " unsigned Match_" << I->first << "(SelectionDAGNode *N);\n";
1033 OS << "\n // DAG matching methods for DAG nodes...\n";
1034
1035 // Output all of the matching prototypes for slot/node pairs
1036 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1037 E = ComputableValues.end(); I != E; ++I)
1038 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1039 E = I->second.end(); J != E; ++J)
1040 OS << " unsigned Match_" << I->first << "_" << getNodeName(J->first)
1041 << "(SelectionDAGNode *N);\n";
1042
1043 // Output all of the dag reduction methods prototypes...
1044 OS << "\n // DAG reduction methods...\n";
1045 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1046 E = ComputableValues.end(); I != E; ++I)
1047 OS << " ReducedValue_" << I->first << " *Reduce_" << I->first
1048 << "(SelectionDAGNode *N,\n" << std::string(27+2*I->first.size(), ' ')
1049 << "MachineBasicBlock *MBB);\n";
1050 OS << " };\n}\n\n";
1051
1052 // Emit the generateCode entry-point...
1053 OS << "void X86ISel::generateCode() {\n"
1054 << " SelectionDAGNode *Root = DAG.getRoot();\n"
1055 << " assert(Root->getValueType() == MVT::isVoid && "
1056 "\"Root of DAG produces value??\");\n\n"
1057 << " std::cerr << \"\\n\";\n"
1058 << " unsigned Cost = Match_Void_void(Root);\n"
1059 << " if (Cost >= ~0U >> 1) {\n"
1060 << " std::cerr << \"Match failed!\\n\";\n"
1061 << " Root->dump();\n"
1062 << " abort();\n"
1063 << " }\n\n"
1064 << " std::cerr << \"Total DAG Cost: \" << Cost << \"\\n\\n\";\n\n"
1065 << " Reduce_Void_void(Root, 0);\n"
1066 << "}\n\n"
1067 << "//===" << std::string(70, '-') << "===//\n"
1068 << "// Matching methods...\n"
1069 << "//\n\n";
1070
1071 //===--------------------------------------------------------------------===//
1072 // Emit all of the matcher methods...
1073 //
1074 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1075 E = ComputableValues.end(); I != E; ++I) {
1076 const std::string &SlotName = I->first;
1077 OS << "unsigned " << Target.getName() << "ISel::Match_" << SlotName
1078 << "(SelectionDAGNode *N) {\n"
1079 << " assert(N->getValueType() == MVT::"
1080 << getEnumName((*I->second.begin()).second[0]->getTree()->getType())
1081 << ");\n" << " // If we already have a cost available for " << SlotName
1082 << " use it!\n"
1083 << " if (N->getPatternFor(" << SlotName << "_Slot))\n"
1084 << " return N->getCostFor(" << SlotName << "_Slot);\n\n"
1085 << " unsigned Cost;\n"
1086 << " switch (N->getNodeType()) {\n"
1087 << " default: Cost = ~0U >> 1; // Match failed\n"
1088 << " N->setPatternCostFor(" << SlotName << "_Slot, NoMatchPattern, Cost, NumSlots);\n"
1089 << " break;\n";
1090
1091 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1092 E = I->second.end(); J != E; ++J)
1093 if (!J->first->isSubClassOf("Nonterminal"))
1094 OS << " case ISD::" << getNodeName(J->first) << ":\tCost = Match_"
1095 << SlotName << "_" << getNodeName(J->first) << "(N); break;\n";
1096 OS << " }\n"; // End of the switch statement
1097
1098 // Emit any patterns which have a nonterminal leaf as the RHS. These may
1099 // match multiple root nodes, so they cannot be handled with the switch...
1100 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1101 E = I->second.end(); J != E; ++J)
1102 if (J->first->isSubClassOf("Nonterminal")) {
1103 OS << " unsigned " << J->first->getName() << "_Cost = Match_"
1104 << getNodeName(J->first) << "(N);\n"
1105 << " if (" << getNodeName(J->first) << "_Cost < Cost) Cost = "
1106 << getNodeName(J->first) << "_Cost;\n";
1107 }
1108
1109 OS << " return Cost;\n}\n\n";
1110
1111 for (PatternOrganizer::NodesForSlot::iterator J = I->second.begin(),
1112 E = I->second.end(); J != E; ++J) {
1113 Record *Operator = J->first;
1114 bool isNonterm = Operator->isSubClassOf("Nonterminal");
1115 if (!isNonterm) {
1116 OS << "unsigned " << Target.getName() << "ISel::Match_";
1117 if (!isNonterm) OS << SlotName << "_";
1118 OS << getNodeName(Operator) << "(SelectionDAGNode *N) {\n"
1119 << " unsigned Pattern = NoMatchPattern;\n"
1120 << " unsigned MinCost = ~0U >> 1;\n";
1121
1122 std::vector<std::pair<Pattern*, TreePatternNode*> > Patterns;
1123 for (unsigned i = 0, e = J->second.size(); i != e; ++i)
1124 Patterns.push_back(std::make_pair(J->second[i],
1125 J->second[i]->getTree()));
1126 EmitMatchCosters(OS, Patterns, "N", 2);
1127
1128 OS << "\n N->setPatternCostFor(" << SlotName
1129 << "_Slot, Pattern, MinCost, NumSlots);\n"
1130 << " return MinCost;\n"
1131 << "}\n";
1132 }
1133 }
1134 }
1135
1136 //===--------------------------------------------------------------------===//
1137 // Emit all of the reducer methods...
1138 //
1139 OS << "\n\n//===" << std::string(70, '-') << "===//\n"
1140 << "// Reducer methods...\n"
1141 << "//\n";
1142
1143 for (PatternOrganizer::iterator I = ComputableValues.begin(),
1144 E = ComputableValues.end(); I != E; ++I) {
1145 const std::string &SlotName = I->first;
1146 OS << "ReducedValue_" << SlotName << " *" << Target.getName()
1147 << "ISel::Reduce_" << SlotName
1148 << "(SelectionDAGNode *N, MachineBasicBlock *MBB) {\n"
1149 << " ReducedValue_" << SlotName << " *Val = N->hasValue<ReducedValue_"
1150 << SlotName << ">(" << SlotName << "_Slot);\n"
1151 << " if (Val) return Val;\n"
1152 << " if (N->getBB()) MBB = N->getBB();\n\n"
1153 << " switch (N->getPatternFor(" << SlotName << "_Slot)) {\n";
1154
1155 // Loop over all of the patterns that can produce a value for this slot...
1156 PatternOrganizer::NodesForSlot &NodesForSlot = I->second;
1157 for (PatternOrganizer::NodesForSlot::iterator J = NodesForSlot.begin(),
1158 E = NodesForSlot.end(); J != E; ++J)
1159 for (unsigned i = 0, e = J->second.size(); i != e; ++i) {
1160 Pattern *P = J->second[i];
1161 OS << " case " << P->getRecord()->getName() << "_Pattern: {\n"
1162 << " // " << *P << "\n";
1163 // Loop over the operands, reducing them...
1164 std::vector<std::pair<TreePatternNode*, std::string> > Operands;
1165 ReduceAllOperands(P->getTree(), "N", Operands, OS);
1166
1167 // Now that we have reduced all of our operands, and have the values
1168 // that reduction produces, perform the reduction action for this
1169 // pattern.
1170 std::string Result;
1171
1172 // If the pattern produces a register result, generate a new register
1173 // now.
1174 if (Record *R = P->getResult()) {
1175 assert(R->isSubClassOf("RegisterClass") &&
1176 "Only handle register class results so far!");
1177 OS << " unsigned NewReg = makeAnotherReg(" << Target.getName()
1178 << "::" << R->getName() << "RegisterClass);\n";
1179 Result = "NewReg";
1180 DEBUG(OS << " std::cerr << \"%reg\" << NewReg << \" =\t\";\n");
1181 } else {
1182 DEBUG(OS << " std::cerr << \"\t\t\";\n");
1183 Result = "0";
1184 }
1185
1186 // Print out the pattern that matched...
1187 DEBUG(OS << " std::cerr << \" " << P->getRecord()->getName() <<'"');
1188 DEBUG(for (unsigned i = 0, e = Operands.size(); i != e; ++i)
1189 if (Operands[i].first->isLeaf()) {
1190 Record *RV = Operands[i].first->getValueRecord();
1191 assert(RV->isSubClassOf("RegisterClass") &&
1192 "Only handles registers here so far!");
1193 OS << " << \" %reg\" << " << Operands[i].second
1194 << "->Val";
1195 } else {
1196 OS << " << ' ' << " << Operands[i].second
1197 << "->Val";
1198 });
1199 DEBUG(OS << " << \"\\n\";\n");
1200
1201 // Generate the reduction code appropriate to the particular type of
1202 // pattern that this is...
1203 switch (P->getPatternType()) {
1204 case Pattern::Instruction:
1205 // Instruction patterns just emit a single MachineInstr, using BuildMI
1206 OS << " BuildMI(MBB, " << Target.getName() << "::"
1207 << P->getRecord()->getName() << ", " << Operands.size();
1208 if (P->getResult()) OS << ", NewReg";
1209 OS << ")";
1210
1211 for (unsigned i = 0, e = Operands.size(); i != e; ++i) {
1212 TreePatternNode *Op = Operands[i].first;
1213 if (Op->isLeaf()) {
1214 Record *RV = Op->getValueRecord();
1215 assert(RV->isSubClassOf("RegisterClass") &&
1216 "Only handles registers here so far!");
1217 OS << ".addReg(" << Operands[i].second << "->Val)";
1218 } else if (Op->getOperator()->getName() == "imm") {
1219 OS << ".addZImm(" << Operands[i].second << "->Val)";
1220 } else if (Op->getOperator()->getName() == "basicblock") {
1221 OS << ".addMBB(" << Operands[i].second << "->Val)";
1222 } else {
1223 assert(0 && "Unknown value type!");
1224 }
1225 }
1226 OS << ";\n";
1227 break;
1228 case Pattern::Expander: {
1229 // Expander patterns emit one machine instr for each instruction in
1230 // the list of instructions expanded to.
1231 ListInit *Insts = P->getRecord()->getValueAsListInit("Result");
1232 for (unsigned IN = 0, e = Insts->getSize(); IN != e; ++IN) {
1233 DagInit *DIInst = dynamic_cast<DagInit*>(Insts->getElement(IN));
1234 if (!DIInst) P->error("Result list must contain instructions!");
1235 Record *InstRec = DIInst->getNodeType();
1236 Pattern *InstPat = getPattern(InstRec);
1237 if (!InstPat || InstPat->getPatternType() != Pattern::Instruction)
1238 P->error("Instruction list must contain Instruction patterns!");
1239
1240 bool hasResult = InstPat->getResult() != 0;
1241 if (InstPat->getNumArgs() != DIInst->getNumArgs()-hasResult) {
1242 P->error("Incorrect number of arguments specified for inst '" +
1243 InstPat->getRecord()->getName() + "' in result list!");
1244 }
1245
1246 // Start emission of the instruction...
1247 OS << " BuildMI(MBB, " << Target.getName() << "::"
1248 << InstRec->getName() << ", "
1249 << DIInst->getNumArgs()-hasResult;
1250 // Emit register result if necessary..
1251 if (hasResult) {
1252 std::string ArgNameVal =
1253 getArgName(P, DIInst->getArgName(0), Operands);
1254 PrintExpanderOperand(DIInst->getArg(0), ArgNameVal,
1255 InstPat->getResultNode(), P, false,
1256 OS << ", ");
1257 }
1258 OS << ")";
1259
1260 for (unsigned i = hasResult, e = DIInst->getNumArgs(); i != e; ++i){
1261 std::string ArgNameVal =
1262 getArgName(P, DIInst->getArgName(i), Operands);
1263
1264 PrintExpanderOperand(DIInst->getArg(i), ArgNameVal,
1265 InstPat->getArg(i-hasResult), P, true, OS);
1266 }
1267
1268 OS << ";\n";
1269 }
1270 break;
1271 }
1272 default:
1273 assert(0 && "Reduction of this type of pattern not implemented!");
1274 }
1275
1276 OS << " Val = new ReducedValue_" << SlotName << "(" << Result<<");\n"
1277 << " break;\n"
1278 << " }\n";
1279 }
1280
1281
1282 OS << " default: assert(0 && \"Unknown " << SlotName << " pattern!\");\n"
1283 << " }\n\n N->addValue(Val); // Do not ever recalculate this\n"
1284 << " return Val;\n}\n\n";
1285 }
1286}
1287