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