Move yet more folds over to the dag combiner from sd.cpp
[oota-llvm.git] / lib / CodeGen / SelectionDAG / SelectionDAG.cpp
1 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This implements the SelectionDAG class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/CodeGen/SelectionDAG.h"
15 #include "llvm/Constants.h"
16 #include "llvm/GlobalValue.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "llvm/CodeGen/MachineBasicBlock.h"
19 #include "llvm/Support/MathExtras.h"
20 #include "llvm/Target/MRegisterInfo.h"
21 #include "llvm/Target/TargetLowering.h"
22 #include "llvm/Target/TargetInstrInfo.h"
23 #include "llvm/Target/TargetMachine.h"
24 #include <iostream>
25 #include <set>
26 #include <cmath>
27 #include <algorithm>
28 using namespace llvm;
29
30 // Temporary boolean for testing the dag combiner
31 namespace llvm {
32   extern bool CombinerEnabled;
33 }
34
35 static bool isCommutativeBinOp(unsigned Opcode) {
36   switch (Opcode) {
37   case ISD::ADD:
38   case ISD::MUL:
39   case ISD::AND:
40   case ISD::OR:
41   case ISD::XOR: return true;
42   default: return false; // FIXME: Need commutative info for user ops!
43   }
44 }
45
46 static bool isAssociativeBinOp(unsigned Opcode) {
47   switch (Opcode) {
48   case ISD::ADD:
49   case ISD::MUL:
50   case ISD::AND:
51   case ISD::OR:
52   case ISD::XOR: return true;
53   default: return false; // FIXME: Need associative info for user ops!
54   }
55 }
56
57 // isInvertibleForFree - Return true if there is no cost to emitting the logical
58 // inverse of this node.
59 static bool isInvertibleForFree(SDOperand N) {
60   if (isa<ConstantSDNode>(N.Val)) return true;
61   if (N.Val->getOpcode() == ISD::SETCC && N.Val->hasOneUse())
62     return true;
63   return false;
64 }
65
66 //===----------------------------------------------------------------------===//
67 //                              ConstantFPSDNode Class
68 //===----------------------------------------------------------------------===//
69
70 /// isExactlyValue - We don't rely on operator== working on double values, as
71 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
72 /// As such, this method can be used to do an exact bit-for-bit comparison of
73 /// two floating point values.
74 bool ConstantFPSDNode::isExactlyValue(double V) const {
75   return DoubleToBits(V) == DoubleToBits(Value);
76 }
77
78 //===----------------------------------------------------------------------===//
79 //                              ISD Class
80 //===----------------------------------------------------------------------===//
81
82 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
83 /// when given the operation for (X op Y).
84 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
85   // To perform this operation, we just need to swap the L and G bits of the
86   // operation.
87   unsigned OldL = (Operation >> 2) & 1;
88   unsigned OldG = (Operation >> 1) & 1;
89   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
90                        (OldL << 1) |       // New G bit
91                        (OldG << 2));        // New L bit.
92 }
93
94 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
95 /// 'op' is a valid SetCC operation.
96 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
97   unsigned Operation = Op;
98   if (isInteger)
99     Operation ^= 7;   // Flip L, G, E bits, but not U.
100   else
101     Operation ^= 15;  // Flip all of the condition bits.
102   if (Operation > ISD::SETTRUE2)
103     Operation &= ~8;     // Don't let N and U bits get set.
104   return ISD::CondCode(Operation);
105 }
106
107
108 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
109 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
110 /// if the operation does not depend on the sign of the input (setne and seteq).
111 static int isSignedOp(ISD::CondCode Opcode) {
112   switch (Opcode) {
113   default: assert(0 && "Illegal integer setcc operation!");
114   case ISD::SETEQ:
115   case ISD::SETNE: return 0;
116   case ISD::SETLT:
117   case ISD::SETLE:
118   case ISD::SETGT:
119   case ISD::SETGE: return 1;
120   case ISD::SETULT:
121   case ISD::SETULE:
122   case ISD::SETUGT:
123   case ISD::SETUGE: return 2;
124   }
125 }
126
127 /// getSetCCOrOperation - Return the result of a logical OR between different
128 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
129 /// returns SETCC_INVALID if it is not possible to represent the resultant
130 /// comparison.
131 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
132                                        bool isInteger) {
133   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
134     // Cannot fold a signed integer setcc with an unsigned integer setcc.
135     return ISD::SETCC_INVALID;
136
137   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
138
139   // If the N and U bits get set then the resultant comparison DOES suddenly
140   // care about orderedness, and is true when ordered.
141   if (Op > ISD::SETTRUE2)
142     Op &= ~16;     // Clear the N bit.
143   return ISD::CondCode(Op);
144 }
145
146 /// getSetCCAndOperation - Return the result of a logical AND between different
147 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
148 /// function returns zero if it is not possible to represent the resultant
149 /// comparison.
150 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
151                                         bool isInteger) {
152   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
153     // Cannot fold a signed setcc with an unsigned setcc.
154     return ISD::SETCC_INVALID;
155
156   // Combine all of the condition bits.
157   return ISD::CondCode(Op1 & Op2);
158 }
159
160 const TargetMachine &SelectionDAG::getTarget() const {
161   return TLI.getTargetMachine();
162 }
163
164 //===----------------------------------------------------------------------===//
165 //                              SelectionDAG Class
166 //===----------------------------------------------------------------------===//
167
168 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
169 /// SelectionDAG, including nodes (like loads) that have uses of their token
170 /// chain but no other uses and no side effect.  If a node is passed in as an
171 /// argument, it is used as the seed for node deletion.
172 void SelectionDAG::RemoveDeadNodes(SDNode *N) {
173   std::set<SDNode*> AllNodeSet(AllNodes.begin(), AllNodes.end());
174
175   // Create a dummy node (which is not added to allnodes), that adds a reference
176   // to the root node, preventing it from being deleted.
177   SDNode *DummyNode = new SDNode(ISD::EntryToken, getRoot());
178
179   // If we have a hint to start from, use it.
180   if (N) DeleteNodeIfDead(N, &AllNodeSet);
181
182  Restart:
183   unsigned NumNodes = AllNodeSet.size();
184   for (std::set<SDNode*>::iterator I = AllNodeSet.begin(), E = AllNodeSet.end();
185        I != E; ++I) {
186     // Try to delete this node.
187     DeleteNodeIfDead(*I, &AllNodeSet);
188
189     // If we actually deleted any nodes, do not use invalid iterators in
190     // AllNodeSet.
191     if (AllNodeSet.size() != NumNodes)
192       goto Restart;
193   }
194
195   // Restore AllNodes.
196   if (AllNodes.size() != NumNodes)
197     AllNodes.assign(AllNodeSet.begin(), AllNodeSet.end());
198
199   // If the root changed (e.g. it was a dead load, update the root).
200   setRoot(DummyNode->getOperand(0));
201
202   // Now that we are done with the dummy node, delete it.
203   DummyNode->getOperand(0).Val->removeUser(DummyNode);
204   delete DummyNode;
205 }
206
207
208 void SelectionDAG::DeleteNodeIfDead(SDNode *N, void *NodeSet) {
209   if (!N->use_empty())
210     return;
211
212   // Okay, we really are going to delete this node.  First take this out of the
213   // appropriate CSE map.
214   RemoveNodeFromCSEMaps(N);
215   
216   // Next, brutally remove the operand list.  This is safe to do, as there are
217   // no cycles in the graph.
218   while (!N->Operands.empty()) {
219     SDNode *O = N->Operands.back().Val;
220     N->Operands.pop_back();
221     O->removeUser(N);
222     
223     // Now that we removed this operand, see if there are no uses of it left.
224     DeleteNodeIfDead(O, NodeSet);
225   }
226   
227   // Remove the node from the nodes set and delete it.
228   std::set<SDNode*> &AllNodeSet = *(std::set<SDNode*>*)NodeSet;
229   AllNodeSet.erase(N);
230   
231   // Now that the node is gone, check to see if any of the operands of this node
232   // are dead now.
233   delete N;  
234 }
235
236 void SelectionDAG::DeleteNode(SDNode *N) {
237   assert(N->use_empty() && "Cannot delete a node that is not dead!");
238
239   // First take this out of the appropriate CSE map.
240   RemoveNodeFromCSEMaps(N);
241
242   // Finally, remove uses due to operands of this node, remove from the 
243   // AllNodes list, and delete the node.
244   DeleteNodeNotInCSEMaps(N);
245 }
246
247 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
248
249   // Remove it from the AllNodes list.
250   for (std::vector<SDNode*>::iterator I = AllNodes.begin(); ; ++I) {
251     assert(I != AllNodes.end() && "Node not in AllNodes list??");
252     if (*I == N) {
253       // Erase from the vector, which is not ordered.
254       std::swap(*I, AllNodes.back());
255       AllNodes.pop_back();
256       break;
257     }
258   }
259     
260   // Drop all of the operands and decrement used nodes use counts.
261   while (!N->Operands.empty()) {
262     SDNode *O = N->Operands.back().Val;
263     N->Operands.pop_back();
264     O->removeUser(N);
265   }
266   
267   delete N;
268 }
269
270 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
271 /// correspond to it.  This is useful when we're about to delete or repurpose
272 /// the node.  We don't want future request for structurally identical nodes
273 /// to return N anymore.
274 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
275   bool Erased = false;
276   switch (N->getOpcode()) {
277   case ISD::Constant:
278     Erased = Constants.erase(std::make_pair(cast<ConstantSDNode>(N)->getValue(),
279                                             N->getValueType(0)));
280     break;
281   case ISD::TargetConstant:
282     Erased = TargetConstants.erase(std::make_pair(
283                                     cast<ConstantSDNode>(N)->getValue(),
284                                                   N->getValueType(0)));
285     break;
286   case ISD::ConstantFP: {
287     uint64_t V = DoubleToBits(cast<ConstantFPSDNode>(N)->getValue());
288     Erased = ConstantFPs.erase(std::make_pair(V, N->getValueType(0)));
289     break;
290   }
291   case ISD::CONDCODE:
292     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
293            "Cond code doesn't exist!");
294     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
295     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
296     break;
297   case ISD::GlobalAddress:
298     Erased = GlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
299     break;
300   case ISD::TargetGlobalAddress:
301     Erased =TargetGlobalValues.erase(cast<GlobalAddressSDNode>(N)->getGlobal());
302     break;
303   case ISD::FrameIndex:
304     Erased = FrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
305     break;
306   case ISD::TargetFrameIndex:
307     Erased = TargetFrameIndices.erase(cast<FrameIndexSDNode>(N)->getIndex());
308     break;
309   case ISD::ConstantPool:
310     Erased = ConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
311     break;
312   case ISD::TargetConstantPool:
313     Erased =TargetConstantPoolIndices.erase(cast<ConstantPoolSDNode>(N)->get());
314     break;
315   case ISD::BasicBlock:
316     Erased = BBNodes.erase(cast<BasicBlockSDNode>(N)->getBasicBlock());
317     break;
318   case ISD::ExternalSymbol:
319     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
320     break;
321   case ISD::VALUETYPE:
322     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
323     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
324     break;
325   case ISD::Register:
326     Erased = RegNodes.erase(std::make_pair(cast<RegisterSDNode>(N)->getReg(),
327                                            N->getValueType(0)));
328     break;
329   case ISD::SRCVALUE: {
330     SrcValueSDNode *SVN = cast<SrcValueSDNode>(N);
331     Erased =ValueNodes.erase(std::make_pair(SVN->getValue(), SVN->getOffset()));
332     break;
333   }    
334   case ISD::LOAD:
335     Erased = Loads.erase(std::make_pair(N->getOperand(1),
336                                         std::make_pair(N->getOperand(0),
337                                                        N->getValueType(0))));
338     break;
339   default:
340     if (N->getNumValues() == 1) {
341       if (N->getNumOperands() == 0) {
342         Erased = NullaryOps.erase(std::make_pair(N->getOpcode(),
343                                                  N->getValueType(0)));
344       } else if (N->getNumOperands() == 1) {
345         Erased = 
346           UnaryOps.erase(std::make_pair(N->getOpcode(),
347                                         std::make_pair(N->getOperand(0),
348                                                        N->getValueType(0))));
349       } else if (N->getNumOperands() == 2) {
350         Erased = 
351           BinaryOps.erase(std::make_pair(N->getOpcode(),
352                                          std::make_pair(N->getOperand(0),
353                                                         N->getOperand(1))));
354       } else { 
355         std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
356         Erased = 
357           OneResultNodes.erase(std::make_pair(N->getOpcode(),
358                                               std::make_pair(N->getValueType(0),
359                                                              Ops)));
360       }
361     } else {
362       // Remove the node from the ArbitraryNodes map.
363       std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
364       std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
365       Erased =
366         ArbitraryNodes.erase(std::make_pair(N->getOpcode(),
367                                             std::make_pair(RV, Ops)));
368     }
369     break;
370   }
371 #ifndef NDEBUG
372   // Verify that the node was actually in one of the CSE maps, unless it has a 
373   // flag result (which cannot be CSE'd) or is one of the special cases that are
374   // not subject to CSE.
375   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
376       N->getOpcode() != ISD::CALL && N->getOpcode() != ISD::CALLSEQ_START &&
377       N->getOpcode() != ISD::CALLSEQ_END && !N->isTargetOpcode()) {
378     
379     N->dump();
380     assert(0 && "Node is not in map!");
381   }
382 #endif
383 }
384
385 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
386 /// has been taken out and modified in some way.  If the specified node already
387 /// exists in the CSE maps, do not modify the maps, but return the existing node
388 /// instead.  If it doesn't exist, add it and return null.
389 ///
390 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
391   assert(N->getNumOperands() && "This is a leaf node!");
392   if (N->getOpcode() == ISD::LOAD) {
393     SDNode *&L = Loads[std::make_pair(N->getOperand(1),
394                                       std::make_pair(N->getOperand(0),
395                                                      N->getValueType(0)))];
396     if (L) return L;
397     L = N;
398   } else if (N->getNumOperands() == 1) {
399     SDNode *&U = UnaryOps[std::make_pair(N->getOpcode(),
400                                          std::make_pair(N->getOperand(0),
401                                                         N->getValueType(0)))];
402     if (U) return U;
403     U = N;
404   } else if (N->getNumOperands() == 2) {
405     SDNode *&B = BinaryOps[std::make_pair(N->getOpcode(),
406                                           std::make_pair(N->getOperand(0),
407                                                          N->getOperand(1)))];
408     if (B) return B;
409     B = N;
410   } else if (N->getNumValues() == 1) {
411     std::vector<SDOperand> Ops(N->op_begin(), N->op_end());
412     SDNode *&ORN = OneResultNodes[std::make_pair(N->getOpcode(),
413                                   std::make_pair(N->getValueType(0), Ops))];
414     if (ORN) return ORN;
415     ORN = N;
416   } else {
417     // Remove the node from the ArbitraryNodes map.
418     std::vector<MVT::ValueType> RV(N->value_begin(), N->value_end());
419     std::vector<SDOperand>     Ops(N->op_begin(), N->op_end());
420     SDNode *&AN = ArbitraryNodes[std::make_pair(N->getOpcode(),
421                                                 std::make_pair(RV, Ops))];
422     if (AN) return AN;
423     AN = N;
424   }
425   return 0;
426   
427 }
428
429
430
431 SelectionDAG::~SelectionDAG() {
432   for (unsigned i = 0, e = AllNodes.size(); i != e; ++i)
433     delete AllNodes[i];
434 }
435
436 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
437   if (Op.getValueType() == VT) return Op;
438   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
439   return getNode(ISD::AND, Op.getValueType(), Op,
440                  getConstant(Imm, Op.getValueType()));
441 }
442
443 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT) {
444   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
445   // Mask out any bits that are not valid for this constant.
446   if (VT != MVT::i64)
447     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
448
449   SDNode *&N = Constants[std::make_pair(Val, VT)];
450   if (N) return SDOperand(N, 0);
451   N = new ConstantSDNode(false, Val, VT);
452   AllNodes.push_back(N);
453   return SDOperand(N, 0);
454 }
455
456 SDOperand SelectionDAG::getTargetConstant(uint64_t Val, MVT::ValueType VT) {
457   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
458   // Mask out any bits that are not valid for this constant.
459   if (VT != MVT::i64)
460     Val &= ((uint64_t)1 << MVT::getSizeInBits(VT)) - 1;
461   
462   SDNode *&N = TargetConstants[std::make_pair(Val, VT)];
463   if (N) return SDOperand(N, 0);
464   N = new ConstantSDNode(true, Val, VT);
465   AllNodes.push_back(N);
466   return SDOperand(N, 0);
467 }
468
469 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT) {
470   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
471   if (VT == MVT::f32)
472     Val = (float)Val;  // Mask out extra precision.
473
474   // Do the map lookup using the actual bit pattern for the floating point
475   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
476   // we don't have issues with SNANs.
477   SDNode *&N = ConstantFPs[std::make_pair(DoubleToBits(Val), VT)];
478   if (N) return SDOperand(N, 0);
479   N = new ConstantFPSDNode(Val, VT);
480   AllNodes.push_back(N);
481   return SDOperand(N, 0);
482 }
483
484
485
486 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
487                                          MVT::ValueType VT) {
488   SDNode *&N = GlobalValues[GV];
489   if (N) return SDOperand(N, 0);
490   N = new GlobalAddressSDNode(false, GV, VT);
491   AllNodes.push_back(N);
492   return SDOperand(N, 0);
493 }
494
495 SDOperand SelectionDAG::getTargetGlobalAddress(const GlobalValue *GV,
496                                                MVT::ValueType VT) {
497   SDNode *&N = TargetGlobalValues[GV];
498   if (N) return SDOperand(N, 0);
499   N = new GlobalAddressSDNode(true, GV, VT);
500   AllNodes.push_back(N);
501   return SDOperand(N, 0);
502 }
503
504 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT) {
505   SDNode *&N = FrameIndices[FI];
506   if (N) return SDOperand(N, 0);
507   N = new FrameIndexSDNode(FI, VT, false);
508   AllNodes.push_back(N);
509   return SDOperand(N, 0);
510 }
511
512 SDOperand SelectionDAG::getTargetFrameIndex(int FI, MVT::ValueType VT) {
513   SDNode *&N = TargetFrameIndices[FI];
514   if (N) return SDOperand(N, 0);
515   N = new FrameIndexSDNode(FI, VT, true);
516   AllNodes.push_back(N);
517   return SDOperand(N, 0);
518 }
519
520 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT) {
521   SDNode *&N = ConstantPoolIndices[C];
522   if (N) return SDOperand(N, 0);
523   N = new ConstantPoolSDNode(C, VT, false);
524   AllNodes.push_back(N);
525   return SDOperand(N, 0);
526 }
527
528 SDOperand SelectionDAG::getTargetConstantPool(Constant *C, MVT::ValueType VT) {
529   SDNode *&N = TargetConstantPoolIndices[C];
530   if (N) return SDOperand(N, 0);
531   N = new ConstantPoolSDNode(C, VT, true);
532   AllNodes.push_back(N);
533   return SDOperand(N, 0);
534 }
535
536 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
537   SDNode *&N = BBNodes[MBB];
538   if (N) return SDOperand(N, 0);
539   N = new BasicBlockSDNode(MBB);
540   AllNodes.push_back(N);
541   return SDOperand(N, 0);
542 }
543
544 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
545   if ((unsigned)VT >= ValueTypeNodes.size())
546     ValueTypeNodes.resize(VT+1);
547   if (ValueTypeNodes[VT] == 0) {
548     ValueTypeNodes[VT] = new VTSDNode(VT);
549     AllNodes.push_back(ValueTypeNodes[VT]);
550   }
551
552   return SDOperand(ValueTypeNodes[VT], 0);
553 }
554
555 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
556   SDNode *&N = ExternalSymbols[Sym];
557   if (N) return SDOperand(N, 0);
558   N = new ExternalSymbolSDNode(Sym, VT);
559   AllNodes.push_back(N);
560   return SDOperand(N, 0);
561 }
562
563 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
564   if ((unsigned)Cond >= CondCodeNodes.size())
565     CondCodeNodes.resize(Cond+1);
566   
567   if (CondCodeNodes[Cond] == 0) {
568     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
569     AllNodes.push_back(CondCodeNodes[Cond]);
570   }
571   return SDOperand(CondCodeNodes[Cond], 0);
572 }
573
574 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
575   RegisterSDNode *&Reg = RegNodes[std::make_pair(RegNo, VT)];
576   if (!Reg) {
577     Reg = new RegisterSDNode(RegNo, VT);
578     AllNodes.push_back(Reg);
579   }
580   return SDOperand(Reg, 0);
581 }
582
583 SDOperand SelectionDAG::SimplifySetCC(MVT::ValueType VT, SDOperand N1,
584                                       SDOperand N2, ISD::CondCode Cond) {
585   // These setcc operations always fold.
586   switch (Cond) {
587   default: break;
588   case ISD::SETFALSE:
589   case ISD::SETFALSE2: return getConstant(0, VT);
590   case ISD::SETTRUE:
591   case ISD::SETTRUE2:  return getConstant(1, VT);
592   }
593
594   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
595     uint64_t C2 = N2C->getValue();
596     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
597       uint64_t C1 = N1C->getValue();
598
599       // Sign extend the operands if required
600       if (ISD::isSignedIntSetCC(Cond)) {
601         C1 = N1C->getSignExtended();
602         C2 = N2C->getSignExtended();
603       }
604
605       switch (Cond) {
606       default: assert(0 && "Unknown integer setcc!");
607       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
608       case ISD::SETNE:  return getConstant(C1 != C2, VT);
609       case ISD::SETULT: return getConstant(C1 <  C2, VT);
610       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
611       case ISD::SETULE: return getConstant(C1 <= C2, VT);
612       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
613       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
614       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
615       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
616       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
617       }
618     } else {
619       // If the LHS is a ZERO_EXTEND, perform the comparison on the input.
620       if (N1.getOpcode() == ISD::ZERO_EXTEND) {
621         unsigned InSize = MVT::getSizeInBits(N1.getOperand(0).getValueType());
622
623         // If the comparison constant has bits in the upper part, the
624         // zero-extended value could never match.
625         if (C2 & (~0ULL << InSize)) {
626           unsigned VSize = MVT::getSizeInBits(N1.getValueType());
627           switch (Cond) {
628           case ISD::SETUGT:
629           case ISD::SETUGE:
630           case ISD::SETEQ: return getConstant(0, VT);
631           case ISD::SETULT:
632           case ISD::SETULE:
633           case ISD::SETNE: return getConstant(1, VT);
634           case ISD::SETGT:
635           case ISD::SETGE:
636             // True if the sign bit of C2 is set.
637             return getConstant((C2 & (1ULL << VSize)) != 0, VT);
638           case ISD::SETLT:
639           case ISD::SETLE:
640             // True if the sign bit of C2 isn't set.
641             return getConstant((C2 & (1ULL << VSize)) == 0, VT);
642           default:
643             break;
644           }
645         }
646
647         // Otherwise, we can perform the comparison with the low bits.
648         switch (Cond) {
649         case ISD::SETEQ:
650         case ISD::SETNE:
651         case ISD::SETUGT:
652         case ISD::SETUGE:
653         case ISD::SETULT:
654         case ISD::SETULE:
655           return getSetCC(VT, N1.getOperand(0),
656                           getConstant(C2, N1.getOperand(0).getValueType()),
657                           Cond);
658         default:
659           break;   // todo, be more careful with signed comparisons
660         }
661       } else if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG &&
662                  (Cond == ISD::SETEQ || Cond == ISD::SETNE)) {
663         MVT::ValueType ExtSrcTy = cast<VTSDNode>(N1.getOperand(1))->getVT();
664         unsigned ExtSrcTyBits = MVT::getSizeInBits(ExtSrcTy);
665         MVT::ValueType ExtDstTy = N1.getValueType();
666         unsigned ExtDstTyBits = MVT::getSizeInBits(ExtDstTy);
667
668         // If the extended part has any inconsistent bits, it cannot ever
669         // compare equal.  In other words, they have to be all ones or all
670         // zeros.
671         uint64_t ExtBits =
672           (~0ULL >> (64-ExtSrcTyBits)) & (~0ULL << (ExtDstTyBits-1));
673         if ((C2 & ExtBits) != 0 && (C2 & ExtBits) != ExtBits)
674           return getConstant(Cond == ISD::SETNE, VT);
675         
676         // Otherwise, make this a use of a zext.
677         return getSetCC(VT, getZeroExtendInReg(N1.getOperand(0), ExtSrcTy),
678                         getConstant(C2 & (~0ULL>>(64-ExtSrcTyBits)), ExtDstTy),
679                         Cond);
680       }
681
682       uint64_t MinVal, MaxVal;
683       unsigned OperandBitSize = MVT::getSizeInBits(N2C->getValueType(0));
684       if (ISD::isSignedIntSetCC(Cond)) {
685         MinVal = 1ULL << (OperandBitSize-1);
686         if (OperandBitSize != 1)   // Avoid X >> 64, which is undefined.
687           MaxVal = ~0ULL >> (65-OperandBitSize);
688         else
689           MaxVal = 0;
690       } else {
691         MinVal = 0;
692         MaxVal = ~0ULL >> (64-OperandBitSize);
693       }
694
695       // Canonicalize GE/LE comparisons to use GT/LT comparisons.
696       if (Cond == ISD::SETGE || Cond == ISD::SETUGE) {
697         if (C2 == MinVal) return getConstant(1, VT);   // X >= MIN --> true
698         --C2;                                          // X >= C1 --> X > (C1-1)
699         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
700                         (Cond == ISD::SETGE) ? ISD::SETGT : ISD::SETUGT);
701       }
702
703       if (Cond == ISD::SETLE || Cond == ISD::SETULE) {
704         if (C2 == MaxVal) return getConstant(1, VT);   // X <= MAX --> true
705         ++C2;                                          // X <= C1 --> X < (C1+1)
706         return getSetCC(VT, N1, getConstant(C2, N2.getValueType()),
707                         (Cond == ISD::SETLE) ? ISD::SETLT : ISD::SETULT);
708       }
709
710       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal)
711         return getConstant(0, VT);      // X < MIN --> false
712
713       // Canonicalize setgt X, Min --> setne X, Min
714       if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MinVal)
715         return getSetCC(VT, N1, N2, ISD::SETNE);
716
717       // If we have setult X, 1, turn it into seteq X, 0
718       if ((Cond == ISD::SETLT || Cond == ISD::SETULT) && C2 == MinVal+1)
719         return getSetCC(VT, N1, getConstant(MinVal, N1.getValueType()),
720                         ISD::SETEQ);
721       // If we have setugt X, Max-1, turn it into seteq X, Max
722       else if ((Cond == ISD::SETGT || Cond == ISD::SETUGT) && C2 == MaxVal-1)
723         return getSetCC(VT, N1, getConstant(MaxVal, N1.getValueType()),
724                         ISD::SETEQ);
725
726       // If we have "setcc X, C1", check to see if we can shrink the immediate
727       // by changing cc.
728
729       // SETUGT X, SINTMAX  -> SETLT X, 0
730       if (Cond == ISD::SETUGT && OperandBitSize != 1 &&
731           C2 == (~0ULL >> (65-OperandBitSize)))
732         return getSetCC(VT, N1, getConstant(0, N2.getValueType()), ISD::SETLT);
733
734       // FIXME: Implement the rest of these.
735
736
737       // Fold bit comparisons when we can.
738       if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
739           VT == N1.getValueType() && N1.getOpcode() == ISD::AND)
740         if (ConstantSDNode *AndRHS =
741                     dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
742           if (Cond == ISD::SETNE && C2 == 0) {// (X & 8) != 0  -->  (X & 8) >> 3
743             // Perform the xform if the AND RHS is a single bit.
744             if ((AndRHS->getValue() & (AndRHS->getValue()-1)) == 0) {
745               return getNode(ISD::SRL, VT, N1,
746                              getConstant(Log2_64(AndRHS->getValue()),
747                                                    TLI.getShiftAmountTy()));
748             }
749           } else if (Cond == ISD::SETEQ && C2 == AndRHS->getValue()) {
750             // (X & 8) == 8  -->  (X & 8) >> 3
751             // Perform the xform if C2 is a single bit.
752             if ((C2 & (C2-1)) == 0) {
753               return getNode(ISD::SRL, VT, N1,
754                              getConstant(Log2_64(C2),TLI.getShiftAmountTy()));
755             }
756           }
757         }
758     }
759   } else if (isa<ConstantSDNode>(N1.Val)) {
760       // Ensure that the constant occurs on the RHS.
761     return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
762   }
763
764   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
765     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
766       double C1 = N1C->getValue(), C2 = N2C->getValue();
767
768       switch (Cond) {
769       default: break; // FIXME: Implement the rest of these!
770       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
771       case ISD::SETNE:  return getConstant(C1 != C2, VT);
772       case ISD::SETLT:  return getConstant(C1 < C2, VT);
773       case ISD::SETGT:  return getConstant(C1 > C2, VT);
774       case ISD::SETLE:  return getConstant(C1 <= C2, VT);
775       case ISD::SETGE:  return getConstant(C1 >= C2, VT);
776       }
777     } else {
778       // Ensure that the constant occurs on the RHS.
779       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
780     }
781
782   if (N1 == N2) {
783     // We can always fold X == Y for integer setcc's.
784     if (MVT::isInteger(N1.getValueType()))
785       return getConstant(ISD::isTrueWhenEqual(Cond), VT);
786     unsigned UOF = ISD::getUnorderedFlavor(Cond);
787     if (UOF == 2)   // FP operators that are undefined on NaNs.
788       return getConstant(ISD::isTrueWhenEqual(Cond), VT);
789     if (UOF == unsigned(ISD::isTrueWhenEqual(Cond)))
790       return getConstant(UOF, VT);
791     // Otherwise, we can't fold it.  However, we can simplify it to SETUO/SETO
792     // if it is not already.
793     ISD::CondCode NewCond = UOF == 0 ? ISD::SETUO : ISD::SETO;
794     if (NewCond != Cond)
795       return getSetCC(VT, N1, N2, NewCond);
796   }
797
798   if ((Cond == ISD::SETEQ || Cond == ISD::SETNE) &&
799       MVT::isInteger(N1.getValueType())) {
800     if (N1.getOpcode() == ISD::ADD || N1.getOpcode() == ISD::SUB ||
801         N1.getOpcode() == ISD::XOR) {
802       // Simplify (X+Y) == (X+Z) -->  Y == Z
803       if (N1.getOpcode() == N2.getOpcode()) {
804         if (N1.getOperand(0) == N2.getOperand(0))
805           return getSetCC(VT, N1.getOperand(1), N2.getOperand(1), Cond);
806         if (N1.getOperand(1) == N2.getOperand(1))
807           return getSetCC(VT, N1.getOperand(0), N2.getOperand(0), Cond);
808         if (isCommutativeBinOp(N1.getOpcode())) {
809           // If X op Y == Y op X, try other combinations.
810           if (N1.getOperand(0) == N2.getOperand(1))
811             return getSetCC(VT, N1.getOperand(1), N2.getOperand(0), Cond);
812           if (N1.getOperand(1) == N2.getOperand(0))
813             return getSetCC(VT, N1.getOperand(1), N2.getOperand(1), Cond);
814         }
815       }
816
817       // FIXME: move this stuff to the DAG Combiner when it exists!
818
819       // Simplify (X+Z) == X -->  Z == 0
820       if (N1.getOperand(0) == N2)
821         return getSetCC(VT, N1.getOperand(1),
822                         getConstant(0, N1.getValueType()), Cond);
823       if (N1.getOperand(1) == N2) {
824         if (isCommutativeBinOp(N1.getOpcode()))
825           return getSetCC(VT, N1.getOperand(0),
826                           getConstant(0, N1.getValueType()), Cond);
827         else {
828           assert(N1.getOpcode() == ISD::SUB && "Unexpected operation!");
829           // (Z-X) == X  --> Z == X<<1
830           return getSetCC(VT, N1.getOperand(0),
831                           getNode(ISD::SHL, N2.getValueType(),
832                                   N2, getConstant(1, TLI.getShiftAmountTy())),
833                           Cond);
834         }
835       }
836     }
837
838     if (N2.getOpcode() == ISD::ADD || N2.getOpcode() == ISD::SUB ||
839         N2.getOpcode() == ISD::XOR) {
840       // Simplify  X == (X+Z) -->  Z == 0
841       if (N2.getOperand(0) == N1) {
842         return getSetCC(VT, N2.getOperand(1),
843                         getConstant(0, N2.getValueType()), Cond);
844       } else if (N2.getOperand(1) == N1) {
845         if (isCommutativeBinOp(N2.getOpcode())) {
846           return getSetCC(VT, N2.getOperand(0),
847                           getConstant(0, N2.getValueType()), Cond);
848         } else {
849           assert(N2.getOpcode() == ISD::SUB && "Unexpected operation!");
850           // X == (Z-X)  --> X<<1 == Z
851           return getSetCC(VT, getNode(ISD::SHL, N2.getValueType(), N1, 
852                                       getConstant(1, TLI.getShiftAmountTy())),
853                           N2.getOperand(0), Cond);
854         }
855       }
856     }
857   }
858
859   // Fold away ALL boolean setcc's.
860   if (N1.getValueType() == MVT::i1) {
861     switch (Cond) {
862     default: assert(0 && "Unknown integer setcc!");
863     case ISD::SETEQ:  // X == Y  -> (X^Y)^1
864       N1 = getNode(ISD::XOR, MVT::i1,
865                    getNode(ISD::XOR, MVT::i1, N1, N2),
866                    getConstant(1, MVT::i1));
867       break;
868     case ISD::SETNE:  // X != Y   -->  (X^Y)
869       N1 = getNode(ISD::XOR, MVT::i1, N1, N2);
870       break;
871     case ISD::SETGT:  // X >s Y   -->  X == 0 & Y == 1  -->  X^1 & Y
872     case ISD::SETULT: // X <u Y   -->  X == 0 & Y == 1  -->  X^1 & Y
873       N1 = getNode(ISD::AND, MVT::i1, N2,
874                    getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
875       break;
876     case ISD::SETLT:  // X <s Y   --> X == 1 & Y == 0  -->  Y^1 & X
877     case ISD::SETUGT: // X >u Y   --> X == 1 & Y == 0  -->  Y^1 & X
878       N1 = getNode(ISD::AND, MVT::i1, N1,
879                    getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
880       break;
881     case ISD::SETULE: // X <=u Y  --> X == 0 | Y == 1  -->  X^1 | Y
882     case ISD::SETGE:  // X >=s Y  --> X == 0 | Y == 1  -->  X^1 | Y
883       N1 = getNode(ISD::OR, MVT::i1, N2,
884                    getNode(ISD::XOR, MVT::i1, N1, getConstant(1, MVT::i1)));
885       break;
886     case ISD::SETUGE: // X >=u Y  --> X == 1 | Y == 0  -->  Y^1 | X
887     case ISD::SETLE:  // X <=s Y  --> X == 1 | Y == 0  -->  Y^1 | X
888       N1 = getNode(ISD::OR, MVT::i1, N1,
889                    getNode(ISD::XOR, MVT::i1, N2, getConstant(1, MVT::i1)));
890       break;
891     }
892     if (VT != MVT::i1)
893       N1 = getNode(ISD::ZERO_EXTEND, VT, N1);
894     return N1;
895   }
896
897   // Could not fold it.
898   return SDOperand();
899 }
900
901 SDOperand SelectionDAG::SimplifySelectCC(SDOperand N1, SDOperand N2, 
902                                          SDOperand N3, SDOperand N4, 
903                                          ISD::CondCode CC) {
904   MVT::ValueType VT = N3.getValueType();
905   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
906   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
907   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
908   ConstantSDNode *N4C = dyn_cast<ConstantSDNode>(N4.Val);
909   
910   // Check to see if we can simplify the select into an fabs node
911   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2)) {
912     // Allow either -0.0 or 0.0
913     if (CFP->getValue() == 0.0) {
914       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
915       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
916           N1 == N3 && N4.getOpcode() == ISD::FNEG &&
917           N1 == N4.getOperand(0))
918         return getNode(ISD::FABS, VT, N1);
919       
920       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
921       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
922           N1 == N4 && N3.getOpcode() == ISD::FNEG &&
923           N3.getOperand(0) == N4)
924         return getNode(ISD::FABS, VT, N4);
925     }
926   }
927   
928   // check to see if we're select_cc'ing a select_cc.
929   // this allows us to turn:
930   // select_cc set[eq,ne] (select_cc cc, lhs, rhs, 1, 0), 0, true, false ->
931   // select_cc cc, lhs, rhs, true, false
932   if ((N1C && N1C->isNullValue() && N2.getOpcode() == ISD::SELECT_CC) ||
933       (N2C && N2C->isNullValue() && N1.getOpcode() == ISD::SELECT_CC) &&
934       (CC == ISD::SETEQ || CC == ISD::SETNE)) {
935     SDOperand SCC = N1C ? N2 : N1;
936     ConstantSDNode *SCCT = dyn_cast<ConstantSDNode>(SCC.getOperand(2));
937     ConstantSDNode *SCCF = dyn_cast<ConstantSDNode>(SCC.getOperand(3));
938     if (SCCT && SCCF && SCCF->isNullValue() && SCCT->getValue() == 1ULL) {
939       if (CC == ISD::SETEQ) std::swap(N3, N4);
940       return getNode(ISD::SELECT_CC, N3.getValueType(), SCC.getOperand(0), 
941                      SCC.getOperand(1), N3, N4, SCC.getOperand(4));
942     }
943   }
944       
945   // Check to see if we can perform the "gzip trick", transforming
946   // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
947   if (N2C && N2C->isNullValue() && N4C && N4C->isNullValue() &&
948       MVT::isInteger(N1.getValueType()) && 
949       MVT::isInteger(N3.getValueType()) && CC == ISD::SETLT) {
950     MVT::ValueType XType = N1.getValueType();
951     MVT::ValueType AType = N3.getValueType();
952     if (XType >= AType) {
953       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
954       // single-bit constant.  FIXME: remove once the dag combiner
955       // exists.
956       if (N3C && ((N3C->getValue() & (N3C->getValue()-1)) == 0)) {
957         unsigned ShCtV = Log2_64(N3C->getValue());
958         ShCtV = MVT::getSizeInBits(XType)-ShCtV-1;
959         SDOperand ShCt = getConstant(ShCtV, TLI.getShiftAmountTy());
960         SDOperand Shift = getNode(ISD::SRL, XType, N1, ShCt);
961         if (XType > AType)
962           Shift = getNode(ISD::TRUNCATE, AType, Shift);
963         return getNode(ISD::AND, AType, Shift, N3);
964       }
965       SDOperand Shift = getNode(ISD::SRA, XType, N1,
966                                 getConstant(MVT::getSizeInBits(XType)-1,
967                                             TLI.getShiftAmountTy()));
968       if (XType > AType)
969         Shift = getNode(ISD::TRUNCATE, AType, Shift);
970       return getNode(ISD::AND, AType, Shift, N3);
971     }
972   }
973   
974   // Check to see if this is the equivalent of setcc
975   if (N4C && N4C->isNullValue() && N3C && (N3C->getValue() == 1ULL)) {
976     MVT::ValueType XType = N1.getValueType();
977     if (TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultTy()))
978       return getSetCC(TLI.getSetCCResultTy(), N1, N2, CC);
979
980     // seteq X, 0 -> srl (ctlz X, log2(size(X)))
981     if (N2C && N2C->isNullValue() && CC == ISD::SETEQ && 
982         TLI.isOperationLegal(ISD::CTLZ, XType)) {
983       SDOperand Ctlz = getNode(ISD::CTLZ, XType, N1);
984       return getNode(ISD::SRL, XType, Ctlz, 
985                      getConstant(Log2_32(MVT::getSizeInBits(XType)),
986                                  TLI.getShiftAmountTy()));
987     }
988     // setgt X, 0 -> srl (and (-X, ~X), size(X)-1)
989     if (N2C && N2C->isNullValue() && CC == ISD::SETGT) { 
990       SDOperand NegN1 = getNode(ISD::SUB, XType, getConstant(0, XType), N1);
991       SDOperand NotN1 = getNode(ISD::XOR, XType, N1, getConstant(~0ULL, XType));
992       return getNode(ISD::SRL, XType, getNode(ISD::AND, XType, NegN1, NotN1),
993                      getConstant(MVT::getSizeInBits(XType)-1,
994                                  TLI.getShiftAmountTy()));
995     }
996     // setgt X, -1 -> xor (srl (X, size(X)-1), 1)
997     if (N2C && N2C->isAllOnesValue() && CC == ISD::SETGT) {
998       SDOperand Sign = getNode(ISD::SRL, XType, N1,
999                                getConstant(MVT::getSizeInBits(XType)-1,
1000                                            TLI.getShiftAmountTy()));
1001       return getNode(ISD::XOR, XType, Sign, getConstant(1, XType));
1002     }
1003   }
1004
1005   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
1006   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
1007   if (N2C && N2C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
1008       N1 == N4 && N3.getOpcode() == ISD::SUB && N1 == N3.getOperand(1)) {
1009     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
1010       MVT::ValueType XType = N1.getValueType();
1011       if (SubC->isNullValue() && MVT::isInteger(XType)) {
1012         SDOperand Shift = getNode(ISD::SRA, XType, N1,
1013                                   getConstant(MVT::getSizeInBits(XType)-1,
1014                                               TLI.getShiftAmountTy()));
1015         return getNode(ISD::XOR, XType, getNode(ISD::ADD, XType, N1, Shift), 
1016                        Shift);
1017       }
1018     }
1019   }
1020   
1021   // Could not fold it.
1022   return SDOperand();
1023 }
1024
1025 /// getNode - Gets or creates the specified node.
1026 ///
1027 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1028   SDNode *&N = NullaryOps[std::make_pair(Opcode, VT)];
1029   if (!N) {
1030     N = new SDNode(Opcode, VT);
1031     AllNodes.push_back(N);
1032   }
1033   return SDOperand(N, 0);
1034 }
1035
1036 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1037                                 SDOperand Operand) {
1038   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1039     uint64_t Val = C->getValue();
1040     switch (Opcode) {
1041     default: break;
1042     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1043     case ISD::ANY_EXTEND:
1044     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1045     case ISD::TRUNCATE:    return getConstant(Val, VT);
1046     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
1047     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
1048     }
1049   }
1050
1051   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val))
1052     switch (Opcode) {
1053     case ISD::FNEG:
1054       return getConstantFP(-C->getValue(), VT);
1055     case ISD::FP_ROUND:
1056     case ISD::FP_EXTEND:
1057       return getConstantFP(C->getValue(), VT);
1058     case ISD::FP_TO_SINT:
1059       return getConstant((int64_t)C->getValue(), VT);
1060     case ISD::FP_TO_UINT:
1061       return getConstant((uint64_t)C->getValue(), VT);
1062     }
1063
1064   unsigned OpOpcode = Operand.Val->getOpcode();
1065   switch (Opcode) {
1066   case ISD::TokenFactor:
1067     return Operand;         // Factor of one node?  No factor.
1068   case ISD::SIGN_EXTEND:
1069     if (Operand.getValueType() == VT) return Operand;   // noop extension
1070     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1071       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1072     break;
1073   case ISD::ZERO_EXTEND:
1074     if (Operand.getValueType() == VT) return Operand;   // noop extension
1075     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1076       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1077     break;
1078   case ISD::ANY_EXTEND:
1079     if (Operand.getValueType() == VT) return Operand;   // noop extension
1080     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1081       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1082       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1083     break;
1084   case ISD::TRUNCATE:
1085     if (Operand.getValueType() == VT) return Operand;   // noop truncate
1086     if (OpOpcode == ISD::TRUNCATE)
1087       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1088     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1089              OpOpcode == ISD::ANY_EXTEND) {
1090       // If the source is smaller than the dest, we still need an extend.
1091       if (Operand.Val->getOperand(0).getValueType() < VT)
1092         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1093       else if (Operand.Val->getOperand(0).getValueType() > VT)
1094         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1095       else
1096         return Operand.Val->getOperand(0);
1097     }
1098     break;
1099   case ISD::FNEG:
1100     if (OpOpcode == ISD::SUB)   // -(X-Y) -> (Y-X)
1101       return getNode(ISD::SUB, VT, Operand.Val->getOperand(1),
1102                      Operand.Val->getOperand(0));
1103     if (OpOpcode == ISD::FNEG)  // --X -> X
1104       return Operand.Val->getOperand(0);
1105     break;
1106   case ISD::FABS:
1107     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1108       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1109     break;
1110   }
1111
1112   SDNode *N;
1113   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1114     SDNode *&E = UnaryOps[std::make_pair(Opcode, std::make_pair(Operand, VT))];
1115     if (E) return SDOperand(E, 0);
1116     E = N = new SDNode(Opcode, Operand);
1117   } else {
1118     N = new SDNode(Opcode, Operand);
1119   }
1120   N->setValueTypes(VT);
1121   AllNodes.push_back(N);
1122   return SDOperand(N, 0);
1123 }
1124
1125 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1126 /// this predicate to simplify operations downstream.  V and Mask are known to
1127 /// be the same type.
1128 static bool MaskedValueIsZero(const SDOperand &Op, uint64_t Mask,
1129                               const TargetLowering &TLI) {
1130   unsigned SrcBits;
1131   if (Mask == 0) return true;
1132
1133   // If we know the result of a setcc has the top bits zero, use this info.
1134   switch (Op.getOpcode()) {
1135   case ISD::Constant:
1136     return (cast<ConstantSDNode>(Op)->getValue() & Mask) == 0;
1137
1138   case ISD::SETCC:
1139     return ((Mask & 1) == 0) &&
1140            TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult;
1141
1142   case ISD::ZEXTLOAD:
1143     SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(3))->getVT());
1144     return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
1145   case ISD::ZERO_EXTEND:
1146     SrcBits = MVT::getSizeInBits(Op.getOperand(0).getValueType());
1147     return MaskedValueIsZero(Op.getOperand(0),Mask & ((1ULL << SrcBits)-1),TLI);
1148   case ISD::AssertZext:
1149     SrcBits = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1150     return (Mask & ((1ULL << SrcBits)-1)) == 0; // Returning only the zext bits.
1151   case ISD::AND:
1152     // (X & C1) & C2 == 0   iff   C1 & C2 == 0.
1153     if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
1154       return MaskedValueIsZero(Op.getOperand(0),AndRHS->getValue() & Mask, TLI);
1155
1156     // FALL THROUGH
1157   case ISD::OR:
1158   case ISD::XOR:
1159     return MaskedValueIsZero(Op.getOperand(0), Mask, TLI) &&
1160            MaskedValueIsZero(Op.getOperand(1), Mask, TLI);
1161   case ISD::SELECT:
1162     return MaskedValueIsZero(Op.getOperand(1), Mask, TLI) &&
1163            MaskedValueIsZero(Op.getOperand(2), Mask, TLI);
1164   case ISD::SELECT_CC:
1165     return MaskedValueIsZero(Op.getOperand(2), Mask, TLI) &&
1166            MaskedValueIsZero(Op.getOperand(3), Mask, TLI);
1167   case ISD::SRL:
1168     // (ushr X, C1) & C2 == 0   iff  X & (C2 << C1) == 0
1169     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1170       uint64_t NewVal = Mask << ShAmt->getValue();
1171       SrcBits = MVT::getSizeInBits(Op.getValueType());
1172       if (SrcBits != 64) NewVal &= (1ULL << SrcBits)-1;
1173       return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
1174     }
1175     return false;
1176   case ISD::SHL:
1177     // (ushl X, C1) & C2 == 0   iff  X & (C2 >> C1) == 0
1178     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1179       uint64_t NewVal = Mask >> ShAmt->getValue();
1180       return MaskedValueIsZero(Op.getOperand(0), NewVal, TLI);
1181     }
1182     return false;
1183   case ISD::CTTZ:
1184   case ISD::CTLZ:
1185   case ISD::CTPOP:
1186     // Bit counting instructions can not set the high bits of the result
1187     // register.  The max number of bits sets depends on the input.
1188     return (Mask & (MVT::getSizeInBits(Op.getValueType())*2-1)) == 0;
1189     
1190     // TODO we could handle some SRA cases here.
1191   default: break;
1192   }
1193
1194   return false;
1195 }
1196
1197
1198
1199 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1200                                 SDOperand N1, SDOperand N2) {
1201 #ifndef NDEBUG
1202   switch (Opcode) {
1203   case ISD::TokenFactor:
1204     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1205            N2.getValueType() == MVT::Other && "Invalid token factor!");
1206     break;
1207   case ISD::AND:
1208   case ISD::OR:
1209   case ISD::XOR:
1210   case ISD::UDIV:
1211   case ISD::UREM:
1212   case ISD::MULHU:
1213   case ISD::MULHS:
1214     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1215     // fall through
1216   case ISD::ADD:
1217   case ISD::SUB:
1218   case ISD::MUL:
1219   case ISD::SDIV:
1220   case ISD::SREM:
1221     assert(N1.getValueType() == N2.getValueType() &&
1222            N1.getValueType() == VT && "Binary operator types must match!");
1223     break;
1224
1225   case ISD::SHL:
1226   case ISD::SRA:
1227   case ISD::SRL:
1228     assert(VT == N1.getValueType() &&
1229            "Shift operators return type must be the same as their first arg");
1230     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1231            VT != MVT::i1 && "Shifts only work on integers");
1232     break;
1233   case ISD::FP_ROUND_INREG: {
1234     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1235     assert(VT == N1.getValueType() && "Not an inreg round!");
1236     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1237            "Cannot FP_ROUND_INREG integer types");
1238     assert(EVT <= VT && "Not rounding down!");
1239     break;
1240   }
1241   case ISD::AssertSext:
1242   case ISD::AssertZext:
1243   case ISD::SIGN_EXTEND_INREG: {
1244     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1245     assert(VT == N1.getValueType() && "Not an inreg extend!");
1246     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1247            "Cannot *_EXTEND_INREG FP types");
1248     assert(EVT <= VT && "Not extending!");
1249   }
1250
1251   default: break;
1252   }
1253 #endif
1254
1255   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1256   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1257   if (N1C) {
1258     if (N2C) {
1259       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1260       switch (Opcode) {
1261       case ISD::ADD: return getConstant(C1 + C2, VT);
1262       case ISD::SUB: return getConstant(C1 - C2, VT);
1263       case ISD::MUL: return getConstant(C1 * C2, VT);
1264       case ISD::UDIV:
1265         if (C2) return getConstant(C1 / C2, VT);
1266         break;
1267       case ISD::UREM :
1268         if (C2) return getConstant(C1 % C2, VT);
1269         break;
1270       case ISD::SDIV :
1271         if (C2) return getConstant(N1C->getSignExtended() /
1272                                    N2C->getSignExtended(), VT);
1273         break;
1274       case ISD::SREM :
1275         if (C2) return getConstant(N1C->getSignExtended() %
1276                                    N2C->getSignExtended(), VT);
1277         break;
1278       case ISD::AND  : return getConstant(C1 & C2, VT);
1279       case ISD::OR   : return getConstant(C1 | C2, VT);
1280       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1281       case ISD::SHL  : return getConstant(C1 << C2, VT);
1282       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1283       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1284       default: break;
1285       }
1286     } else {      // Cannonicalize constant to RHS if commutative
1287       if (isCommutativeBinOp(Opcode)) {
1288         std::swap(N1C, N2C);
1289         std::swap(N1, N2);
1290       }
1291     }
1292
1293     if (!CombinerEnabled) {
1294     switch (Opcode) {
1295     default: break;
1296     case ISD::SHL:    // shl  0, X -> 0
1297       if (N1C->isNullValue()) return N1;
1298       break;
1299     case ISD::SRL:    // srl  0, X -> 0
1300       if (N1C->isNullValue()) return N1;
1301       break;
1302     case ISD::SRA:    // sra -1, X -> -1
1303       if (N1C->isAllOnesValue()) return N1;
1304       break;
1305     case ISD::SIGN_EXTEND_INREG:  // SIGN_EXTEND_INREG N1C, EVT
1306       // Extending a constant?  Just return the extended constant.
1307       SDOperand Tmp = getNode(ISD::TRUNCATE, cast<VTSDNode>(N2)->getVT(), N1);
1308       return getNode(ISD::SIGN_EXTEND, VT, Tmp);
1309     }
1310     }
1311   }
1312
1313   if (N2C) {
1314     uint64_t C2 = N2C->getValue();
1315
1316     if (!CombinerEnabled) {
1317     switch (Opcode) {
1318     case ISD::ADD:
1319       if (!C2) return N1;         // add X, 0 -> X
1320       break;
1321     case ISD::SUB:
1322       if (!C2) return N1;         // sub X, 0 -> X
1323       return getNode(ISD::ADD, VT, N1, getConstant(-C2, VT));
1324     case ISD::MUL:
1325       if (!C2) return N2;         // mul X, 0 -> 0
1326       if (N2C->isAllOnesValue()) // mul X, -1 -> 0-X
1327         return getNode(ISD::SUB, VT, getConstant(0, VT), N1);
1328
1329       // FIXME: Move this to the DAG combiner when it exists.
1330       if ((C2 & C2-1) == 0) {
1331         SDOperand ShAmt = getConstant(Log2_64(C2), TLI.getShiftAmountTy());
1332         return getNode(ISD::SHL, VT, N1, ShAmt);
1333       }
1334       break;
1335
1336     case ISD::MULHU:
1337     case ISD::MULHS:
1338       if (!C2) return N2;         // mul X, 0 -> 0
1339
1340       if (C2 == 1)                // 0X*01 -> 0X  hi(0X) == 0
1341         return getConstant(0, VT);
1342
1343       // Many others could be handled here, including -1, powers of 2, etc.
1344       break;
1345
1346     case ISD::UDIV:
1347       // FIXME: Move this to the DAG combiner when it exists.
1348       if ((C2 & C2-1) == 0 && C2) {
1349         SDOperand ShAmt = getConstant(Log2_64(C2), TLI.getShiftAmountTy());
1350         return getNode(ISD::SRL, VT, N1, ShAmt);
1351       }
1352       break;
1353
1354     case ISD::SHL:
1355     case ISD::SRL:
1356     case ISD::SRA:
1357       // If the shift amount is bigger than the size of the data, then all the
1358       // bits are shifted out.  Simplify to undef.
1359       if (C2 >= MVT::getSizeInBits(N1.getValueType())) {
1360         return getNode(ISD::UNDEF, N1.getValueType());
1361       }
1362       if (C2 == 0) return N1;
1363       
1364       if (Opcode == ISD::SRA) {
1365         // If the sign bit is known to be zero, switch this to a SRL.
1366         if (MaskedValueIsZero(N1,
1367                               1ULL << (MVT::getSizeInBits(N1.getValueType())-1),
1368                               TLI))
1369           return getNode(ISD::SRL, N1.getValueType(), N1, N2);
1370       } else {
1371         // If the part left over is known to be zero, the whole thing is zero.
1372         uint64_t TypeMask = ~0ULL >> (64-MVT::getSizeInBits(N1.getValueType()));
1373         if (Opcode == ISD::SRL) {
1374           if (MaskedValueIsZero(N1, TypeMask << C2, TLI))
1375             return getConstant(0, N1.getValueType());
1376         } else if (Opcode == ISD::SHL) {
1377           if (MaskedValueIsZero(N1, TypeMask >> C2, TLI))
1378             return getConstant(0, N1.getValueType());
1379         }
1380       }
1381
1382       if (Opcode == ISD::SHL && N1.getNumOperands() == 2)
1383         if (ConstantSDNode *OpSA = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1384           unsigned OpSAC = OpSA->getValue();
1385           if (N1.getOpcode() == ISD::SHL) {
1386             if (C2+OpSAC >= MVT::getSizeInBits(N1.getValueType()))
1387               return getConstant(0, N1.getValueType());
1388             return getNode(ISD::SHL, N1.getValueType(), N1.getOperand(0),
1389                            getConstant(C2+OpSAC, N2.getValueType()));
1390           } else if (N1.getOpcode() == ISD::SRL) {
1391             // (X >> C1) << C2:  if C2 > C1, ((X & ~0<<C1) << C2-C1)
1392             SDOperand Mask = getNode(ISD::AND, VT, N1.getOperand(0),
1393                                      getConstant(~0ULL << OpSAC, VT));
1394             if (C2 > OpSAC) {
1395               return getNode(ISD::SHL, VT, Mask,
1396                              getConstant(C2-OpSAC, N2.getValueType()));
1397             } else {
1398               // (X >> C1) << C2:  if C2 <= C1, ((X & ~0<<C1) >> C1-C2)
1399               return getNode(ISD::SRL, VT, Mask,
1400                              getConstant(OpSAC-C2, N2.getValueType()));
1401             }
1402           } else if (N1.getOpcode() == ISD::SRA) {
1403             // if C1 == C2, just mask out low bits.
1404             if (C2 == OpSAC)
1405               return getNode(ISD::AND, VT, N1.getOperand(0),
1406                              getConstant(~0ULL << C2, VT));
1407           }
1408         }
1409       break;
1410
1411     case ISD::AND:
1412       if (!C2) return N2;         // X and 0 -> 0
1413       if (N2C->isAllOnesValue())
1414         return N1;                // X and -1 -> X
1415
1416       if (MaskedValueIsZero(N1, C2, TLI))  // X and 0 -> 0
1417         return getConstant(0, VT);
1418
1419       {
1420         uint64_t NotC2 = ~C2;
1421         if (VT != MVT::i64)
1422           NotC2 &= (1ULL << MVT::getSizeInBits(VT))-1;
1423
1424         if (MaskedValueIsZero(N1, NotC2, TLI))
1425           return N1;                // if (X & ~C2) -> 0, the and is redundant
1426       }
1427
1428       // FIXME: Should add a corresponding version of this for
1429       // ZERO_EXTEND/SIGN_EXTEND by converting them to an ANY_EXTEND node which
1430       // we don't have yet.
1431       // FIXME: NOW WE DO, add this.
1432
1433       // and (sign_extend_inreg x:16:32), 1 -> and x, 1
1434       if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1435         // If we are masking out the part of our input that was extended, just
1436         // mask the input to the extension directly.
1437         unsigned ExtendBits =
1438           MVT::getSizeInBits(cast<VTSDNode>(N1.getOperand(1))->getVT());
1439         if ((C2 & (~0ULL << ExtendBits)) == 0)
1440           return getNode(ISD::AND, VT, N1.getOperand(0), N2);
1441       } else if (N1.getOpcode() == ISD::OR) {
1442         if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N1.getOperand(1)))
1443           if ((ORI->getValue() & C2) == C2) {
1444             // If the 'or' is setting all of the bits that we are masking for,
1445             // we know the result of the AND will be the AND mask itself.
1446             return N2;
1447           }
1448       }
1449       break;
1450     case ISD::OR:
1451       if (!C2)return N1;          // X or 0 -> X
1452       if (N2C->isAllOnesValue())
1453         return N2;                // X or -1 -> -1
1454       break;
1455     case ISD::XOR:
1456       if (!C2) return N1;        // X xor 0 -> X
1457       if (N2C->getValue() == 1 && N1.Val->getOpcode() == ISD::SETCC) {
1458           SDNode *SetCC = N1.Val;
1459           // !(X op Y) -> (X !op Y)
1460           bool isInteger = MVT::isInteger(SetCC->getOperand(0).getValueType());
1461           ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
1462           return getSetCC(SetCC->getValueType(0),
1463                           SetCC->getOperand(0), SetCC->getOperand(1),
1464                           ISD::getSetCCInverse(CC, isInteger));
1465       } else if (N2C->isAllOnesValue()) {
1466         if (N1.getOpcode() == ISD::AND || N1.getOpcode() == ISD::OR) {
1467           SDNode *Op = N1.Val;
1468           // !(X or Y) -> (!X and !Y) iff X or Y are freely invertible
1469           // !(X and Y) -> (!X or !Y) iff X or Y are freely invertible
1470           SDOperand LHS = Op->getOperand(0), RHS = Op->getOperand(1);
1471           if (isInvertibleForFree(RHS) || isInvertibleForFree(LHS)) {
1472             LHS = getNode(ISD::XOR, VT, LHS, N2);  // RHS = ~LHS
1473             RHS = getNode(ISD::XOR, VT, RHS, N2);  // RHS = ~RHS
1474             if (Op->getOpcode() == ISD::AND)
1475               return getNode(ISD::OR, VT, LHS, RHS);
1476             return getNode(ISD::AND, VT, LHS, RHS);
1477           }
1478         }
1479         // X xor -1 -> not(x)  ?
1480       }
1481       break;
1482     }
1483
1484     // Reassociate ((X op C1) op C2) if possible.
1485     if (N1.getOpcode() == Opcode && isAssociativeBinOp(Opcode))
1486       if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N1.Val->getOperand(1)))
1487         return getNode(Opcode, VT, N1.Val->getOperand(0),
1488                        getNode(Opcode, VT, N2, N1.Val->getOperand(1)));
1489     }
1490   }
1491
1492   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1493   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1494   if (N1CFP) {
1495     if (N2CFP) {
1496       double C1 = N1CFP->getValue(), C2 = N2CFP->getValue();
1497       switch (Opcode) {
1498       case ISD::ADD: return getConstantFP(C1 + C2, VT);
1499       case ISD::SUB: return getConstantFP(C1 - C2, VT);
1500       case ISD::MUL: return getConstantFP(C1 * C2, VT);
1501       case ISD::SDIV:
1502         if (C2) return getConstantFP(C1 / C2, VT);
1503         break;
1504       case ISD::SREM :
1505         if (C2) return getConstantFP(fmod(C1, C2), VT);
1506         break;
1507       default: break;
1508       }
1509     } else {      // Cannonicalize constant to RHS if commutative
1510       if (isCommutativeBinOp(Opcode)) {
1511         std::swap(N1CFP, N2CFP);
1512         std::swap(N1, N2);
1513       }
1514     }
1515
1516     if (!CombinerEnabled) {
1517     if (Opcode == ISD::FP_ROUND_INREG)
1518       return getNode(ISD::FP_EXTEND, VT,
1519                      getNode(ISD::FP_ROUND, cast<VTSDNode>(N2)->getVT(), N1));
1520     }
1521   }
1522
1523   // Finally, fold operations that do not require constants.
1524   switch (Opcode) {
1525   case ISD::TokenFactor:
1526     if (!CombinerEnabled) {
1527     if (N1.getOpcode() == ISD::EntryToken)
1528       return N2;
1529     if (N2.getOpcode() == ISD::EntryToken)
1530       return N1;
1531     }
1532     break;
1533
1534   case ISD::AND:
1535   case ISD::OR:
1536     if (N1.Val->getOpcode() == ISD::SETCC && N2.Val->getOpcode() == ISD::SETCC){
1537       SDNode *LHS = N1.Val, *RHS = N2.Val;
1538       SDOperand LL = LHS->getOperand(0), RL = RHS->getOperand(0);
1539       SDOperand LR = LHS->getOperand(1), RR = RHS->getOperand(1);
1540       ISD::CondCode Op1 = cast<CondCodeSDNode>(LHS->getOperand(2))->get();
1541       ISD::CondCode Op2 = cast<CondCodeSDNode>(RHS->getOperand(2))->get();
1542
1543       if (LR == RR && isa<ConstantSDNode>(LR) &&
1544           Op2 == Op1 && MVT::isInteger(LL.getValueType())) {
1545         // (X != 0) | (Y != 0) -> (X|Y != 0)
1546         // (X == 0) & (Y == 0) -> (X|Y == 0)
1547         // (X <  0) | (Y <  0) -> (X|Y < 0)
1548         if (cast<ConstantSDNode>(LR)->getValue() == 0 &&
1549             ((Op2 == ISD::SETEQ && Opcode == ISD::AND) ||
1550              (Op2 == ISD::SETNE && Opcode == ISD::OR) ||
1551              (Op2 == ISD::SETLT && Opcode == ISD::OR)))
1552           return getSetCC(VT, getNode(ISD::OR, LR.getValueType(), LL, RL), LR,
1553                           Op2);
1554
1555         if (cast<ConstantSDNode>(LR)->isAllOnesValue()) {
1556           // (X == -1) & (Y == -1) -> (X&Y == -1)
1557           // (X != -1) | (Y != -1) -> (X&Y != -1)
1558           // (X >  -1) | (Y >  -1) -> (X&Y >  -1)
1559           if ((Opcode == ISD::AND && Op2 == ISD::SETEQ) ||
1560               (Opcode == ISD::OR  && Op2 == ISD::SETNE) ||
1561               (Opcode == ISD::OR  && Op2 == ISD::SETGT))
1562             return getSetCC(VT, getNode(ISD::AND, LR.getValueType(), LL, RL),
1563                             LR, Op2);
1564           // (X >  -1) & (Y >  -1) -> (X|Y > -1)
1565           if (Opcode == ISD::AND && Op2 == ISD::SETGT)
1566             return getSetCC(VT, getNode(ISD::OR, LR.getValueType(), LL, RL),
1567                             LR, Op2);
1568         }
1569       }
1570
1571       // (X op1 Y) | (Y op2 X) -> (X op1 Y) | (X swapop2 Y)
1572       if (LL == RR && LR == RL) {
1573         Op2 = ISD::getSetCCSwappedOperands(Op2);
1574         goto MatchedBackwards;
1575       }
1576
1577       if (LL == RL && LR == RR) {
1578       MatchedBackwards:
1579         ISD::CondCode Result;
1580         bool isInteger = MVT::isInteger(LL.getValueType());
1581         if (Opcode == ISD::OR)
1582           Result = ISD::getSetCCOrOperation(Op1, Op2, isInteger);
1583         else
1584           Result = ISD::getSetCCAndOperation(Op1, Op2, isInteger);
1585
1586         if (Result != ISD::SETCC_INVALID)
1587           return getSetCC(LHS->getValueType(0), LL, LR, Result);
1588       }
1589     }
1590
1591     // and/or zext(a), zext(b) -> zext(and/or a, b)
1592     if (N1.getOpcode() == ISD::ZERO_EXTEND &&
1593         N2.getOpcode() == ISD::ZERO_EXTEND &&
1594         N1.getOperand(0).getValueType() == N2.getOperand(0).getValueType())
1595       return getNode(ISD::ZERO_EXTEND, VT,
1596                      getNode(Opcode, N1.getOperand(0).getValueType(),
1597                              N1.getOperand(0), N2.getOperand(0)));
1598     break;
1599   case ISD::XOR:
1600     if (!CombinerEnabled) {
1601     if (N1 == N2) return getConstant(0, VT);  // xor X, Y -> 0
1602     }
1603     break;
1604   case ISD::ADD:
1605     if (!CombinerEnabled) {
1606     if (N2.getOpcode() == ISD::FNEG)          // (A+ (-B) -> A-B
1607       return getNode(ISD::SUB, VT, N1, N2.getOperand(0));
1608     if (N1.getOpcode() == ISD::FNEG)          // ((-A)+B) -> B-A
1609       return getNode(ISD::SUB, VT, N2, N1.getOperand(0));
1610     if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1611         cast<ConstantSDNode>(N1.getOperand(0))->getValue() == 0)
1612       return getNode(ISD::SUB, VT, N2, N1.getOperand(1)); // (0-A)+B -> B-A
1613     if (N2.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N2.getOperand(0)) &&
1614         cast<ConstantSDNode>(N2.getOperand(0))->getValue() == 0)
1615       return getNode(ISD::SUB, VT, N1, N2.getOperand(1)); // A+(0-B) -> A-B
1616     if (N2.getOpcode() == ISD::SUB && N1 == N2.Val->getOperand(1) &&
1617         !MVT::isFloatingPoint(N2.getValueType()))
1618       return N2.Val->getOperand(0); // A+(B-A) -> B
1619     }
1620     break;
1621   case ISD::SUB:
1622     if (!CombinerEnabled) {
1623     if (N1.getOpcode() == ISD::ADD) {
1624       if (N1.Val->getOperand(0) == N2 &&
1625           !MVT::isFloatingPoint(N2.getValueType()))
1626         return N1.Val->getOperand(1);         // (A+B)-A == B
1627       if (N1.Val->getOperand(1) == N2 &&
1628           !MVT::isFloatingPoint(N2.getValueType()))
1629         return N1.Val->getOperand(0);         // (A+B)-B == A
1630     }
1631     if (N2.getOpcode() == ISD::FNEG)          // (A- (-B) -> A+B
1632       return getNode(ISD::ADD, VT, N1, N2.getOperand(0));
1633     }
1634     break;
1635   case ISD::FP_ROUND_INREG:
1636     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
1637     break;
1638   case ISD::SIGN_EXTEND_INREG: {
1639     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1640     if (EVT == VT) return N1;  // Not actually extending
1641     if (!CombinerEnabled) {
1642     // If we are sign extending an extension, use the original source.
1643     if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG ||
1644         N1.getOpcode() == ISD::AssertSext)
1645       if (cast<VTSDNode>(N1.getOperand(1))->getVT() <= EVT)
1646         return N1;
1647
1648     // If we are sign extending a sextload, return just the load.
1649     if (N1.getOpcode() == ISD::SEXTLOAD)
1650       if (cast<VTSDNode>(N1.getOperand(3))->getVT() <= EVT)
1651         return N1;    
1652
1653     // If we are extending the result of a setcc, and we already know the
1654     // contents of the top bits, eliminate the extension.
1655     if (N1.getOpcode() == ISD::SETCC &&
1656         TLI.getSetCCResultContents() ==
1657                         TargetLowering::ZeroOrNegativeOneSetCCResult)
1658       return N1;
1659     
1660     // If we are sign extending the result of an (and X, C) operation, and we
1661     // know the extended bits are zeros already, don't do the extend.
1662     if (N1.getOpcode() == ISD::AND)
1663       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
1664         uint64_t Mask = N1C->getValue();
1665         unsigned NumBits = MVT::getSizeInBits(EVT);
1666         if ((Mask & (~0ULL << (NumBits-1))) == 0)
1667           return N1;
1668       }
1669     }
1670     break;
1671   }
1672
1673   // FIXME: figure out how to safely handle things like
1674   // int foo(int x) { return 1 << (x & 255); }
1675   // int bar() { return foo(256); }
1676 #if 0
1677   case ISD::SHL:
1678   case ISD::SRL:
1679   case ISD::SRA:
1680     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
1681         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
1682       return getNode(Opcode, VT, N1, N2.getOperand(0));
1683     else if (N2.getOpcode() == ISD::AND)
1684       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
1685         // If the and is only masking out bits that cannot effect the shift,
1686         // eliminate the and.
1687         unsigned NumBits = MVT::getSizeInBits(VT);
1688         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
1689           return getNode(Opcode, VT, N1, N2.getOperand(0));
1690       }
1691     break;
1692 #endif
1693   }
1694
1695   // Memoize this node if possible.
1696   SDNode *N;
1697   if (Opcode != ISD::CALLSEQ_START && Opcode != ISD::CALLSEQ_END &&
1698       VT != MVT::Flag) {
1699     SDNode *&BON = BinaryOps[std::make_pair(Opcode, std::make_pair(N1, N2))];
1700     if (BON) return SDOperand(BON, 0);
1701
1702     BON = N = new SDNode(Opcode, N1, N2);
1703   } else {
1704     N = new SDNode(Opcode, N1, N2);
1705   }
1706
1707   N->setValueTypes(VT);
1708   AllNodes.push_back(N);
1709   return SDOperand(N, 0);
1710 }
1711
1712 // setAdjCallChain - This method changes the token chain of an
1713 // CALLSEQ_START/END node to be the specified operand.
1714 void SDNode::setAdjCallChain(SDOperand N) {
1715   assert(N.getValueType() == MVT::Other);
1716   assert((getOpcode() == ISD::CALLSEQ_START ||
1717           getOpcode() == ISD::CALLSEQ_END) && "Cannot adjust this node!");
1718
1719   Operands[0].Val->removeUser(this);
1720   Operands[0] = N;
1721   N.Val->Uses.push_back(this);
1722 }
1723
1724
1725
1726 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
1727                                 SDOperand Chain, SDOperand Ptr,
1728                                 SDOperand SV) {
1729   SDNode *&N = Loads[std::make_pair(Ptr, std::make_pair(Chain, VT))];
1730   if (N) return SDOperand(N, 0);
1731   N = new SDNode(ISD::LOAD, Chain, Ptr, SV);
1732
1733   // Loads have a token chain.
1734   N->setValueTypes(VT, MVT::Other);
1735   AllNodes.push_back(N);
1736   return SDOperand(N, 0);
1737 }
1738
1739
1740 SDOperand SelectionDAG::getExtLoad(unsigned Opcode, MVT::ValueType VT,
1741                                    SDOperand Chain, SDOperand Ptr, SDOperand SV,
1742                                    MVT::ValueType EVT) {
1743   std::vector<SDOperand> Ops;
1744   Ops.reserve(4);
1745   Ops.push_back(Chain);
1746   Ops.push_back(Ptr);
1747   Ops.push_back(SV);
1748   Ops.push_back(getValueType(EVT));
1749   std::vector<MVT::ValueType> VTs;
1750   VTs.reserve(2);
1751   VTs.push_back(VT); VTs.push_back(MVT::Other);  // Add token chain.
1752   return getNode(Opcode, VTs, Ops);
1753 }
1754
1755 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1756                                 SDOperand N1, SDOperand N2, SDOperand N3) {
1757   // Perform various simplifications.
1758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1759   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1760   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.Val);
1761   switch (Opcode) {
1762   case ISD::SETCC: {
1763     // Use SimplifySetCC  to simplify SETCC's.
1764     SDOperand Simp = SimplifySetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
1765     if (Simp.Val) return Simp;
1766     break;
1767   }
1768   case ISD::SELECT:
1769     if (N1C)
1770       if (N1C->getValue())
1771         return N2;             // select true, X, Y -> X
1772       else
1773         return N3;             // select false, X, Y -> Y
1774
1775     if (N2 == N3) return N2;   // select C, X, X -> X
1776
1777     if (VT == MVT::i1) {  // Boolean SELECT
1778       if (N2C) {
1779         if (N2C->getValue())   // select C, 1, X -> C | X
1780           return getNode(ISD::OR, VT, N1, N3);
1781         else                   // select C, 0, X -> ~C & X
1782           return getNode(ISD::AND, VT,
1783                          getNode(ISD::XOR, N1.getValueType(), N1,
1784                                  getConstant(1, N1.getValueType())), N3);
1785       } else if (N3C) {
1786         if (N3C->getValue())   // select C, X, 1 -> ~C | X
1787           return getNode(ISD::OR, VT,
1788                          getNode(ISD::XOR, N1.getValueType(), N1,
1789                                  getConstant(1, N1.getValueType())), N2);
1790         else                   // select C, X, 0 -> C & X
1791           return getNode(ISD::AND, VT, N1, N2);
1792       }
1793
1794       if (N1 == N2)   // X ? X : Y --> X ? 1 : Y --> X | Y
1795         return getNode(ISD::OR, VT, N1, N3);
1796       if (N1 == N3)   // X ? Y : X --> X ? Y : 0 --> X & Y
1797         return getNode(ISD::AND, VT, N1, N2);
1798     }
1799     if (N1.getOpcode() == ISD::SETCC) {
1800       SDOperand Simp = SimplifySelectCC(N1.getOperand(0), N1.getOperand(1), N2, 
1801                              N3, cast<CondCodeSDNode>(N1.getOperand(2))->get());
1802       if (Simp.Val) return Simp;
1803     }
1804     break;
1805   case ISD::BRCOND:
1806     if (N2C)
1807       if (N2C->getValue()) // Unconditional branch
1808         return getNode(ISD::BR, MVT::Other, N1, N3);
1809       else
1810         return N1;         // Never-taken branch
1811     break;
1812   }
1813
1814   std::vector<SDOperand> Ops;
1815   Ops.reserve(3);
1816   Ops.push_back(N1);
1817   Ops.push_back(N2);
1818   Ops.push_back(N3);
1819
1820   // Memoize node if it doesn't produce a flag.
1821   SDNode *N;
1822   if (VT != MVT::Flag) {
1823     SDNode *&E = OneResultNodes[std::make_pair(Opcode,std::make_pair(VT, Ops))];
1824     if (E) return SDOperand(E, 0);
1825     E = N = new SDNode(Opcode, N1, N2, N3);
1826   } else {
1827     N = new SDNode(Opcode, N1, N2, N3);
1828   }
1829   N->setValueTypes(VT);
1830   AllNodes.push_back(N);
1831   return SDOperand(N, 0);
1832 }
1833
1834 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1835                                 SDOperand N1, SDOperand N2, SDOperand N3,
1836                                 SDOperand N4) {
1837   std::vector<SDOperand> Ops;
1838   Ops.reserve(4);
1839   Ops.push_back(N1);
1840   Ops.push_back(N2);
1841   Ops.push_back(N3);
1842   Ops.push_back(N4);
1843   return getNode(Opcode, VT, Ops);
1844 }
1845
1846 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1847                                 SDOperand N1, SDOperand N2, SDOperand N3,
1848                                 SDOperand N4, SDOperand N5) {
1849   std::vector<SDOperand> Ops;
1850   Ops.reserve(5);
1851   Ops.push_back(N1);
1852   Ops.push_back(N2);
1853   Ops.push_back(N3);
1854   Ops.push_back(N4);
1855   Ops.push_back(N5);
1856   return getNode(Opcode, VT, Ops);
1857 }
1858
1859
1860 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
1861   assert((!V || isa<PointerType>(V->getType())) &&
1862          "SrcValue is not a pointer?");
1863   SDNode *&N = ValueNodes[std::make_pair(V, Offset)];
1864   if (N) return SDOperand(N, 0);
1865
1866   N = new SrcValueSDNode(V, Offset);
1867   AllNodes.push_back(N);
1868   return SDOperand(N, 0);
1869 }
1870
1871 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1872                                 std::vector<SDOperand> &Ops) {
1873   switch (Ops.size()) {
1874   case 0: return getNode(Opcode, VT);
1875   case 1: return getNode(Opcode, VT, Ops[0]);
1876   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
1877   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
1878   default: break;
1879   }
1880
1881   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(Ops[1].Val);
1882   switch (Opcode) {
1883   default: break;
1884   case ISD::BRCONDTWOWAY:
1885     if (N1C)
1886       if (N1C->getValue()) // Unconditional branch to true dest.
1887         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[2]);
1888       else                 // Unconditional branch to false dest.
1889         return getNode(ISD::BR, MVT::Other, Ops[0], Ops[3]);
1890     break;
1891   case ISD::BRTWOWAY_CC:
1892     assert(Ops.size() == 6 && "BRTWOWAY_CC takes 6 operands!");
1893     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1894            "LHS and RHS of comparison must have same type!");
1895     break;
1896   case ISD::TRUNCSTORE: {
1897     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1898     MVT::ValueType EVT = cast<VTSDNode>(Ops[4])->getVT();
1899 #if 0 // FIXME: If the target supports EVT natively, convert to a truncate/store
1900     // If this is a truncating store of a constant, convert to the desired type
1901     // and store it instead.
1902     if (isa<Constant>(Ops[0])) {
1903       SDOperand Op = getNode(ISD::TRUNCATE, EVT, N1);
1904       if (isa<Constant>(Op))
1905         N1 = Op;
1906     }
1907     // Also for ConstantFP?
1908 #endif
1909     if (Ops[0].getValueType() == EVT)       // Normal store?
1910       return getNode(ISD::STORE, VT, Ops[0], Ops[1], Ops[2], Ops[3]);
1911     assert(Ops[1].getValueType() > EVT && "Not a truncation?");
1912     assert(MVT::isInteger(Ops[1].getValueType()) == MVT::isInteger(EVT) &&
1913            "Can't do FP-INT conversion!");
1914     break;
1915   }
1916   case ISD::SELECT_CC: {
1917     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1918     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
1919            "LHS and RHS of condition must have same type!");
1920     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1921            "True and False arms of SelectCC must have same type!");
1922     assert(Ops[2].getValueType() == VT &&
1923            "select_cc node must be of same type as true and false value!");
1924     SDOperand Simp = SimplifySelectCC(Ops[0], Ops[1], Ops[2], Ops[3], 
1925                                       cast<CondCodeSDNode>(Ops[4])->get());
1926     if (Simp.Val) return Simp;
1927     break;
1928   }
1929   case ISD::BR_CC: {
1930     assert(Ops.size() == 5 && "TRUNCSTORE takes 5 operands!");
1931     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
1932            "LHS/RHS of comparison should match types!");
1933     // Use SimplifySetCC  to simplify SETCC's.
1934     SDOperand Simp = SimplifySetCC(MVT::i1, Ops[2], Ops[3],
1935                                    cast<CondCodeSDNode>(Ops[1])->get());
1936     if (Simp.Val) {
1937       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Simp)) {
1938         if (C->getValue() & 1) // Unconditional branch
1939           return getNode(ISD::BR, MVT::Other, Ops[0], Ops[4]);
1940         else
1941           return Ops[0];          // Unconditional Fall through
1942       } else if (Simp.Val->getOpcode() == ISD::SETCC) {
1943         Ops[2] = Simp.getOperand(0);
1944         Ops[3] = Simp.getOperand(1);
1945         Ops[1] = Simp.getOperand(2);
1946       }
1947     }
1948     break;
1949   }
1950   }
1951
1952   // Memoize nodes.
1953   SDNode *N;
1954   if (VT != MVT::Flag) {
1955     SDNode *&E =
1956       OneResultNodes[std::make_pair(Opcode, std::make_pair(VT, Ops))];
1957     if (E) return SDOperand(E, 0);
1958     E = N = new SDNode(Opcode, Ops);
1959   } else {
1960     N = new SDNode(Opcode, Ops);
1961   }
1962   N->setValueTypes(VT);
1963   AllNodes.push_back(N);
1964   return SDOperand(N, 0);
1965 }
1966
1967 SDOperand SelectionDAG::getNode(unsigned Opcode,
1968                                 std::vector<MVT::ValueType> &ResultTys,
1969                                 std::vector<SDOperand> &Ops) {
1970   if (ResultTys.size() == 1)
1971     return getNode(Opcode, ResultTys[0], Ops);
1972
1973   switch (Opcode) {
1974   case ISD::EXTLOAD:
1975   case ISD::SEXTLOAD:
1976   case ISD::ZEXTLOAD: {
1977     MVT::ValueType EVT = cast<VTSDNode>(Ops[3])->getVT();
1978     assert(Ops.size() == 4 && ResultTys.size() == 2 && "Bad *EXTLOAD!");
1979     // If they are asking for an extending load from/to the same thing, return a
1980     // normal load.
1981     if (ResultTys[0] == EVT)
1982       return getLoad(ResultTys[0], Ops[0], Ops[1], Ops[2]);
1983     assert(EVT < ResultTys[0] &&
1984            "Should only be an extending load, not truncating!");
1985     assert((Opcode == ISD::EXTLOAD || MVT::isInteger(ResultTys[0])) &&
1986            "Cannot sign/zero extend a FP load!");
1987     assert(MVT::isInteger(ResultTys[0]) == MVT::isInteger(EVT) &&
1988            "Cannot convert from FP to Int or Int -> FP!");
1989     break;
1990   }
1991
1992   // FIXME: figure out how to safely handle things like
1993   // int foo(int x) { return 1 << (x & 255); }
1994   // int bar() { return foo(256); }
1995 #if 0
1996   case ISD::SRA_PARTS:
1997   case ISD::SRL_PARTS:
1998   case ISD::SHL_PARTS:
1999     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2000         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2001       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2002     else if (N3.getOpcode() == ISD::AND)
2003       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2004         // If the and is only masking out bits that cannot effect the shift,
2005         // eliminate the and.
2006         unsigned NumBits = MVT::getSizeInBits(VT)*2;
2007         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2008           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2009       }
2010     break;
2011 #endif
2012   }
2013
2014   // Memoize the node unless it returns a flag.
2015   SDNode *N;
2016   if (ResultTys.back() != MVT::Flag) {
2017     SDNode *&E =
2018       ArbitraryNodes[std::make_pair(Opcode, std::make_pair(ResultTys, Ops))];
2019     if (E) return SDOperand(E, 0);
2020     E = N = new SDNode(Opcode, Ops);
2021   } else {
2022     N = new SDNode(Opcode, Ops);
2023   }
2024   N->setValueTypes(ResultTys);
2025   AllNodes.push_back(N);
2026   return SDOperand(N, 0);
2027 }
2028
2029
2030 /// SelectNodeTo - These are used for target selectors to *mutate* the
2031 /// specified node to have the specified return type, Target opcode, and
2032 /// operands.  Note that target opcodes are stored as
2033 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2034 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2035                                 MVT::ValueType VT) {
2036   RemoveNodeFromCSEMaps(N);
2037   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2038   N->setValueTypes(VT);
2039 }
2040 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2041                                 MVT::ValueType VT, SDOperand Op1) {
2042   RemoveNodeFromCSEMaps(N);
2043   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2044   N->setValueTypes(VT);
2045   N->setOperands(Op1);
2046 }
2047 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2048                                 MVT::ValueType VT, SDOperand Op1,
2049                                 SDOperand Op2) {
2050   RemoveNodeFromCSEMaps(N);
2051   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2052   N->setValueTypes(VT);
2053   N->setOperands(Op1, Op2);
2054 }
2055 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
2056                                 MVT::ValueType VT1, MVT::ValueType VT2,
2057                                 SDOperand Op1, SDOperand Op2) {
2058   RemoveNodeFromCSEMaps(N);
2059   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2060   N->setValueTypes(VT1, VT2);
2061   N->setOperands(Op1, Op2);
2062 }
2063 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2064                                 MVT::ValueType VT, SDOperand Op1,
2065                                 SDOperand Op2, SDOperand Op3) {
2066   RemoveNodeFromCSEMaps(N);
2067   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2068   N->setValueTypes(VT);
2069   N->setOperands(Op1, Op2, Op3);
2070 }
2071 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2072                                 MVT::ValueType VT1, MVT::ValueType VT2,
2073                                 SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2074   RemoveNodeFromCSEMaps(N);
2075   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2076   N->setValueTypes(VT1, VT2);
2077   N->setOperands(Op1, Op2, Op3);
2078 }
2079
2080 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2081                                 MVT::ValueType VT, SDOperand Op1,
2082                                 SDOperand Op2, SDOperand Op3, SDOperand Op4) {
2083   RemoveNodeFromCSEMaps(N);
2084   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2085   N->setValueTypes(VT);
2086   N->setOperands(Op1, Op2, Op3, Op4);
2087 }
2088 void SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2089                                 MVT::ValueType VT, SDOperand Op1,
2090                                 SDOperand Op2, SDOperand Op3, SDOperand Op4,
2091                                 SDOperand Op5) {
2092   RemoveNodeFromCSEMaps(N);
2093   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc);
2094   N->setValueTypes(VT);
2095   N->setOperands(Op1, Op2, Op3, Op4, Op5);
2096 }
2097
2098 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2099 /// This can cause recursive merging of nodes in the DAG.
2100 ///
2101 /// This version assumes From/To have a single result value.
2102 ///
2103 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
2104                                       std::vector<SDNode*> *Deleted) {
2105   SDNode *From = FromN.Val, *To = ToN.Val;
2106   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
2107          "Cannot replace with this method!");
2108   assert(From != To && "Cannot replace uses of with self");
2109   
2110   while (!From->use_empty()) {
2111     // Process users until they are all gone.
2112     SDNode *U = *From->use_begin();
2113     
2114     // This node is about to morph, remove its old self from the CSE maps.
2115     RemoveNodeFromCSEMaps(U);
2116     
2117     for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
2118       if (U->getOperand(i).Val == From) {
2119         From->removeUser(U);
2120         U->Operands[i].Val = To;
2121         To->addUser(U);
2122       }
2123
2124     // Now that we have modified U, add it back to the CSE maps.  If it already
2125     // exists there, recursively merge the results together.
2126     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2127       ReplaceAllUsesWith(U, Existing, Deleted);
2128       // U is now dead.
2129       if (Deleted) Deleted->push_back(U);
2130       DeleteNodeNotInCSEMaps(U);
2131     }
2132   }
2133 }
2134
2135 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2136 /// This can cause recursive merging of nodes in the DAG.
2137 ///
2138 /// This version assumes From/To have matching types and numbers of result
2139 /// values.
2140 ///
2141 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
2142                                       std::vector<SDNode*> *Deleted) {
2143   assert(From != To && "Cannot replace uses of with self");
2144   assert(From->getNumValues() == To->getNumValues() &&
2145          "Cannot use this version of ReplaceAllUsesWith!");
2146   if (From->getNumValues() == 1) {  // If possible, use the faster version.
2147     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
2148     return;
2149   }
2150   
2151   while (!From->use_empty()) {
2152     // Process users until they are all gone.
2153     SDNode *U = *From->use_begin();
2154     
2155     // This node is about to morph, remove its old self from the CSE maps.
2156     RemoveNodeFromCSEMaps(U);
2157     
2158     for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
2159       if (U->getOperand(i).Val == From) {
2160         From->removeUser(U);
2161         U->Operands[i].Val = To;
2162         To->addUser(U);
2163       }
2164         
2165     // Now that we have modified U, add it back to the CSE maps.  If it already
2166     // exists there, recursively merge the results together.
2167     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2168       ReplaceAllUsesWith(U, Existing, Deleted);
2169       // U is now dead.
2170       if (Deleted) Deleted->push_back(U);
2171       DeleteNodeNotInCSEMaps(U);
2172     }
2173   }
2174 }
2175
2176 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
2177 /// This can cause recursive merging of nodes in the DAG.
2178 ///
2179 /// This version can replace From with any result values.  To must match the
2180 /// number and types of values returned by From.
2181 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
2182                                       const std::vector<SDOperand> &To,
2183                                       std::vector<SDNode*> *Deleted) {
2184   assert(From->getNumValues() == To.size() &&
2185          "Incorrect number of values to replace with!");
2186   if (To.size() == 1 && To[0].Val->getNumValues() == 1) {
2187     // Degenerate case handled above.
2188     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
2189     return;
2190   }
2191
2192   while (!From->use_empty()) {
2193     // Process users until they are all gone.
2194     SDNode *U = *From->use_begin();
2195     
2196     // This node is about to morph, remove its old self from the CSE maps.
2197     RemoveNodeFromCSEMaps(U);
2198     
2199     for (unsigned i = 0, e = U->getNumOperands(); i != e; ++i)
2200       if (U->getOperand(i).Val == From) {
2201         const SDOperand &ToOp = To[U->getOperand(i).ResNo];
2202         From->removeUser(U);
2203         U->Operands[i] = ToOp;
2204         ToOp.Val->addUser(U);
2205       }
2206         
2207     // Now that we have modified U, add it back to the CSE maps.  If it already
2208     // exists there, recursively merge the results together.
2209     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
2210       ReplaceAllUsesWith(U, Existing, Deleted);
2211       // U is now dead.
2212       if (Deleted) Deleted->push_back(U);
2213       DeleteNodeNotInCSEMaps(U);
2214     }
2215   }
2216 }
2217
2218
2219 //===----------------------------------------------------------------------===//
2220 //                              SDNode Class
2221 //===----------------------------------------------------------------------===//
2222
2223 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
2224 /// indicated value.  This method ignores uses of other values defined by this
2225 /// operation.
2226 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) {
2227   assert(Value < getNumValues() && "Bad value!");
2228
2229   // If there is only one value, this is easy.
2230   if (getNumValues() == 1)
2231     return use_size() == NUses;
2232   if (Uses.size() < NUses) return false;
2233
2234   SDOperand TheValue(this, Value);
2235
2236   std::set<SDNode*> UsersHandled;
2237
2238   for (std::vector<SDNode*>::iterator UI = Uses.begin(), E = Uses.end();
2239        UI != E; ++UI) {
2240     SDNode *User = *UI;
2241     if (User->getNumOperands() == 1 ||
2242         UsersHandled.insert(User).second)     // First time we've seen this?
2243       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
2244         if (User->getOperand(i) == TheValue) {
2245           if (NUses == 0)
2246             return false;   // too many uses
2247           --NUses;
2248         }
2249   }
2250
2251   // Found exactly the right number of uses?
2252   return NUses == 0;
2253 }
2254
2255
2256 const char *SDNode::getOperationName(const SelectionDAG *G) const {
2257   switch (getOpcode()) {
2258   default:
2259     if (getOpcode() < ISD::BUILTIN_OP_END)
2260       return "<<Unknown DAG Node>>";
2261     else {
2262       if (G)
2263         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
2264           return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
2265       return "<<Unknown Target Node>>";
2266     }
2267    
2268   case ISD::PCMARKER:      return "PCMarker";
2269   case ISD::SRCVALUE:      return "SrcValue";
2270   case ISD::VALUETYPE:     return "ValueType";
2271   case ISD::EntryToken:    return "EntryToken";
2272   case ISD::TokenFactor:   return "TokenFactor";
2273   case ISD::AssertSext:    return "AssertSext";
2274   case ISD::AssertZext:    return "AssertZext";
2275   case ISD::Constant:      return "Constant";
2276   case ISD::TargetConstant: return "TargetConstant";
2277   case ISD::ConstantFP:    return "ConstantFP";
2278   case ISD::GlobalAddress: return "GlobalAddress";
2279   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
2280   case ISD::FrameIndex:    return "FrameIndex";
2281   case ISD::TargetFrameIndex: return "TargetFrameIndex";
2282   case ISD::BasicBlock:    return "BasicBlock";
2283   case ISD::Register:      return "Register";
2284   case ISD::ExternalSymbol: return "ExternalSymbol";
2285   case ISD::ConstantPool:  return "ConstantPool";
2286   case ISD::TargetConstantPool:  return "TargetConstantPool";
2287   case ISD::CopyToReg:     return "CopyToReg";
2288   case ISD::CopyFromReg:   return "CopyFromReg";
2289   case ISD::ImplicitDef:   return "ImplicitDef";
2290   case ISD::UNDEF:         return "undef";
2291
2292   // Unary operators
2293   case ISD::FABS:   return "fabs";
2294   case ISD::FNEG:   return "fneg";
2295   case ISD::FSQRT:  return "fsqrt";
2296   case ISD::FSIN:   return "fsin";
2297   case ISD::FCOS:   return "fcos";
2298
2299   // Binary operators
2300   case ISD::ADD:    return "add";
2301   case ISD::SUB:    return "sub";
2302   case ISD::MUL:    return "mul";
2303   case ISD::MULHU:  return "mulhu";
2304   case ISD::MULHS:  return "mulhs";
2305   case ISD::SDIV:   return "sdiv";
2306   case ISD::UDIV:   return "udiv";
2307   case ISD::SREM:   return "srem";
2308   case ISD::UREM:   return "urem";
2309   case ISD::AND:    return "and";
2310   case ISD::OR:     return "or";
2311   case ISD::XOR:    return "xor";
2312   case ISD::SHL:    return "shl";
2313   case ISD::SRA:    return "sra";
2314   case ISD::SRL:    return "srl";
2315
2316   case ISD::SETCC:       return "setcc";
2317   case ISD::SELECT:      return "select";
2318   case ISD::SELECT_CC:   return "select_cc";
2319   case ISD::ADD_PARTS:   return "add_parts";
2320   case ISD::SUB_PARTS:   return "sub_parts";
2321   case ISD::SHL_PARTS:   return "shl_parts";
2322   case ISD::SRA_PARTS:   return "sra_parts";
2323   case ISD::SRL_PARTS:   return "srl_parts";
2324
2325   // Conversion operators.
2326   case ISD::SIGN_EXTEND: return "sign_extend";
2327   case ISD::ZERO_EXTEND: return "zero_extend";
2328   case ISD::ANY_EXTEND:  return "any_extend";
2329   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
2330   case ISD::TRUNCATE:    return "truncate";
2331   case ISD::FP_ROUND:    return "fp_round";
2332   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
2333   case ISD::FP_EXTEND:   return "fp_extend";
2334
2335   case ISD::SINT_TO_FP:  return "sint_to_fp";
2336   case ISD::UINT_TO_FP:  return "uint_to_fp";
2337   case ISD::FP_TO_SINT:  return "fp_to_sint";
2338   case ISD::FP_TO_UINT:  return "fp_to_uint";
2339
2340     // Control flow instructions
2341   case ISD::BR:      return "br";
2342   case ISD::BRCOND:  return "brcond";
2343   case ISD::BRCONDTWOWAY:  return "brcondtwoway";
2344   case ISD::BR_CC:  return "br_cc";
2345   case ISD::BRTWOWAY_CC:  return "brtwoway_cc";
2346   case ISD::RET:     return "ret";
2347   case ISD::CALL:    return "call";
2348   case ISD::TAILCALL:return "tailcall";
2349   case ISD::CALLSEQ_START:  return "callseq_start";
2350   case ISD::CALLSEQ_END:    return "callseq_end";
2351
2352     // Other operators
2353   case ISD::LOAD:    return "load";
2354   case ISD::STORE:   return "store";
2355   case ISD::EXTLOAD:    return "extload";
2356   case ISD::SEXTLOAD:   return "sextload";
2357   case ISD::ZEXTLOAD:   return "zextload";
2358   case ISD::TRUNCSTORE: return "truncstore";
2359
2360   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
2361   case ISD::EXTRACT_ELEMENT: return "extract_element";
2362   case ISD::BUILD_PAIR: return "build_pair";
2363   case ISD::MEMSET:  return "memset";
2364   case ISD::MEMCPY:  return "memcpy";
2365   case ISD::MEMMOVE: return "memmove";
2366
2367   // Bit counting
2368   case ISD::CTPOP:   return "ctpop";
2369   case ISD::CTTZ:    return "cttz";
2370   case ISD::CTLZ:    return "ctlz";
2371
2372   // IO Intrinsics
2373   case ISD::READPORT: return "readport";
2374   case ISD::WRITEPORT: return "writeport";
2375   case ISD::READIO: return "readio";
2376   case ISD::WRITEIO: return "writeio";
2377
2378   case ISD::CONDCODE:
2379     switch (cast<CondCodeSDNode>(this)->get()) {
2380     default: assert(0 && "Unknown setcc condition!");
2381     case ISD::SETOEQ:  return "setoeq";
2382     case ISD::SETOGT:  return "setogt";
2383     case ISD::SETOGE:  return "setoge";
2384     case ISD::SETOLT:  return "setolt";
2385     case ISD::SETOLE:  return "setole";
2386     case ISD::SETONE:  return "setone";
2387
2388     case ISD::SETO:    return "seto";
2389     case ISD::SETUO:   return "setuo";
2390     case ISD::SETUEQ:  return "setue";
2391     case ISD::SETUGT:  return "setugt";
2392     case ISD::SETUGE:  return "setuge";
2393     case ISD::SETULT:  return "setult";
2394     case ISD::SETULE:  return "setule";
2395     case ISD::SETUNE:  return "setune";
2396
2397     case ISD::SETEQ:   return "seteq";
2398     case ISD::SETGT:   return "setgt";
2399     case ISD::SETGE:   return "setge";
2400     case ISD::SETLT:   return "setlt";
2401     case ISD::SETLE:   return "setle";
2402     case ISD::SETNE:   return "setne";
2403     }
2404   }
2405 }
2406
2407 void SDNode::dump() const { dump(0); }
2408 void SDNode::dump(const SelectionDAG *G) const {
2409   std::cerr << (void*)this << ": ";
2410
2411   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
2412     if (i) std::cerr << ",";
2413     if (getValueType(i) == MVT::Other)
2414       std::cerr << "ch";
2415     else
2416       std::cerr << MVT::getValueTypeString(getValueType(i));
2417   }
2418   std::cerr << " = " << getOperationName(G);
2419
2420   std::cerr << " ";
2421   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
2422     if (i) std::cerr << ", ";
2423     std::cerr << (void*)getOperand(i).Val;
2424     if (unsigned RN = getOperand(i).ResNo)
2425       std::cerr << ":" << RN;
2426   }
2427
2428   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
2429     std::cerr << "<" << CSDN->getValue() << ">";
2430   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
2431     std::cerr << "<" << CSDN->getValue() << ">";
2432   } else if (const GlobalAddressSDNode *GADN =
2433              dyn_cast<GlobalAddressSDNode>(this)) {
2434     std::cerr << "<";
2435     WriteAsOperand(std::cerr, GADN->getGlobal()) << ">";
2436   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
2437     std::cerr << "<" << FIDN->getIndex() << ">";
2438   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
2439     std::cerr << "<" << *CP->get() << ">";
2440   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
2441     std::cerr << "<";
2442     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
2443     if (LBB)
2444       std::cerr << LBB->getName() << " ";
2445     std::cerr << (const void*)BBDN->getBasicBlock() << ">";
2446   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
2447     if (G && MRegisterInfo::isPhysicalRegister(R->getReg())) {
2448       std::cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
2449     } else {
2450       std::cerr << " #" << R->getReg();
2451     }
2452   } else if (const ExternalSymbolSDNode *ES =
2453              dyn_cast<ExternalSymbolSDNode>(this)) {
2454     std::cerr << "'" << ES->getSymbol() << "'";
2455   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
2456     if (M->getValue())
2457       std::cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
2458     else
2459       std::cerr << "<null:" << M->getOffset() << ">";
2460   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
2461     std::cerr << ":" << getValueTypeString(N->getVT());
2462   }
2463 }
2464
2465 static void DumpNodes(SDNode *N, unsigned indent, const SelectionDAG *G) {
2466   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
2467     if (N->getOperand(i).Val->hasOneUse())
2468       DumpNodes(N->getOperand(i).Val, indent+2, G);
2469     else
2470       std::cerr << "\n" << std::string(indent+2, ' ')
2471                 << (void*)N->getOperand(i).Val << ": <multiple use>";
2472
2473
2474   std::cerr << "\n" << std::string(indent, ' ');
2475   N->dump(G);
2476 }
2477
2478 void SelectionDAG::dump() const {
2479   std::cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
2480   std::vector<SDNode*> Nodes(AllNodes);
2481   std::sort(Nodes.begin(), Nodes.end());
2482
2483   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
2484     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
2485       DumpNodes(Nodes[i], 2, this);
2486   }
2487
2488   DumpNodes(getRoot().Val, 2, this);
2489
2490   std::cerr << "\n\n";
2491 }
2492