fix the matcher in the presence of multiple scopes: we need to save
[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_Scope,
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_CheckChild0Type, OPC_CheckChild1Type, OPC_CheckChild2Type,
237   OPC_CheckChild3Type, OPC_CheckChild4Type, OPC_CheckChild5Type,
238   OPC_CheckChild6Type, OPC_CheckChild7Type,
239   OPC_CheckInteger1, OPC_CheckInteger2, OPC_CheckInteger4, OPC_CheckInteger8,
240   OPC_CheckCondCode,
241   OPC_CheckValueType,
242   OPC_CheckComplexPat,
243   OPC_CheckAndImm1, OPC_CheckAndImm2, OPC_CheckAndImm4, OPC_CheckAndImm8,
244   OPC_CheckOrImm1, OPC_CheckOrImm2, OPC_CheckOrImm4, OPC_CheckOrImm8,
245   OPC_CheckFoldableChainNode,
246   OPC_CheckChainCompatible,
247   
248   OPC_EmitInteger1, OPC_EmitInteger2, OPC_EmitInteger4, OPC_EmitInteger8,
249   OPC_EmitRegister,
250   OPC_EmitConvertToTarget,
251   OPC_EmitMergeInputChains,
252   OPC_EmitCopyToReg,
253   OPC_EmitNodeXForm,
254   OPC_EmitNode,
255   OPC_MarkFlagResults,
256   OPC_CompleteMatch
257 };
258
259 enum {
260   OPFL_None      = 0,     // Node has no chain or flag input and isn't variadic.
261   OPFL_Chain     = 1,     // Node has a chain input.
262   OPFL_Flag      = 2,     // Node has a flag input.
263   OPFL_MemRefs   = 4,     // Node gets accumulated MemRefs.
264   OPFL_Variadic0 = 1<<3,  // Node is variadic, root has 0 fixed inputs.
265   OPFL_Variadic1 = 2<<3,  // Node is variadic, root has 1 fixed inputs.
266   OPFL_Variadic2 = 3<<3,  // Node is variadic, root has 2 fixed inputs.
267   OPFL_Variadic3 = 4<<3,  // Node is variadic, root has 3 fixed inputs.
268   OPFL_Variadic4 = 5<<3,  // Node is variadic, root has 4 fixed inputs.
269   OPFL_Variadic5 = 6<<3,  // Node is variadic, root has 5 fixed inputs.
270   OPFL_Variadic6 = 7<<3,  // Node is variadic, root has 6 fixed inputs.
271   
272   OPFL_VariadicInfo = OPFL_Variadic6
273 };
274
275 /// getNumFixedFromVariadicInfo - Transform an EmitNode flags word into the
276 /// number of fixed arity values that should be skipped when copying from the
277 /// root.
278 static inline int getNumFixedFromVariadicInfo(unsigned Flags) {
279   return ((Flags&OPFL_VariadicInfo) >> 3)-1;
280 }
281
282 struct MatchScope {
283   /// FailIndex - If this match fails, this is the index to continue with.
284   unsigned FailIndex;
285   
286   /// NodeStack - The node stack when the scope was formed.
287   SmallVector<SDValue, 4> NodeStack;
288   
289   /// NumRecordedNodes - The number of recorded nodes when the scope was formed.
290   unsigned NumRecordedNodes;
291   
292   /// NumMatchedMemRefs - The number of matched memref entries.
293   unsigned NumMatchedMemRefs;
294   
295   /// InputChain/InputFlag - The current chain/flag 
296   SDValue InputChain, InputFlag;
297
298   /// HasChainNodesMatched - True if the ChainNodesMatched list is non-empty.
299   bool HasChainNodesMatched, HasFlagResultNodesMatched;
300 };
301
302 SDNode *SelectCodeCommon(SDNode *NodeToMatch, const unsigned char *MatcherTable,
303                          unsigned TableSize) {
304   // FIXME: Should these even be selected?  Handle these cases in the caller?
305   switch (NodeToMatch->getOpcode()) {
306   default:
307     break;
308   case ISD::EntryToken:       // These nodes remain the same.
309   case ISD::BasicBlock:
310   case ISD::Register:
311   case ISD::HANDLENODE:
312   case ISD::TargetConstant:
313   case ISD::TargetConstantFP:
314   case ISD::TargetConstantPool:
315   case ISD::TargetFrameIndex:
316   case ISD::TargetExternalSymbol:
317   case ISD::TargetBlockAddress:
318   case ISD::TargetJumpTable:
319   case ISD::TargetGlobalTLSAddress:
320   case ISD::TargetGlobalAddress:
321   case ISD::TokenFactor:
322   case ISD::CopyFromReg:
323   case ISD::CopyToReg:
324     return 0;
325   case ISD::AssertSext:
326   case ISD::AssertZext:
327     ReplaceUses(SDValue(NodeToMatch, 0), NodeToMatch->getOperand(0));
328     return 0;
329   case ISD::INLINEASM: return Select_INLINEASM(NodeToMatch);
330   case ISD::EH_LABEL:  return Select_EH_LABEL(NodeToMatch);
331   case ISD::UNDEF:     return Select_UNDEF(NodeToMatch);
332   }
333   
334   assert(!NodeToMatch->isMachineOpcode() && "Node already selected!");
335
336   // Set up the node stack with NodeToMatch as the only node on the stack.
337   SmallVector<SDValue, 8> NodeStack;
338   SDValue N = SDValue(NodeToMatch, 0);
339   NodeStack.push_back(N);
340
341   // MatchScopes - Scopes used when matching, if a match failure happens, this
342   // indicates where to continue checking.
343   SmallVector<MatchScope, 8> MatchScopes;
344   
345   // RecordedNodes - This is the set of nodes that have been recorded by the
346   // state machine.
347   SmallVector<SDValue, 8> RecordedNodes;
348   
349   // MatchedMemRefs - This is the set of MemRef's we've seen in the input
350   // pattern.
351   SmallVector<MachineMemOperand*, 2> MatchedMemRefs;
352   
353   // These are the current input chain and flag for use when generating nodes.
354   // Various Emit operations change these.  For example, emitting a copytoreg
355   // uses and updates these.
356   SDValue InputChain, InputFlag;
357   
358   // ChainNodesMatched - If a pattern matches nodes that have input/output
359   // chains, the OPC_EmitMergeInputChains operation is emitted which indicates
360   // which ones they are.  The result is captured into this list so that we can
361   // update the chain results when the pattern is complete.
362   SmallVector<SDNode*, 3> ChainNodesMatched;
363   SmallVector<SDNode*, 3> FlagResultNodesMatched;
364   
365   DEBUG(errs() << "ISEL: Starting pattern match on root node: ";
366         NodeToMatch->dump(CurDAG);
367         errs() << '\n');
368   
369   // Interpreter starts at opcode #0.
370   unsigned MatcherIndex = 0;
371   while (1) {
372     assert(MatcherIndex < TableSize && "Invalid index");
373     BuiltinOpcodes Opcode = (BuiltinOpcodes)MatcherTable[MatcherIndex++];
374     switch (Opcode) {
375     case OPC_Scope: {
376       unsigned NumToSkip = MatcherTable[MatcherIndex++];
377       if (NumToSkip & 128)
378         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
379       assert(NumToSkip != 0 &&
380              "First entry of OPC_Scope shouldn't be 0, scope has no children?");
381
382       // Push a MatchScope which indicates where to go if the first child fails
383       // to match.
384       MatchScope NewEntry;
385       NewEntry.FailIndex = MatcherIndex+NumToSkip;
386       NewEntry.NodeStack.append(NodeStack.begin(), NodeStack.end());
387       NewEntry.NumRecordedNodes = RecordedNodes.size();
388       NewEntry.NumMatchedMemRefs = MatchedMemRefs.size();
389       NewEntry.InputChain = InputChain;
390       NewEntry.InputFlag = InputFlag;
391       NewEntry.HasChainNodesMatched = !ChainNodesMatched.empty();
392       NewEntry.HasFlagResultNodesMatched = !FlagResultNodesMatched.empty();
393       MatchScopes.push_back(NewEntry);
394       continue;
395     }
396     case OPC_RecordNode:
397       // Remember this node, it may end up being an operand in the pattern.
398       RecordedNodes.push_back(N);
399       continue;
400         
401     case OPC_RecordChild0: case OPC_RecordChild1:
402     case OPC_RecordChild2: case OPC_RecordChild3:
403     case OPC_RecordChild4: case OPC_RecordChild5:
404     case OPC_RecordChild6: case OPC_RecordChild7: {
405       unsigned ChildNo = Opcode-OPC_RecordChild0;
406       if (ChildNo >= N.getNumOperands())
407         break;  // Match fails if out of range child #.
408
409       RecordedNodes.push_back(N->getOperand(ChildNo));
410       continue;
411     }
412     case OPC_RecordMemRef:
413       MatchedMemRefs.push_back(cast<MemSDNode>(N)->getMemOperand());
414       continue;
415         
416     case OPC_CaptureFlagInput:
417       // If the current node has an input flag, capture it in InputFlag.
418       if (N->getNumOperands() != 0 &&
419           N->getOperand(N->getNumOperands()-1).getValueType() == MVT::Flag)
420         InputFlag = N->getOperand(N->getNumOperands()-1);
421       continue;
422         
423     case OPC_MoveChild: {
424       unsigned ChildNo = MatcherTable[MatcherIndex++];
425       if (ChildNo >= N.getNumOperands())
426         break;  // Match fails if out of range child #.
427       N = N.getOperand(ChildNo);
428       NodeStack.push_back(N);
429       continue;
430     }
431         
432     case OPC_MoveParent:
433       // Pop the current node off the NodeStack.
434       NodeStack.pop_back();
435       assert(!NodeStack.empty() && "Node stack imbalance!");
436       N = NodeStack.back();  
437       continue;
438      
439     case OPC_CheckSame: {
440       // Accept if it is exactly the same as a previously recorded node.
441       unsigned RecNo = MatcherTable[MatcherIndex++];
442       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
443       if (N != RecordedNodes[RecNo]) break;
444       continue;
445     }
446     case OPC_CheckPatternPredicate:
447       if (!CheckPatternPredicate(MatcherTable[MatcherIndex++])) break;
448       continue;
449     case OPC_CheckPredicate:
450       if (!CheckNodePredicate(N.getNode(), MatcherTable[MatcherIndex++])) break;
451       continue;
452     case OPC_CheckComplexPat:
453       if (!CheckComplexPattern(NodeToMatch, N, 
454                                MatcherTable[MatcherIndex++], RecordedNodes))
455         break;
456       continue;
457     case OPC_CheckOpcode:
458       if (N->getOpcode() != MatcherTable[MatcherIndex++]) break;
459       continue;
460         
461     case OPC_CheckMultiOpcode: {
462       unsigned NumOps = MatcherTable[MatcherIndex++];
463       bool OpcodeEquals = false;
464       for (unsigned i = 0; i != NumOps; ++i)
465         OpcodeEquals |= N->getOpcode() == MatcherTable[MatcherIndex++];
466       if (!OpcodeEquals) break;
467       continue;
468     }
469         
470     case OPC_CheckType: {
471       MVT::SimpleValueType VT =
472         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
473       if (N.getValueType() != VT) {
474         // Handle the case when VT is iPTR.
475         if (VT != MVT::iPTR || N.getValueType() != TLI.getPointerTy())
476           break;
477       }
478       continue;
479     }
480     case OPC_CheckChild0Type: case OPC_CheckChild1Type:
481     case OPC_CheckChild2Type: case OPC_CheckChild3Type:
482     case OPC_CheckChild4Type: case OPC_CheckChild5Type:
483     case OPC_CheckChild6Type: case OPC_CheckChild7Type: {
484       unsigned ChildNo = Opcode-OPC_CheckChild0Type;
485       if (ChildNo >= N.getNumOperands())
486         break;  // Match fails if out of range child #.
487       
488       MVT::SimpleValueType VT =
489         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
490       EVT ChildVT = N.getOperand(ChildNo).getValueType();
491       if (ChildVT != VT) {
492         // Handle the case when VT is iPTR.
493         if (VT != MVT::iPTR || ChildVT != TLI.getPointerTy())
494           break;
495       }
496       continue;
497     }
498     case OPC_CheckCondCode:
499       if (cast<CondCodeSDNode>(N)->get() !=
500           (ISD::CondCode)MatcherTable[MatcherIndex++]) break;
501       continue;
502     case OPC_CheckValueType: {
503       MVT::SimpleValueType VT =
504         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
505       if (cast<VTSDNode>(N)->getVT() != VT) {
506         // Handle the case when VT is iPTR.
507         if (VT != MVT::iPTR || cast<VTSDNode>(N)->getVT() != TLI.getPointerTy())
508           break;
509       }
510       continue;
511     }
512     case OPC_CheckInteger1:
513       if (CheckInteger(N, GetInt1(MatcherTable, MatcherIndex))) break;
514       continue;
515     case OPC_CheckInteger2:
516       if (CheckInteger(N, GetInt2(MatcherTable, MatcherIndex))) break;
517       continue;
518     case OPC_CheckInteger4:
519       if (CheckInteger(N, GetInt4(MatcherTable, MatcherIndex))) break;
520       continue;
521     case OPC_CheckInteger8:
522       if (CheckInteger(N, GetInt8(MatcherTable, MatcherIndex))) break;
523       continue;
524         
525     case OPC_CheckAndImm1:
526       if (CheckAndImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
527       continue;
528     case OPC_CheckAndImm2:
529       if (CheckAndImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
530       continue;
531     case OPC_CheckAndImm4:
532       if (CheckAndImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
533       continue;
534     case OPC_CheckAndImm8:
535       if (CheckAndImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
536       continue;
537
538     case OPC_CheckOrImm1:
539       if (CheckOrImmediate(N, GetInt1(MatcherTable, MatcherIndex))) break;
540       continue;
541     case OPC_CheckOrImm2:
542       if (CheckOrImmediate(N, GetInt2(MatcherTable, MatcherIndex))) break;
543       continue;
544     case OPC_CheckOrImm4:
545       if (CheckOrImmediate(N, GetInt4(MatcherTable, MatcherIndex))) break;
546       continue;
547     case OPC_CheckOrImm8:
548       if (CheckOrImmediate(N, GetInt8(MatcherTable, MatcherIndex))) break;
549       continue;
550         
551     case OPC_CheckFoldableChainNode: {
552       assert(NodeStack.size() != 1 && "No parent node");
553       // Verify that all intermediate nodes between the root and this one have
554       // a single use.
555       bool HasMultipleUses = false;
556       for (unsigned i = 1, e = NodeStack.size()-1; i != e; ++i)
557         if (!NodeStack[i].hasOneUse()) {
558           HasMultipleUses = true;
559           break;
560         }
561       if (HasMultipleUses) break;
562
563       // Check to see that the target thinks this is profitable to fold and that
564       // we can fold it without inducing cycles in the graph.
565       if (!IsProfitableToFold(N, NodeStack[NodeStack.size()-2].getNode(),
566                               NodeToMatch) ||
567           !IsLegalToFold(N, NodeStack[NodeStack.size()-2].getNode(),
568                          NodeToMatch))
569         break;
570       
571       continue;
572     }
573     case OPC_CheckChainCompatible: {
574       unsigned PrevNode = MatcherTable[MatcherIndex++];
575       assert(PrevNode < RecordedNodes.size() && "Invalid CheckChainCompatible");
576       SDValue PrevChainedNode = RecordedNodes[PrevNode];
577       SDValue ThisChainedNode = RecordedNodes.back();
578       
579       // We have two nodes with chains, verify that their input chains are good.
580       assert(PrevChainedNode.getOperand(0).getValueType() == MVT::Other &&
581              ThisChainedNode.getOperand(0).getValueType() == MVT::Other &&
582              "Invalid chained nodes");
583       
584       if (!IsChainCompatible(// Input chain of the previous node.
585                              PrevChainedNode.getOperand(0).getNode(),
586                              // Node with chain.
587                              ThisChainedNode.getNode()))
588         break;
589       continue;
590     }
591         
592     case OPC_EmitInteger1: {
593       MVT::SimpleValueType VT =
594         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
595       EmitInteger(GetInt1(MatcherTable, MatcherIndex), VT, RecordedNodes);
596       continue;
597     }
598     case OPC_EmitInteger2: {
599       MVT::SimpleValueType VT =
600         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
601       EmitInteger(GetInt2(MatcherTable, MatcherIndex), VT, RecordedNodes);
602       continue;
603     }
604     case OPC_EmitInteger4: {
605       MVT::SimpleValueType VT =
606         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
607       EmitInteger(GetInt4(MatcherTable, MatcherIndex), VT, RecordedNodes);
608       continue;
609     }
610     case OPC_EmitInteger8: {
611       MVT::SimpleValueType VT =
612        (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
613       EmitInteger(GetInt8(MatcherTable, MatcherIndex), VT, RecordedNodes);
614       continue;
615     }
616         
617     case OPC_EmitRegister: {
618       MVT::SimpleValueType VT =
619         (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
620       unsigned RegNo = MatcherTable[MatcherIndex++];
621       RecordedNodes.push_back(CurDAG->getRegister(RegNo, VT));
622       continue;
623     }
624         
625     case OPC_EmitConvertToTarget:  {
626       // Convert from IMM/FPIMM to target version.
627       unsigned RecNo = MatcherTable[MatcherIndex++];
628       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
629       SDValue Imm = RecordedNodes[RecNo];
630
631       if (Imm->getOpcode() == ISD::Constant) {
632         int64_t Val = cast<ConstantSDNode>(Imm)->getZExtValue();
633         Imm = CurDAG->getTargetConstant(Val, Imm.getValueType());
634       } else if (Imm->getOpcode() == ISD::ConstantFP) {
635         const ConstantFP *Val=cast<ConstantFPSDNode>(Imm)->getConstantFPValue();
636         Imm = CurDAG->getTargetConstantFP(*Val, Imm.getValueType());
637       }
638       
639       RecordedNodes.push_back(Imm);
640       continue;
641     }
642         
643     case OPC_EmitMergeInputChains: {
644       assert(InputChain.getNode() == 0 &&
645              "EmitMergeInputChains should be the first chain producing node");
646       // This node gets a list of nodes we matched in the input that have
647       // chains.  We want to token factor all of the input chains to these nodes
648       // together.  However, if any of the input chains is actually one of the
649       // nodes matched in this pattern, then we have an intra-match reference.
650       // Ignore these because the newly token factored chain should not refer to
651       // the old nodes.
652       unsigned NumChains = MatcherTable[MatcherIndex++];
653       assert(NumChains != 0 && "Can't TF zero chains");
654
655       assert(ChainNodesMatched.empty() &&
656              "Should only have one EmitMergeInputChains per match");
657
658       // Handle the first chain.
659       unsigned RecNo = MatcherTable[MatcherIndex++];
660       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
661       ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
662       
663       // If the chained node is not the root, we can't fold it if it has
664       // multiple uses.
665       // FIXME: What if other value results of the node have uses not matched by
666       // this pattern?
667       if (ChainNodesMatched.back() != NodeToMatch &&
668           !RecordedNodes[RecNo].hasOneUse()) {
669         ChainNodesMatched.clear();
670         break;
671       }
672       
673       // The common case here is that we have exactly one chain, which is really
674       // cheap to handle, just do it.
675       if (NumChains == 1) {
676         InputChain = RecordedNodes[RecNo].getOperand(0);
677         assert(InputChain.getValueType() == MVT::Other && "Not a chain");
678         continue;
679       }
680       
681       // Read all of the chained nodes.
682       for (unsigned i = 1; i != NumChains; ++i) {
683         RecNo = MatcherTable[MatcherIndex++];
684         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
685         ChainNodesMatched.push_back(RecordedNodes[RecNo].getNode());
686         
687         // FIXME: What if other value results of the node have uses not matched by
688         // this pattern?
689         if (ChainNodesMatched.back() != NodeToMatch &&
690             !RecordedNodes[RecNo].hasOneUse()) {
691           ChainNodesMatched.clear();
692           break;
693         }
694       }
695
696       // Walk all the chained nodes, adding the input chains if they are not in
697       // ChainedNodes (and this, not in the matched pattern).  This is an N^2
698       // algorithm, but # chains is usually 2 here, at most 3 for MSP430.
699       SmallVector<SDValue, 3> InputChains;
700       for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
701         SDValue InChain = ChainNodesMatched[i]->getOperand(0);
702         assert(InChain.getValueType() == MVT::Other && "Not a chain");
703         bool Invalid = false;
704         for (unsigned j = 0; j != e; ++j)
705           Invalid |= ChainNodesMatched[j] == InChain.getNode();
706         if (!Invalid)
707           InputChains.push_back(InChain);
708       }
709
710       SDValue Res;
711       if (InputChains.size() == 1)
712         InputChain = InputChains[0];
713       else
714         InputChain = CurDAG->getNode(ISD::TokenFactor,
715                                      NodeToMatch->getDebugLoc(), MVT::Other,
716                                      &InputChains[0], InputChains.size());
717       continue;
718     }
719         
720     case OPC_EmitCopyToReg: {
721       unsigned RecNo = MatcherTable[MatcherIndex++];
722       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
723       unsigned DestPhysReg = MatcherTable[MatcherIndex++];
724       
725       if (InputChain.getNode() == 0)
726         InputChain = CurDAG->getEntryNode();
727       
728       InputChain = CurDAG->getCopyToReg(InputChain, NodeToMatch->getDebugLoc(),
729                                         DestPhysReg, RecordedNodes[RecNo],
730                                         InputFlag);
731       
732       InputFlag = InputChain.getValue(1);
733       continue;
734     }
735         
736     case OPC_EmitNodeXForm: {
737       unsigned XFormNo = MatcherTable[MatcherIndex++];
738       unsigned RecNo = MatcherTable[MatcherIndex++];
739       assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
740       RecordedNodes.push_back(RunSDNodeXForm(RecordedNodes[RecNo], XFormNo));
741       continue;
742     }
743         
744     case OPC_EmitNode: {
745       uint16_t TargetOpc = GetInt2(MatcherTable, MatcherIndex);
746       unsigned EmitNodeInfo = MatcherTable[MatcherIndex++];
747       // Get the result VT list.
748       unsigned NumVTs = MatcherTable[MatcherIndex++];
749       assert(NumVTs != 0 && "Invalid node result");
750       SmallVector<EVT, 4> VTs;
751       for (unsigned i = 0; i != NumVTs; ++i) {
752         MVT::SimpleValueType VT =
753           (MVT::SimpleValueType)MatcherTable[MatcherIndex++];
754         if (VT == MVT::iPTR) VT = TLI.getPointerTy().SimpleTy;
755         VTs.push_back(VT);
756       }
757       
758       // FIXME: Use faster version for the common 'one VT' case?
759       SDVTList VTList = CurDAG->getVTList(VTs.data(), VTs.size());
760
761       // Get the operand list.
762       unsigned NumOps = MatcherTable[MatcherIndex++];
763       SmallVector<SDValue, 8> Ops;
764       for (unsigned i = 0; i != NumOps; ++i) {
765         unsigned RecNo = MatcherTable[MatcherIndex++];
766         if (RecNo & 128)
767           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
768         
769         assert(RecNo < RecordedNodes.size() && "Invalid EmitNode");
770         Ops.push_back(RecordedNodes[RecNo]);
771       }
772       
773       // If there are variadic operands to add, handle them now.
774       if (EmitNodeInfo & OPFL_VariadicInfo) {
775         // Determine the start index to copy from.
776         unsigned FirstOpToCopy = getNumFixedFromVariadicInfo(EmitNodeInfo);
777         FirstOpToCopy += (EmitNodeInfo & OPFL_Chain) ? 1 : 0;
778         assert(NodeToMatch->getNumOperands() >= FirstOpToCopy &&
779                "Invalid variadic node");
780         // Copy all of the variadic operands, not including a potential flag
781         // input.
782         for (unsigned i = FirstOpToCopy, e = NodeToMatch->getNumOperands();
783              i != e; ++i) {
784           SDValue V = NodeToMatch->getOperand(i);
785           if (V.getValueType() == MVT::Flag) break;
786           Ops.push_back(V);
787         }
788       }
789       
790       // If this has chain/flag inputs, add them.
791       if (EmitNodeInfo & OPFL_Chain)
792         Ops.push_back(InputChain);
793       if ((EmitNodeInfo & OPFL_Flag) && InputFlag.getNode() != 0)
794         Ops.push_back(InputFlag);
795       
796       // Create the node.
797       MachineSDNode *Res = CurDAG->getMachineNode(TargetOpc,
798                                                   NodeToMatch->getDebugLoc(),
799                                                   VTList,
800                                                   Ops.data(), Ops.size());
801       // Add all the non-flag/non-chain results to the RecordedNodes list.
802       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
803         if (VTs[i] == MVT::Other || VTs[i] == MVT::Flag) break;
804         RecordedNodes.push_back(SDValue(Res, i));
805       }
806       
807       // If the node had chain/flag results, update our notion of the current
808       // chain and flag.
809       if (VTs.back() == MVT::Flag) {
810         InputFlag = SDValue(Res, VTs.size()-1);
811         if (EmitNodeInfo & OPFL_Chain)
812           InputChain = SDValue(Res, VTs.size()-2);
813       } else if (EmitNodeInfo & OPFL_Chain)
814         InputChain = SDValue(Res, VTs.size()-1);
815
816       // If the OPFL_MemRefs flag is set on this node, slap all of the
817       // accumulated memrefs onto it.
818       //
819       // FIXME: This is vastly incorrect for patterns with multiple outputs
820       // instructions that access memory and for ComplexPatterns that match
821       // loads.
822       if (EmitNodeInfo & OPFL_MemRefs) {
823         MachineSDNode::mmo_iterator MemRefs =
824           MF->allocateMemRefsArray(MatchedMemRefs.size());
825         std::copy(MatchedMemRefs.begin(), MatchedMemRefs.end(), MemRefs);
826         Res->setMemRefs(MemRefs, MemRefs + MatchedMemRefs.size());
827       }
828       
829       DEBUG(errs() << "  Created node: "; Res->dump(CurDAG); errs() << "\n");
830       continue;
831     }
832         
833     case OPC_MarkFlagResults: {
834       unsigned NumNodes = MatcherTable[MatcherIndex++];
835       
836       // Read and remember all the flag-result nodes.
837       for (unsigned i = 0; i != NumNodes; ++i) {
838         unsigned RecNo = MatcherTable[MatcherIndex++];
839         if (RecNo & 128)
840           RecNo = GetVBR(RecNo, MatcherTable, MatcherIndex);
841
842         assert(RecNo < RecordedNodes.size() && "Invalid CheckSame");
843         FlagResultNodesMatched.push_back(RecordedNodes[RecNo].getNode());
844       }
845       continue;
846     }
847       
848     case OPC_CompleteMatch: {
849       // The match has been completed, and any new nodes (if any) have been
850       // created.  Patch up references to the matched dag to use the newly
851       // created nodes.
852       unsigned NumResults = MatcherTable[MatcherIndex++];
853
854       for (unsigned i = 0; i != NumResults; ++i) {
855         unsigned ResSlot = MatcherTable[MatcherIndex++];
856         if (ResSlot & 128)
857           ResSlot = GetVBR(ResSlot, MatcherTable, MatcherIndex);
858         
859         assert(ResSlot < RecordedNodes.size() && "Invalid CheckSame");
860         SDValue Res = RecordedNodes[ResSlot];
861         
862         // FIXME2: Eliminate this horrible hack by fixing the 'Gen' program
863         // after (parallel) on input patterns are removed.  This would also
864         // allow us to stop encoding #results in OPC_CompleteMatch's table
865         // entry.
866         if (NodeToMatch->getNumValues() <= i ||
867             NodeToMatch->getValueType(i) == MVT::Other ||
868             NodeToMatch->getValueType(i) == MVT::Flag)
869           break;
870         assert((NodeToMatch->getValueType(i) == Res.getValueType() ||
871                 NodeToMatch->getValueType(i) == MVT::iPTR ||
872                 Res.getValueType() == MVT::iPTR ||
873                 NodeToMatch->getValueType(i).getSizeInBits() ==
874                     Res.getValueType().getSizeInBits()) &&
875                "invalid replacement");
876         ReplaceUses(SDValue(NodeToMatch, i), Res);
877       }
878       
879       // Now that all the normal results are replaced, we replace the chain and
880       // flag results if present.
881       if (!ChainNodesMatched.empty()) {
882         assert(InputChain.getNode() != 0 &&
883                "Matched input chains but didn't produce a chain");
884         // Loop over all of the nodes we matched that produced a chain result.
885         // Replace all the chain results with the final chain we ended up with.
886         for (unsigned i = 0, e = ChainNodesMatched.size(); i != e; ++i) {
887           SDNode *ChainNode = ChainNodesMatched[i];
888           SDValue ChainVal = SDValue(ChainNode, ChainNode->getNumValues()-1);
889           if (ChainVal.getValueType() == MVT::Flag)
890             ChainVal = ChainVal.getValue(ChainVal->getNumValues()-2);
891           assert(ChainVal.getValueType() == MVT::Other && "Not a chain?");
892           ReplaceUses(ChainVal, InputChain);
893         }
894       }
895
896       // If the result produces a flag, update any flag results in the matched
897       // pattern with the flag result.
898       if (InputFlag.getNode() != 0) {
899         // Handle the root node:
900         if (NodeToMatch->getValueType(NodeToMatch->getNumValues()-1) ==
901               MVT::Flag)
902           ReplaceUses(SDValue(NodeToMatch, NodeToMatch->getNumValues()-1),
903                       InputFlag);
904         
905         // Handle any interior nodes explicitly marked.
906         for (unsigned i = 0, e = FlagResultNodesMatched.size(); i != e; ++i) {
907           SDNode *FRN = FlagResultNodesMatched[i];
908           assert(FRN->getValueType(FRN->getNumValues()-1) == MVT::Flag &&
909                  "Doesn't have a flag result");
910           ReplaceUses(SDValue(FRN, FRN->getNumValues()-1), InputFlag);
911         }
912       }
913       
914       assert(NodeToMatch->use_empty() &&
915              "Didn't replace all uses of the node?");
916       
917       DEBUG(errs() << "ISEL: Match complete!\n");
918       
919       // FIXME: We just return here, which interacts correctly with SelectRoot
920       // above.  We should fix this to not return an SDNode* anymore.
921       return 0;
922     }
923     }
924     
925     // If the code reached this point, then the match failed.  See if there is
926     // another child to try in the current 'Scope', otherwise pop it until we
927     // find a case to check.
928     while (1) {
929       if (MatchScopes.empty()) {
930         CannotYetSelect(NodeToMatch);
931         return 0;
932       }
933
934       // Restore the interpreter state back to the point where the scope was
935       // formed.
936       MatchScope &LastScope = MatchScopes.back();
937       RecordedNodes.resize(LastScope.NumRecordedNodes);
938       NodeStack.clear();
939       NodeStack.append(LastScope.NodeStack.begin(), LastScope.NodeStack.end());
940       N = NodeStack.back();
941
942       DEBUG(errs() << "  Match failed at index " << MatcherIndex
943                    << " continuing at " << LastScope.FailIndex << "\n");
944     
945       if (LastScope.NumMatchedMemRefs != MatchedMemRefs.size())
946         MatchedMemRefs.resize(LastScope.NumMatchedMemRefs);
947       MatcherIndex = LastScope.FailIndex;
948       
949       InputChain = LastScope.InputChain;
950       InputFlag = LastScope.InputFlag;
951       if (!LastScope.HasChainNodesMatched)
952         ChainNodesMatched.clear();
953       if (!LastScope.HasFlagResultNodesMatched)
954         FlagResultNodesMatched.clear();
955
956       // Check to see what the offset is at the new MatcherIndex.  If it is zero
957       // we have reached the end of this scope, otherwise we have another child
958       // in the current scope to try.
959       unsigned NumToSkip = MatcherTable[MatcherIndex++];
960       if (NumToSkip & 128)
961         NumToSkip = GetVBR(NumToSkip, MatcherTable, MatcherIndex);
962
963       // If we have another child in this scope to match, update FailIndex and
964       // try it.
965       if (NumToSkip != 0) {
966         LastScope.FailIndex = MatcherIndex+NumToSkip;
967         break;
968       }
969       
970       // End of this scope, pop it and try the next child in the containing
971       // scope.
972       MatchScopes.pop_back();
973     }
974   }
975 }
976     
977
978 #endif /* LLVM_CODEGEN_DAGISEL_HEADER_H */