88c1a66d4f1934a30e2a1847fb69d6277235ea66
[oota-llvm.git] / include / llvm / CodeGen / DAGISelHeader.h
1 //==-llvm/CodeGen/DAGISelHeader.h - Common DAG ISel definitions  -*- C++ -*-==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file provides definitions of the common, target-independent methods and 
11 // data, which is used by SelectionDAG-based instruction selectors.
12 //
13 // *** NOTE: This file is #included into the middle of the target
14 // instruction selector class.  These functions are really methods.
15 // This is a little awkward, but it allows this code to be shared
16 // by all the targets while still being able to call into
17 // target-specific code without using a virtual function call.
18 //
19 //===----------------------------------------------------------------------===//
20
21 #ifndef LLVM_CODEGEN_DAGISEL_HEADER_H
22 #define LLVM_CODEGEN_DAGISEL_HEADER_H
23
24 /// ISelPosition - Node iterator marking the current position of
25 /// instruction selection as it procedes through the topologically-sorted
26 /// node list.
27 SelectionDAG::allnodes_iterator ISelPosition;
28
29 /// ChainNotReachable - Returns true if Chain does not reach Op.
30 static bool ChainNotReachable(SDNode *Chain, SDNode *Op) {
31   if (Chain->getOpcode() == ISD::EntryToken)
32     return true;
33   if (Chain->getOpcode() == ISD::TokenFactor)
34     return false;
35   if (Chain->getNumOperands() > 0) {
36     SDValue C0 = Chain->getOperand(0);
37     if (C0.getValueType() == MVT::Other)
38       return C0.getNode() != Op && ChainNotReachable(C0.getNode(), Op);
39   }
40   return true;
41 }
42
43 /// IsChainCompatible - Returns true if Chain is Op or Chain does not reach Op.
44 /// This is used to ensure that there are no nodes trapped between Chain, which
45 /// is the first chain node discovered in a pattern and Op, a later node, that
46 /// will not be selected into the pattern.
47 static bool IsChainCompatible(SDNode *Chain, SDNode *Op) {
48   return Chain == Op || ChainNotReachable(Chain, Op);
49 }
50
51
52 /// ISelUpdater - helper class to handle updates of the 
53 /// instruciton selection graph.
54 class VISIBILITY_HIDDEN ISelUpdater : public SelectionDAG::DAGUpdateListener {
55   SelectionDAG::allnodes_iterator &ISelPosition;
56 public:
57   explicit ISelUpdater(SelectionDAG::allnodes_iterator &isp)
58     : ISelPosition(isp) {}
59   
60   /// NodeDeleted - Handle nodes deleted from the graph. If the
61   /// node being deleted is the current ISelPosition node, update
62   /// ISelPosition.
63   ///
64   virtual void NodeDeleted(SDNode *N, SDNode *E) {
65     if (ISelPosition == SelectionDAG::allnodes_iterator(N))
66       ++ISelPosition;
67   }
68
69   /// NodeUpdated - Ignore updates for now.
70   virtual void NodeUpdated(SDNode *N) {}
71 };
72
73 /// ReplaceUses - replace all uses of the old node F with the use
74 /// of the new node T.
75 DISABLE_INLINE void ReplaceUses(SDValue F, SDValue T) {
76   ISelUpdater ISU(ISelPosition);
77   CurDAG->ReplaceAllUsesOfValueWith(F, T, &ISU);
78 }
79
80 /// ReplaceUses - replace all uses of the old nodes F with the use
81 /// of the new nodes T.
82 DISABLE_INLINE void ReplaceUses(const SDValue *F, const SDValue *T,
83                                 unsigned Num) {
84   ISelUpdater ISU(ISelPosition);
85   CurDAG->ReplaceAllUsesOfValuesWith(F, T, Num, &ISU);
86 }
87
88 /// ReplaceUses - replace all uses of the old node F with the use
89 /// of the new node T.
90 DISABLE_INLINE void ReplaceUses(SDNode *F, SDNode *T) {
91   ISelUpdater ISU(ISelPosition);
92   CurDAG->ReplaceAllUsesWith(F, T, &ISU);
93 }
94
95 /// SelectRoot - Top level entry to DAG instruction selector.
96 /// Selects instructions starting at the root of the current DAG.
97 void SelectRoot(SelectionDAG &DAG) {
98   SelectRootInit();
99
100   // Create a dummy node (which is not added to allnodes), that adds
101   // a reference to the root node, preventing it from being deleted,
102   // and tracking any changes of the root.
103   HandleSDNode Dummy(CurDAG->getRoot());
104   ISelPosition = SelectionDAG::allnodes_iterator(CurDAG->getRoot().getNode());
105   ++ISelPosition;
106
107   // The AllNodes list is now topological-sorted. Visit the
108   // nodes by starting at the end of the list (the root of the
109   // graph) and preceding back toward the beginning (the entry
110   // node).
111   while (ISelPosition != CurDAG->allnodes_begin()) {
112     SDNode *Node = --ISelPosition;
113     // Skip dead nodes. DAGCombiner is expected to eliminate all dead nodes,
114     // but there are currently some corner cases that it misses. Also, this
115     // makes it theoretically possible to disable the DAGCombiner.
116     if (Node->use_empty())
117       continue;
118
119     SDNode *ResNode = Select(Node);
120     // If node should not be replaced, continue with the next one.
121     if (ResNode == Node)
122       continue;
123     // Replace node.
124     if (ResNode)
125       ReplaceUses(Node, ResNode);
126
127     // If after the replacement this node is not used any more,
128     // remove this dead node.
129     if (Node->use_empty()) { // Don't delete EntryToken, etc.
130       ISelUpdater ISU(ISelPosition);
131       CurDAG->RemoveDeadNode(Node, &ISU);
132     }
133   }
134
135   CurDAG->setRoot(Dummy.getValue());
136 }
137
138
139 /// CheckInteger - Return true if the specified node is not a ConstantSDNode or
140 /// if it doesn't have the specified value.
141 static bool CheckInteger(SDValue V, int64_t Val) {
142   ConstantSDNode *C = dyn_cast<ConstantSDNode>(V);
143   return C == 0 || C->getSExtValue() != Val;
144 }
145
146 /// CheckAndImmediate - Check to see if the specified node is an and with an
147 /// immediate returning true on failure.
148 ///
149 /// FIXME: Inline this gunk into CheckAndMask.
150 bool CheckAndImmediate(SDValue V, int64_t Val) {
151   if (V->getOpcode() == ISD::AND)
152     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(V->getOperand(1)))
153       if (CheckAndMask(V.getOperand(0), C, Val))
154         return false;
155   return true;
156 }
157
158 /// CheckOrImmediate - Check to see if the specified node is an or with an
159 /// immediate returning true on failure.
160 ///
161 /// FIXME: Inline this gunk into CheckOrMask.
162 bool CheckOrImmediate(SDValue V, int64_t Val) {
163   if (V->getOpcode() == ISD::OR)
164     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(V->getOperand(1)))
165       if (CheckOrMask(V.getOperand(0), C, Val))
166         return false;
167   return true;
168 }
169
170 void EmitInteger(int64_t Val, MVT::SimpleValueType VT,
171                  SmallVectorImpl<SDValue> &RecordedNodes) {
172   RecordedNodes.push_back(CurDAG->getTargetConstant(Val, VT));
173 }
174
175 // These functions are marked always inline so that Idx doesn't get pinned to
176 // the stack.
177 ALWAYS_INLINE static int8_t
178 GetInt1(const unsigned char *MatcherTable, unsigned &Idx) {
179   return MatcherTable[Idx++];
180 }
181
182 ALWAYS_INLINE static int16_t
183 GetInt2(const unsigned char *MatcherTable, unsigned &Idx) {
184   int16_t Val = (uint8_t)GetInt1(MatcherTable, Idx);
185   Val |= int16_t(GetInt1(MatcherTable, Idx)) << 8;
186   return Val;
187 }
188
189 ALWAYS_INLINE static int32_t
190 GetInt4(const unsigned char *MatcherTable, unsigned &Idx) {
191   int32_t Val = (uint16_t)GetInt2(MatcherTable, Idx);
192   Val |= int32_t(GetInt2(MatcherTable, Idx)) << 16;
193   return Val;
194 }
195
196 ALWAYS_INLINE static int64_t
197 GetInt8(const unsigned char *MatcherTable, unsigned &Idx) {
198   int64_t Val = (uint32_t)GetInt4(MatcherTable, Idx);
199   Val |= int64_t(GetInt4(MatcherTable, Idx)) << 32;
200   return Val;
201 }
202
203 /// GetVBR - decode a vbr encoding whose top bit is set.
204 ALWAYS_INLINE static unsigned
205 GetVBR(unsigned Val, const unsigned char *MatcherTable, unsigned &Idx) {
206   assert(Val >= 128 && "Not a VBR");
207   Val &= 127;  // Remove first vbr bit.
208   
209   unsigned Shift = 7;
210   unsigned NextBits;
211   do {
212     NextBits = GetInt1(MatcherTable, Idx);
213     Val |= (NextBits&127) << Shift;
214     Shift += 7;
215   } while (NextBits & 128);
216   
217   return Val;
218 }
219
220
221 enum BuiltinOpcodes {
222   OPC_Push, OPC_Push2,
223   OPC_RecordNode,
224   OPC_RecordChild0, OPC_RecordChild1, OPC_RecordChild2, OPC_RecordChild3, 
225   OPC_RecordChild4, OPC_RecordChild5, OPC_RecordChild6, OPC_RecordChild7,
226   OPC_RecordMemRef,
227   OPC_CaptureFlagInput,
228   OPC_MoveChild,
229   OPC_MoveParent,
230   OPC_CheckSame,
231   OPC_CheckPatternPredicate,
232   OPC_CheckPredicate,
233   OPC_CheckOpcode,
234   OPC_CheckMultiOpcode,
235   OPC_CheckType,
236   OPC_CheckInteger1, OPC_CheckInteger2, OPC_CheckInteger4, OPC_CheckInteger8,
237   OPC_CheckCondCode,
238   OPC_CheckValueType,
239   OPC_CheckComplexPat,
240   OPC_CheckAndImm1, OPC_CheckAndImm2, OPC_CheckAndImm4, OPC_CheckAndImm8,
241   OPC_CheckOrImm1, OPC_CheckOrImm2, OPC_CheckOrImm4, OPC_CheckOrImm8,
242   OPC_CheckFoldableChainNode,
243   OPC_CheckChainCompatible,
244   
245   OPC_EmitInteger1, OPC_EmitInteger2, OPC_EmitInteger4, OPC_EmitInteger8,
246   OPC_EmitRegister,
247   OPC_EmitConvertToTarget,
248   OPC_EmitMergeInputChains,
249   OPC_EmitCopyToReg,
250   OPC_EmitNodeXForm,
251   OPC_EmitNode,
252   OPC_MarkFlagResults,
253   OPC_CompleteMatch
254 };
255
256 enum {
257   OPFL_None      = 0,     // Node has no chain or flag input and isn't variadic.
258   OPFL_Chain     = 1,     // Node has a chain input.
259   OPFL_Flag      = 2,     // Node has a flag input.
260   OPFL_MemRefs   = 4,     // Node gets accumulated MemRefs.
261   OPFL_Variadic0 = 1<<3,  // Node is variadic, root has 0 fixed inputs.
262   OPFL_Variadic1 = 2<<3,  // Node is variadic, root has 1 fixed inputs.
263   OPFL_Variadic2 = 3<<3,  // Node is variadic, root has 2 fixed inputs.
264   OPFL_Variadic3 = 4<<3,  // Node is variadic, root has 3 fixed inputs.
265   OPFL_Variadic4 = 5<<3,  // Node is variadic, root has 4 fixed inputs.
266   OPFL_Variadic5 = 6<<3,  // Node is variadic, root has 5 fixed inputs.
267   OPFL_Variadic6 = 7<<3,  // Node is variadic, root has 6 fixed inputs.
268   
269   OPFL_VariadicInfo = OPFL_Variadic6
270 };
271
272 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
273 /// number of fixed arity values that should be skipped when copying from the
274 /// root.
275 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
276   return ((Flags&OPFL_VariadicInfo) >> 3)-1;
277 }
278
279 struct MatchScope {
280   /// FailIndex - If this match fails, this is the index to continue with.
281   unsigned FailIndex;
282   
283   /// NodeStackSize - The size of the node stack when the scope was formed.
284   unsigned NodeStackSize;
285   
286   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
287   unsigned NumRecordedNodes;
288   
289   /// NumMatchedMemRefs - The number of matched memref entries.
290   unsigned NumMatchedMemRefs;
291   
292   /// InputChain/InputFlag - The current chain/flag 
293   SDValue InputChain, InputFlag;
294
295   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
296   bool HasChainNodesMatched, HasFlagResultNodesMatched;
297 };
298
299 SDNode *SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
300                          unsigned TableSize) {
301   // FIXME: Should these even be selected?  Handle these cases in the caller?
302   switch (NodeToMatch->getOpcode()) {
303   default:
304     break;
305   case ISD::EntryToken:       // These nodes remain the same.
306   case ISD::BasicBlock:
307   case ISD::Register:
308   case ISD::HANDLENODE:
309   case ISD::TargetConstant:
310   case ISD::TargetConstantFP:
311   case ISD::TargetConstantPool:
312   case ISD::TargetFrameIndex:
313   case ISD::TargetExternalSymbol:
314   case ISD::TargetBlockAddress:
315   case ISD::TargetJumpTable:
316   case ISD::TargetGlobalTLSAddress:
317   case ISD::TargetGlobalAddress:
318   case ISD::TokenFactor:
319   case ISD::CopyFromReg:
320   case ISD::CopyToReg:
321     return 0;
322   case ISD::AssertSext:
323   case ISD::AssertZext:
324     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
325     return 0;
326   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
327   case ISD::EH_LABEL:  return Select_EH_LABEL(NodeToMatch);
328   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
329   }
330   
331   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
332
333   // Set up the node stack with NodeToMatch as the only node on the stack.
334   SmallVector<SDValue, 8> NodeStack;
335   SDValue N = SDValue(NodeToMatch, 0);
336   NodeStack.push_back(N);
337
338   // MatchScopes - Scopes used when matching, if a match failure happens, this
339   // indicates where to continue checking.
340   SmallVector<MatchScope, 8> MatchScopes;
341   
342   // RecordedNodes - This is the set of nodes that have been recorded by the
343   // state machine.
344   SmallVector<SDValue, 8> RecordedNodes;
345   
346   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
347   // pattern.
348   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
349   
350   // These are the current input chain and flag for use when generating nodes.
351   // Various Emit operations change these.  For example, emitting a copytoreg
352   // uses and updates these.
353   SDValue InputChain, InputFlag;
354   
355   // ChainNodesMatched - If a pattern matches nodes that have input/output
356   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
357   // which ones they are.  The result is captured into this list so that we can
358   // update the chain results when the pattern is complete.
359   SmallVector<SDNode*, 3> ChainNodesMatched;
360   SmallVector<SDNode*, 3> FlagResultNodesMatched;
361   
362   DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
363         NodeToMatch->dump(CurDAG);
364         errs() << '\n');
365   
366   // Interpreter starts at opcode #0.
367   unsigned MatcherIndex = 0;
368   while (1) {
369     assert(MatcherIndex < TableSize && "Invalid index");
370     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
371     switch (Opcode) {
372     case OPC_Push: {
373       unsigned NumToSkip = MatcherTable[MatcherIndex++];
374       MatchScope NewEntry;
375       NewEntry.FailIndex = MatcherIndex+NumToSkip;
376       NewEntry.NodeStackSize = NodeStack.size();
377       NewEntry.NumRecordedNodes = RecordedNodes.size();
378       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
379       NewEntry.InputChain = InputChain;
380       NewEntry.InputFlag = InputFlag;
381       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
382       NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
383       MatchScopes.push_back(NewEntry);
384       continue;
385     }
386     case OPC_Push2: {
387       unsigned NumToSkip = GetInt2(MatcherTable, MatcherIndex);
388       MatchScope NewEntry;
389       NewEntry.FailIndex = MatcherIndex+NumToSkip;
390       NewEntry.NodeStackSize = NodeStack.size();
391       NewEntry.NumRecordedNodes = RecordedNodes.size();
392       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
393       NewEntry.InputChain = InputChain;
394       NewEntry.InputFlag = InputFlag;
395       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
396       NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
397       MatchScopes.push_back(NewEntry);
398       continue;
399     }
400     case OPC_RecordNode:
401       // Remember this node, it may end up being an operand in the pattern.
402       RecordedNodes.push_back(N);
403       continue;
404         
405     case OPC_RecordChild0: case OPC_RecordChild1:
406     case OPC_RecordChild2: case OPC_RecordChild3:
407     case OPC_RecordChild4: case OPC_RecordChild5:
408     case OPC_RecordChild6: case OPC_RecordChild7: {
409       unsigned ChildNo = Opcode-OPC_RecordChild0;
410       if (ChildNo >= N.getNumOperands())
411         break;  // Match fails if out of range child #.
412
413       RecordedNodes.push_back(N->getOperand(ChildNo));
414       continue;
415     }
416     case OPC_RecordMemRef:
417       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
418       continue;
419         
420     case OPC_CaptureFlagInput:
421       // If the current node has an input flag, capture it in InputFlag.
422       if (N->getNumOperands() != 0 &&
423           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
424         InputFlag = N->getOperand(N->getNumOperands()-1);
425       continue;
426         
427     case OPC_MoveChild: {
428       unsigned ChildNo = MatcherTable[MatcherIndex++];
429       if (ChildNo >= N.getNumOperands())
430         break;  // Match fails if out of range child #.
431       N = N.getOperand(ChildNo);
432       NodeStack.push_back(N);
433       continue;
434     }
435         
436     case OPC_MoveParent:
437       // Pop the current node off the NodeStack.
438       NodeStack.pop_back();
439       assert(!NodeStack.empty() && "Node stack imbalance!");
440       N = NodeStack.back();  
441       continue;
442      
443     case OPC_CheckSame: {
444       // Accept if it is exactly the same as a previously recorded node.
445       unsigned RecNo = MatcherTable[MatcherIndex++];
446       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
447       if (N != RecordedNodes[RecNo]) break;
448       continue;
449     }
450     case OPC_CheckPatternPredicate:
451       if (!CheckPatternPredicate(MatcherTable[MatcherIndex++])) break;
452       continue;
453     case OPC_CheckPredicate:
454       if (!CheckNodePredicate(N.getNode(), MatcherTable[MatcherIndex++])) break;
455       continue;
456     case OPC_CheckComplexPat:
457       if (!CheckComplexPattern(NodeToMatch, N, 
458                                MatcherTable[MatcherIndex++], RecordedNodes))
459         break;
460       continue;
461     case OPC_CheckOpcode:
462       if (N->getOpcode() != MatcherTable[MatcherIndex++]) break;
463       continue;
464         
465     case OPC_CheckMultiOpcode: {
466       unsigned NumOps = MatcherTable[MatcherIndex++];
467       bool OpcodeEquals = false;
468       for (unsigned i = 0; i != NumOps; ++i)
469         OpcodeEquals |= N->getOpcode() == MatcherTable[MatcherIndex++];
470       if (!OpcodeEquals) break;
471       continue;
472     }
473         
474     case OPC_CheckType: {
475       MVT::SimpleValueType VT =
476         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
477       if (N.getValueType() != VT) {
478         // Handle the case when VT is iPTR.
479         if (VT != MVT::iPTR || N.getValueType() != TLI.getPointerTy())
480           break;
481       }
482       continue;
483     }
484     case OPC_CheckCondCode:
485       if (cast<CondCodeSDNode>(N)->get() !=
486           (ISD::CondCode)MatcherTable[MatcherIndex++]) break;
487       continue;
488     case OPC_CheckValueType: {
489       MVT::SimpleValueType VT =
490         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
491       if (cast<VTSDNode>(N)->getVT() != VT) {
492         // Handle the case when VT is iPTR.
493         if (VT != MVT::iPTR || cast<VTSDNode>(N)->getVT() != TLI.getPointerTy())
494           break;
495       }
496       continue;
497     }
498     case OPC_CheckInteger1:
499       if (CheckInteger(N, GetInt1(MatcherTable, MatcherIndex))) break;
500       continue;
501     case OPC_CheckInteger2:
502       if (CheckInteger(N, GetInt2(MatcherTable, MatcherIndex))) break;
503       continue;
504     case OPC_CheckInteger4:
505       if (CheckInteger(N, GetInt4(MatcherTable, MatcherIndex))) break;
506       continue;
507     case OPC_CheckInteger8:
508       if (CheckInteger(N, GetInt8(MatcherTable, MatcherIndex))) break;
509       continue;
510         
511     case OPC_CheckAndImm1:
512       if (CheckAndImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
513       continue;
514     case OPC_CheckAndImm2:
515       if (CheckAndImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
516       continue;
517     case OPC_CheckAndImm4:
518       if (CheckAndImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
519       continue;
520     case OPC_CheckAndImm8:
521       if (CheckAndImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
522       continue;
523
524     case OPC_CheckOrImm1:
525       if (CheckOrImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
526       continue;
527     case OPC_CheckOrImm2:
528       if (CheckOrImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
529       continue;
530     case OPC_CheckOrImm4:
531       if (CheckOrImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
532       continue;
533     case OPC_CheckOrImm8:
534       if (CheckOrImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
535       continue;
536         
537     case OPC_CheckFoldableChainNode: {
538       assert(NodeStack.size() != 1 && "No parent node");
539       // Verify that all intermediate nodes between the root and this one have
540       // a single use.
541       bool HasMultipleUses = false;
542       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
543         if (!NodeStack[i].hasOneUse()) {
544           HasMultipleUses = true;
545           break;
546         }
547       if (HasMultipleUses) break;
548
549       // Check to see that the target thinks this is profitable to fold and that
550       // we can fold it without inducing cycles in the graph.
551       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
552                               NodeToMatch) ||
553           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
554                          NodeToMatch))
555         break;
556       
557       continue;
558     }
559     case OPC_CheckChainCompatible: {
560       unsigned PrevNode = MatcherTable[MatcherIndex++];
561       assert(PrevNode < RecordedNodes.size() && "Invalid CheckChainCompatible");
562       SDValue PrevChainedNode = RecordedNodes[PrevNode];
563       SDValue ThisChainedNode = RecordedNodes.back();
564       
565       // We have two nodes with chains, verify that their input chains are good.
566       assert(PrevChainedNode.getOperand(0).getValueType() == MVT::Other &&
567              ThisChainedNode.getOperand(0).getValueType() == MVT::Other &&
568              "Invalid chained nodes");
569       
570       if (!IsChainCompatible(// Input chain of the previous node.
571                              PrevChainedNode.getOperand(0).getNode(),
572                              // Node with chain.
573                              ThisChainedNode.getNode()))
574         break;
575       continue;
576     }
577         
578     case OPC_EmitInteger1: {
579       MVT::SimpleValueType VT =
580         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
581       EmitInteger(GetInt1(MatcherTable, MatcherIndex), VT, RecordedNodes);
582       continue;
583     }
584     case OPC_EmitInteger2: {
585       MVT::SimpleValueType VT =
586         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
587       EmitInteger(GetInt2(MatcherTable, MatcherIndex), VT, RecordedNodes);
588       continue;
589     }
590     case OPC_EmitInteger4: {
591       MVT::SimpleValueType VT =
592         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
593       EmitInteger(GetInt4(MatcherTable, MatcherIndex), VT, RecordedNodes);
594       continue;
595     }
596     case OPC_EmitInteger8: {
597       MVT::SimpleValueType VT =
598        (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
599       EmitInteger(GetInt8(MatcherTable, MatcherIndex), VT, RecordedNodes);
600       continue;
601     }
602         
603     case OPC_EmitRegister: {
604       MVT::SimpleValueType VT =
605         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
606       unsigned RegNo = MatcherTable[MatcherIndex++];
607       RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
608       continue;
609     }
610         
611     case OPC_EmitConvertToTarget:  {
612       // Convert from IMM/FPIMM to target version.
613       unsigned RecNo = MatcherTable[MatcherIndex++];
614       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
615       SDValue Imm = RecordedNodes[RecNo];
616
617       if (Imm->getOpcode() == ISD::Constant) {
618         int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
619         Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
620       } else if (Imm->getOpcode() == ISD::ConstantFP) {
621         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
622         Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
623       }
624       
625       RecordedNodes.push_back(Imm);
626       continue;
627     }
628         
629     case OPC_EmitMergeInputChains: {
630       assert(InputChain.getNode() == 0 &&
631              "EmitMergeInputChains should be the first chain producing node");
632       // This node gets a list of nodes we matched in the input that have
633       // chains.  We want to token factor all of the input chains to these nodes
634       // together.  However, if any of the input chains is actually one of the
635       // nodes matched in this pattern, then we have an intra-match reference.
636       // Ignore these because the newly token factored chain should not refer to
637       // the old nodes.
638       unsigned NumChains = MatcherTable[MatcherIndex++];
639       assert(NumChains != 0 && "Can't TF zero chains");
640
641       assert(ChainNodesMatched.empty() &&
642              "Should only have one EmitMergeInputChains per match");
643
644       // Handle the first chain.
645       unsigned RecNo = MatcherTable[MatcherIndex++];
646       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
647       ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
648       
649       // If the chained node is not the root, we can't fold it if it has
650       // multiple uses.
651       // FIXME: What if other value results of the node have uses not matched by
652       // this pattern?
653       if (ChainNodesMatched.back() != NodeToMatch &&
654           !RecordedNodes[RecNo].hasOneUse()) {
655         ChainNodesMatched.clear();
656         break;
657       }
658       
659       // The common case here is that we have exactly one chain, which is really
660       // cheap to handle, just do it.
661       if (NumChains == 1) {
662         InputChain = RecordedNodes[RecNo].getOperand(0);
663         assert(InputChain.getValueType() == MVT::Other && "Not a chain");
664         continue;
665       }
666       
667       // Read all of the chained nodes.
668       for (unsigned i = 1; i != NumChains; ++i) {
669         RecNo = MatcherTable[MatcherIndex++];
670         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
671         ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
672         
673         // FIXME: What if other value results of the node have uses not matched by
674         // this pattern?
675         if (ChainNodesMatched.back() != NodeToMatch &&
676             !RecordedNodes[RecNo].hasOneUse()) {
677           ChainNodesMatched.clear();
678           break;
679         }
680       }
681
682       // Walk all the chained nodes, adding the input chains if they are not in
683       // ChainedNodes (and this, not in the matched pattern).  This is an N^2
684       // algorithm, but # chains is usually 2 here, at most 3 for MSP430.
685       SmallVector<SDValue, 3> InputChains;
686       for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
687         SDValue InChain = ChainNodesMatched[i]->getOperand(0);
688         assert(InChain.getValueType() == MVT::Other && "Not a chain");
689         bool Invalid = false;
690         for (unsigned j = 0; j != e; ++j)
691           Invalid |= ChainNodesMatched[j] == InChain.getNode();
692         if (!Invalid)
693           InputChains.push_back(InChain);
694       }
695
696       SDValue Res;
697       if (InputChains.size() == 1)
698         InputChain = InputChains[0];
699       else
700         InputChain = CurDAG->getNode(ISD::TokenFactor,
701                                      NodeToMatch->getDebugLoc(), MVT::Other,
702                                      &InputChains[0], InputChains.size());
703       continue;
704     }
705         
706     case OPC_EmitCopyToReg: {
707       unsigned RecNo = MatcherTable[MatcherIndex++];
708       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
709       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
710       
711       if (InputChain.getNode() == 0)
712         InputChain = CurDAG->getEntryNode();
713       
714       InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
715                                         DestPhysReg, RecordedNodes[RecNo],
716                                         InputFlag);
717       
718       InputFlag = InputChain.getValue(1);
719       continue;
720     }
721         
722     case OPC_EmitNodeXForm: {
723       unsigned XFormNo = MatcherTable[MatcherIndex++];
724       unsigned RecNo = MatcherTable[MatcherIndex++];
725       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
726       RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
727       continue;
728     }
729         
730     case OPC_EmitNode: {
731       uint16_t TargetOpc = GetInt2(MatcherTable, MatcherIndex);
732       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
733       // Get the result VT list.
734       unsigned NumVTs = MatcherTable[MatcherIndex++];
735       assert(NumVTs != 0 && "Invalid node result");
736       SmallVector<EVT, 4> VTs;
737       for (unsigned i = 0; i != NumVTs; ++i) {
738         MVT::SimpleValueType VT =
739           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
740         if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
741         VTs.push_back(VT);
742       }
743       
744       // FIXME: Use faster version for the common 'one VT' case?
745       SDVTList VTList = CurDAG->getVTList(VTs.data(), VTs.size());
746
747       // Get the operand list.
748       unsigned NumOps = MatcherTable[MatcherIndex++];
749       SmallVector<SDValue, 8> Ops;
750       for (unsigned i = 0; i != NumOps; ++i) {
751         unsigned RecNo = MatcherTable[MatcherIndex++];
752         if (RecNo & 128)
753           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
754         
755         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
756         Ops.push_back(RecordedNodes[RecNo]);
757       }
758       
759       // If there are variadic operands to add, handle them now.
760       if (EmitNodeInfo & OPFL_VariadicInfo) {
761         // Determine the start index to copy from.
762         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
763         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
764         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
765                "Invalid variadic node");
766         // Copy all of the variadic operands, not including a potential flag
767         // input.
768         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
769              i != e; ++i) {
770           SDValue V = NodeToMatch->getOperand(i);
771           if (V.getValueType() == MVT::Flag) break;
772           Ops.push_back(V);
773         }
774       }
775       
776       // If this has chain/flag inputs, add them.
777       if (EmitNodeInfo & OPFL_Chain)
778         Ops.push_back(InputChain);
779       if ((EmitNodeInfo & OPFL_Flag) && InputFlag.getNode() != 0)
780         Ops.push_back(InputFlag);
781       
782       // Create the node.
783       MachineSDNode *Res = CurDAG->getMachineNode(TargetOpc,
784                                                   NodeToMatch->getDebugLoc(),
785                                                   VTList,
786                                                   Ops.data(), Ops.size());
787       // Add all the non-flag/non-chain results to the RecordedNodes list.
788       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
789         if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
790         RecordedNodes.push_back(SDValue(Res, i));
791       }
792       
793       // If the node had chain/flag results, update our notion of the current
794       // chain and flag.
795       if (VTs.back() == MVT::Flag) {
796         InputFlag = SDValue(Res, VTs.size()-1);
797         if (EmitNodeInfo & OPFL_Chain)
798           InputChain = SDValue(Res, VTs.size()-2);
799       } else if (EmitNodeInfo & OPFL_Chain)
800         InputChain = SDValue(Res, VTs.size()-1);
801
802       // If the OPFL_MemRefs flag is set on this node, slap all of the
803       // accumulated memrefs onto it.
804       //
805       // FIXME: This is vastly incorrect for patterns with multiple outputs
806       // instructions that access memory and for ComplexPatterns that match
807       // loads.
808       if (EmitNodeInfo & OPFL_MemRefs) {
809         MachineSDNode::mmo_iterator MemRefs =
810           MF->allocateMemRefsArray(MatchedMemRefs.size());
811         std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
812         Res->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
813       }
814       
815       DEBUG(errs() << "  Created node: "; Res->dump(CurDAG); errs() << "\n");
816       continue;
817     }
818         
819     case OPC_MarkFlagResults: {
820       unsigned NumNodes = MatcherTable[MatcherIndex++];
821       
822       // Read and remember all the flag-result nodes.
823       for (unsigned i = 0; i != NumNodes; ++i) {
824         unsigned RecNo = MatcherTable[MatcherIndex++];
825         if (RecNo & 128)
826           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
827
828         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
829         FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
830       }
831       continue;
832     }
833       
834     case OPC_CompleteMatch: {
835       // The match has been completed, and any new nodes (if any) have been
836       // created.  Patch up references to the matched dag to use the newly
837       // created nodes.
838       unsigned NumResults = MatcherTable[MatcherIndex++];
839
840       for (unsigned i = 0; i != NumResults; ++i) {
841         unsigned ResSlot = MatcherTable[MatcherIndex++];
842         if (ResSlot & 128)
843           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
844         
845         assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
846         SDValue Res = RecordedNodes[ResSlot];
847         
848         // FIXME2: Eliminate this horrible hack by fixing the 'Gen' program
849         // after (parallel) on input patterns are removed.  This would also
850         // allow us to stop encoding #results in OPC_CompleteMatch's table
851         // entry.
852         if (NodeToMatch->getNumValues() <= i ||
853             NodeToMatch->getValueType(i) == MVT::Other ||
854             NodeToMatch->getValueType(i) == MVT::Flag)
855           break;
856         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
857                 NodeToMatch->getValueType(i) == MVT::iPTR ||
858                 Res.getValueType() == MVT::iPTR ||
859                 NodeToMatch->getValueType(i).getSizeInBits() ==
860                     Res.getValueType().getSizeInBits()) &&
861                "invalid replacement");
862         ReplaceUses(SDValue(NodeToMatch, i), Res);
863       }
864       
865       // Now that all the normal results are replaced, we replace the chain and
866       // flag results if present.
867       if (!ChainNodesMatched.empty()) {
868         assert(InputChain.getNode() != 0 &&
869                "Matched input chains but didn't produce a chain");
870         // Loop over all of the nodes we matched that produced a chain result.
871         // Replace all the chain results with the final chain we ended up with.
872         for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
873           SDNode *ChainNode = ChainNodesMatched[i];
874           SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
875           if (ChainVal.getValueType() == MVT::Flag)
876             ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
877           assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
878           ReplaceUses(ChainVal, InputChain);
879         }
880       }
881
882       // If the result produces a flag, update any flag results in the matched
883       // pattern with the flag result.
884       if (InputFlag.getNode() != 0) {
885         // Handle the root node:
886         if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) ==
887               MVT::Flag)
888           ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues()-1),
889                       InputFlag);
890         
891         // Handle any interior nodes explicitly marked.
892         for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
893           SDNode *FRN = FlagResultNodesMatched[i];
894           assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
895                  "Doesn't have a flag result");
896           ReplaceUses(SDValue(FRN, FRN->getNumValues()-1), InputFlag);
897         }
898       }
899       
900       assert(NodeToMatch->use_empty() &&
901              "Didn't replace all uses of the node?");
902       
903       DEBUG(errs() << "ISEL: Match complete!\n");
904       
905       // FIXME: We just return here, which interacts correctly with SelectRoot
906       // above.  We should fix this to not return an SDNode* anymore.
907       return 0;
908     }
909     }
910     
911     // If the code reached this point, then the match failed pop out to the next
912     // match scope.
913     if (MatchScopes.empty()) {
914       CannotYetSelect(NodeToMatch);
915       return 0;
916     }
917     
918     const MatchScope &LastScope = MatchScopes.back();
919     RecordedNodes.resize(LastScope.NumRecordedNodes);
920     NodeStack.resize(LastScope.NodeStackSize);
921     N = NodeStack.back();
922
923     DEBUG(errs() << "  Match failed at index " << MatcherIndex
924                  << " continuing at " << LastScope.FailIndex << "\n");
925     
926     if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
927       MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
928     MatcherIndex = LastScope.FailIndex;
929     
930     InputChain = LastScope.InputChain;
931     InputFlag = LastScope.InputFlag;
932     if (!LastScope.HasChainNodesMatched)
933       ChainNodesMatched.clear();
934     if (!LastScope.HasFlagResultNodesMatched)
935       FlagResultNodesMatched.clear();
936
937     MatchScopes.pop_back();
938   }
939 }
940     
941
942 #endif /* LLVM_CODEGEN_DAGISEL_HEADER_H */