Do not hide APInt::dump() inside #ifndef NDEBUG.
[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/GlobalVariable.h"
17 #include "llvm/Intrinsics.h"
18 #include "llvm/DerivedTypes.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "llvm/CodeGen/MachineBasicBlock.h"
21 #include "llvm/CodeGen/MachineConstantPool.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Target/MRegisterInfo.h"
24 #include "llvm/Target/TargetData.h"
25 #include "llvm/Target/TargetLowering.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/ADT/SetVector.h"
29 #include "llvm/ADT/SmallPtrSet.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringExtras.h"
32 #include <algorithm>
33 #include <cmath>
34 using namespace llvm;
35
36 /// makeVTList - Return an instance of the SDVTList struct initialized with the
37 /// specified members.
38 static SDVTList makeVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
39   SDVTList Res = {VTs, NumVTs};
40   return Res;
41 }
42
43 //===----------------------------------------------------------------------===//
44 //                              ConstantFPSDNode Class
45 //===----------------------------------------------------------------------===//
46
47 /// isExactlyValue - We don't rely on operator== working on double values, as
48 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
49 /// As such, this method can be used to do an exact bit-for-bit comparison of
50 /// two floating point values.
51 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
52   return Value.bitwiseIsEqual(V);
53 }
54
55 bool ConstantFPSDNode::isValueValidForType(MVT::ValueType VT, 
56                                            const APFloat& Val) {
57   // convert modifies in place, so make a copy.
58   APFloat Val2 = APFloat(Val);
59   switch (VT) {
60   default:
61     return false;         // These can't be represented as floating point!
62
63   // FIXME rounding mode needs to be more flexible
64   case MVT::f32:
65     return &Val2.getSemantics() == &APFloat::IEEEsingle ||
66            Val2.convert(APFloat::IEEEsingle, APFloat::rmNearestTiesToEven) == 
67               APFloat::opOK;
68   case MVT::f64:
69     return &Val2.getSemantics() == &APFloat::IEEEsingle || 
70            &Val2.getSemantics() == &APFloat::IEEEdouble ||
71            Val2.convert(APFloat::IEEEdouble, APFloat::rmNearestTiesToEven) == 
72              APFloat::opOK;
73   // TODO: Figure out how to test if we can use a shorter type instead!
74   case MVT::f80:
75   case MVT::f128:
76   case MVT::ppcf128:
77     return true;
78   }
79 }
80
81 //===----------------------------------------------------------------------===//
82 //                              ISD Namespace
83 //===----------------------------------------------------------------------===//
84
85 /// isBuildVectorAllOnes - Return true if the specified node is a
86 /// BUILD_VECTOR where all of the elements are ~0 or undef.
87 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
88   // Look through a bit convert.
89   if (N->getOpcode() == ISD::BIT_CONVERT)
90     N = N->getOperand(0).Val;
91   
92   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
93   
94   unsigned i = 0, e = N->getNumOperands();
95   
96   // Skip over all of the undef values.
97   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
98     ++i;
99   
100   // Do not accept an all-undef vector.
101   if (i == e) return false;
102   
103   // Do not accept build_vectors that aren't all constants or which have non-~0
104   // elements.
105   SDOperand NotZero = N->getOperand(i);
106   if (isa<ConstantSDNode>(NotZero)) {
107     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
108       return false;
109   } else if (isa<ConstantFPSDNode>(NotZero)) {
110     MVT::ValueType VT = NotZero.getValueType();
111     if (VT== MVT::f64) {
112       if (((cast<ConstantFPSDNode>(NotZero)->getValueAPF().
113                   convertToAPInt().getZExtValue())) != (uint64_t)-1)
114         return false;
115     } else {
116       if ((uint32_t)cast<ConstantFPSDNode>(NotZero)->
117                       getValueAPF().convertToAPInt().getZExtValue() != 
118           (uint32_t)-1)
119         return false;
120     }
121   } else
122     return false;
123   
124   // Okay, we have at least one ~0 value, check to see if the rest match or are
125   // undefs.
126   for (++i; i != e; ++i)
127     if (N->getOperand(i) != NotZero &&
128         N->getOperand(i).getOpcode() != ISD::UNDEF)
129       return false;
130   return true;
131 }
132
133
134 /// isBuildVectorAllZeros - Return true if the specified node is a
135 /// BUILD_VECTOR where all of the elements are 0 or undef.
136 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
137   // Look through a bit convert.
138   if (N->getOpcode() == ISD::BIT_CONVERT)
139     N = N->getOperand(0).Val;
140   
141   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
142   
143   unsigned i = 0, e = N->getNumOperands();
144   
145   // Skip over all of the undef values.
146   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
147     ++i;
148   
149   // Do not accept an all-undef vector.
150   if (i == e) return false;
151   
152   // Do not accept build_vectors that aren't all constants or which have non-~0
153   // elements.
154   SDOperand Zero = N->getOperand(i);
155   if (isa<ConstantSDNode>(Zero)) {
156     if (!cast<ConstantSDNode>(Zero)->isNullValue())
157       return false;
158   } else if (isa<ConstantFPSDNode>(Zero)) {
159     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
160       return false;
161   } else
162     return false;
163   
164   // Okay, we have at least one ~0 value, check to see if the rest match or are
165   // undefs.
166   for (++i; i != e; ++i)
167     if (N->getOperand(i) != Zero &&
168         N->getOperand(i).getOpcode() != ISD::UNDEF)
169       return false;
170   return true;
171 }
172
173 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
174 /// when given the operation for (X op Y).
175 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
176   // To perform this operation, we just need to swap the L and G bits of the
177   // operation.
178   unsigned OldL = (Operation >> 2) & 1;
179   unsigned OldG = (Operation >> 1) & 1;
180   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
181                        (OldL << 1) |       // New G bit
182                        (OldG << 2));        // New L bit.
183 }
184
185 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
186 /// 'op' is a valid SetCC operation.
187 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
188   unsigned Operation = Op;
189   if (isInteger)
190     Operation ^= 7;   // Flip L, G, E bits, but not U.
191   else
192     Operation ^= 15;  // Flip all of the condition bits.
193   if (Operation > ISD::SETTRUE2)
194     Operation &= ~8;     // Don't let N and U bits get set.
195   return ISD::CondCode(Operation);
196 }
197
198
199 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
200 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
201 /// if the operation does not depend on the sign of the input (setne and seteq).
202 static int isSignedOp(ISD::CondCode Opcode) {
203   switch (Opcode) {
204   default: assert(0 && "Illegal integer setcc operation!");
205   case ISD::SETEQ:
206   case ISD::SETNE: return 0;
207   case ISD::SETLT:
208   case ISD::SETLE:
209   case ISD::SETGT:
210   case ISD::SETGE: return 1;
211   case ISD::SETULT:
212   case ISD::SETULE:
213   case ISD::SETUGT:
214   case ISD::SETUGE: return 2;
215   }
216 }
217
218 /// getSetCCOrOperation - Return the result of a logical OR between different
219 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
220 /// returns SETCC_INVALID if it is not possible to represent the resultant
221 /// comparison.
222 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
223                                        bool isInteger) {
224   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
225     // Cannot fold a signed integer setcc with an unsigned integer setcc.
226     return ISD::SETCC_INVALID;
227
228   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
229
230   // If the N and U bits get set then the resultant comparison DOES suddenly
231   // care about orderedness, and is true when ordered.
232   if (Op > ISD::SETTRUE2)
233     Op &= ~16;     // Clear the U bit if the N bit is set.
234   
235   // Canonicalize illegal integer setcc's.
236   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
237     Op = ISD::SETNE;
238   
239   return ISD::CondCode(Op);
240 }
241
242 /// getSetCCAndOperation - Return the result of a logical AND between different
243 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
244 /// function returns zero if it is not possible to represent the resultant
245 /// comparison.
246 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
247                                         bool isInteger) {
248   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
249     // Cannot fold a signed setcc with an unsigned setcc.
250     return ISD::SETCC_INVALID;
251
252   // Combine all of the condition bits.
253   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
254   
255   // Canonicalize illegal integer setcc's.
256   if (isInteger) {
257     switch (Result) {
258     default: break;
259     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
260     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
261     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
262     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
263     }
264   }
265   
266   return Result;
267 }
268
269 const TargetMachine &SelectionDAG::getTarget() const {
270   return TLI.getTargetMachine();
271 }
272
273 //===----------------------------------------------------------------------===//
274 //                           SDNode Profile Support
275 //===----------------------------------------------------------------------===//
276
277 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
278 ///
279 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
280   ID.AddInteger(OpC);
281 }
282
283 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
284 /// solely with their pointer.
285 void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
286   ID.AddPointer(VTList.VTs);  
287 }
288
289 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
290 ///
291 static void AddNodeIDOperands(FoldingSetNodeID &ID,
292                               const SDOperand *Ops, unsigned NumOps) {
293   for (; NumOps; --NumOps, ++Ops) {
294     ID.AddPointer(Ops->Val);
295     ID.AddInteger(Ops->ResNo);
296   }
297 }
298
299 static void AddNodeIDNode(FoldingSetNodeID &ID,
300                           unsigned short OpC, SDVTList VTList, 
301                           const SDOperand *OpList, unsigned N) {
302   AddNodeIDOpcode(ID, OpC);
303   AddNodeIDValueTypes(ID, VTList);
304   AddNodeIDOperands(ID, OpList, N);
305 }
306
307 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
308 /// data.
309 static void AddNodeIDNode(FoldingSetNodeID &ID, SDNode *N) {
310   AddNodeIDOpcode(ID, N->getOpcode());
311   // Add the return value info.
312   AddNodeIDValueTypes(ID, N->getVTList());
313   // Add the operand info.
314   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
315
316   // Handle SDNode leafs with special info.
317   switch (N->getOpcode()) {
318   default: break;  // Normal nodes don't need extra info.
319   case ISD::TargetConstant:
320   case ISD::Constant:
321     ID.AddInteger(cast<ConstantSDNode>(N)->getValue());
322     break;
323   case ISD::TargetConstantFP:
324   case ISD::ConstantFP: {
325     ID.AddAPFloat(cast<ConstantFPSDNode>(N)->getValueAPF());
326     break;
327   }
328   case ISD::TargetGlobalAddress:
329   case ISD::GlobalAddress:
330   case ISD::TargetGlobalTLSAddress:
331   case ISD::GlobalTLSAddress: {
332     GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
333     ID.AddPointer(GA->getGlobal());
334     ID.AddInteger(GA->getOffset());
335     break;
336   }
337   case ISD::BasicBlock:
338     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
339     break;
340   case ISD::Register:
341     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
342     break;
343   case ISD::SRCVALUE: {
344     SrcValueSDNode *SV = cast<SrcValueSDNode>(N);
345     ID.AddPointer(SV->getValue());
346     ID.AddInteger(SV->getOffset());
347     break;
348   }
349   case ISD::FrameIndex:
350   case ISD::TargetFrameIndex:
351     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
352     break;
353   case ISD::JumpTable:
354   case ISD::TargetJumpTable:
355     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
356     break;
357   case ISD::ConstantPool:
358   case ISD::TargetConstantPool: {
359     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
360     ID.AddInteger(CP->getAlignment());
361     ID.AddInteger(CP->getOffset());
362     if (CP->isMachineConstantPoolEntry())
363       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
364     else
365       ID.AddPointer(CP->getConstVal());
366     break;
367   }
368   case ISD::LOAD: {
369     LoadSDNode *LD = cast<LoadSDNode>(N);
370     ID.AddInteger(LD->getAddressingMode());
371     ID.AddInteger(LD->getExtensionType());
372     ID.AddInteger((unsigned int)(LD->getLoadedVT()));
373     ID.AddPointer(LD->getSrcValue());
374     ID.AddInteger(LD->getSrcValueOffset());
375     ID.AddInteger(LD->getAlignment());
376     ID.AddInteger(LD->isVolatile());
377     break;
378   }
379   case ISD::STORE: {
380     StoreSDNode *ST = cast<StoreSDNode>(N);
381     ID.AddInteger(ST->getAddressingMode());
382     ID.AddInteger(ST->isTruncatingStore());
383     ID.AddInteger((unsigned int)(ST->getStoredVT()));
384     ID.AddPointer(ST->getSrcValue());
385     ID.AddInteger(ST->getSrcValueOffset());
386     ID.AddInteger(ST->getAlignment());
387     ID.AddInteger(ST->isVolatile());
388     break;
389   }
390   }
391 }
392
393 //===----------------------------------------------------------------------===//
394 //                              SelectionDAG Class
395 //===----------------------------------------------------------------------===//
396
397 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
398 /// SelectionDAG.
399 void SelectionDAG::RemoveDeadNodes() {
400   // Create a dummy node (which is not added to allnodes), that adds a reference
401   // to the root node, preventing it from being deleted.
402   HandleSDNode Dummy(getRoot());
403
404   SmallVector<SDNode*, 128> DeadNodes;
405   
406   // Add all obviously-dead nodes to the DeadNodes worklist.
407   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
408     if (I->use_empty())
409       DeadNodes.push_back(I);
410
411   // Process the worklist, deleting the nodes and adding their uses to the
412   // worklist.
413   while (!DeadNodes.empty()) {
414     SDNode *N = DeadNodes.back();
415     DeadNodes.pop_back();
416     
417     // Take the node out of the appropriate CSE map.
418     RemoveNodeFromCSEMaps(N);
419
420     // Next, brutally remove the operand list.  This is safe to do, as there are
421     // no cycles in the graph.
422     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
423       SDNode *Operand = I->Val;
424       Operand->removeUser(N);
425       
426       // Now that we removed this operand, see if there are no uses of it left.
427       if (Operand->use_empty())
428         DeadNodes.push_back(Operand);
429     }
430     if (N->OperandsNeedDelete)
431       delete[] N->OperandList;
432     N->OperandList = 0;
433     N->NumOperands = 0;
434     
435     // Finally, remove N itself.
436     AllNodes.erase(N);
437   }
438   
439   // If the root changed (e.g. it was a dead load, update the root).
440   setRoot(Dummy.getValue());
441 }
442
443 void SelectionDAG::RemoveDeadNode(SDNode *N, std::vector<SDNode*> &Deleted) {
444   SmallVector<SDNode*, 16> DeadNodes;
445   DeadNodes.push_back(N);
446
447   // Process the worklist, deleting the nodes and adding their uses to the
448   // worklist.
449   while (!DeadNodes.empty()) {
450     SDNode *N = DeadNodes.back();
451     DeadNodes.pop_back();
452     
453     // Take the node out of the appropriate CSE map.
454     RemoveNodeFromCSEMaps(N);
455
456     // Next, brutally remove the operand list.  This is safe to do, as there are
457     // no cycles in the graph.
458     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
459       SDNode *Operand = I->Val;
460       Operand->removeUser(N);
461       
462       // Now that we removed this operand, see if there are no uses of it left.
463       if (Operand->use_empty())
464         DeadNodes.push_back(Operand);
465     }
466     if (N->OperandsNeedDelete)
467       delete[] N->OperandList;
468     N->OperandList = 0;
469     N->NumOperands = 0;
470     
471     // Finally, remove N itself.
472     Deleted.push_back(N);
473     AllNodes.erase(N);
474   }
475 }
476
477 void SelectionDAG::DeleteNode(SDNode *N) {
478   assert(N->use_empty() && "Cannot delete a node that is not dead!");
479
480   // First take this out of the appropriate CSE map.
481   RemoveNodeFromCSEMaps(N);
482
483   // Finally, remove uses due to operands of this node, remove from the 
484   // AllNodes list, and delete the node.
485   DeleteNodeNotInCSEMaps(N);
486 }
487
488 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
489
490   // Remove it from the AllNodes list.
491   AllNodes.remove(N);
492     
493   // Drop all of the operands and decrement used nodes use counts.
494   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
495     I->Val->removeUser(N);
496   if (N->OperandsNeedDelete)
497     delete[] N->OperandList;
498   N->OperandList = 0;
499   N->NumOperands = 0;
500   
501   delete N;
502 }
503
504 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
505 /// correspond to it.  This is useful when we're about to delete or repurpose
506 /// the node.  We don't want future request for structurally identical nodes
507 /// to return N anymore.
508 void SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
509   bool Erased = false;
510   switch (N->getOpcode()) {
511   case ISD::HANDLENODE: return;  // noop.
512   case ISD::STRING:
513     Erased = StringNodes.erase(cast<StringSDNode>(N)->getValue());
514     break;
515   case ISD::CONDCODE:
516     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
517            "Cond code doesn't exist!");
518     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
519     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
520     break;
521   case ISD::ExternalSymbol:
522     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
523     break;
524   case ISD::TargetExternalSymbol:
525     Erased =
526       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
527     break;
528   case ISD::VALUETYPE:
529     Erased = ValueTypeNodes[cast<VTSDNode>(N)->getVT()] != 0;
530     ValueTypeNodes[cast<VTSDNode>(N)->getVT()] = 0;
531     break;
532   default:
533     // Remove it from the CSE Map.
534     Erased = CSEMap.RemoveNode(N);
535     break;
536   }
537 #ifndef NDEBUG
538   // Verify that the node was actually in one of the CSE maps, unless it has a 
539   // flag result (which cannot be CSE'd) or is one of the special cases that are
540   // not subject to CSE.
541   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
542       !N->isTargetOpcode()) {
543     N->dump(this);
544     cerr << "\n";
545     assert(0 && "Node is not in map!");
546   }
547 #endif
548 }
549
550 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
551 /// has been taken out and modified in some way.  If the specified node already
552 /// exists in the CSE maps, do not modify the maps, but return the existing node
553 /// instead.  If it doesn't exist, add it and return null.
554 ///
555 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
556   assert(N->getNumOperands() && "This is a leaf node!");
557   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
558     return 0;    // Never add these nodes.
559   
560   // Check that remaining values produced are not flags.
561   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
562     if (N->getValueType(i) == MVT::Flag)
563       return 0;   // Never CSE anything that produces a flag.
564   
565   SDNode *New = CSEMap.GetOrInsertNode(N);
566   if (New != N) return New;  // Node already existed.
567   return 0;
568 }
569
570 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
571 /// were replaced with those specified.  If this node is never memoized, 
572 /// return null, otherwise return a pointer to the slot it would take.  If a
573 /// node already exists with these operands, the slot will be non-null.
574 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDOperand Op,
575                                            void *&InsertPos) {
576   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
577     return 0;    // Never add these nodes.
578   
579   // Check that remaining values produced are not flags.
580   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
581     if (N->getValueType(i) == MVT::Flag)
582       return 0;   // Never CSE anything that produces a flag.
583   
584   SDOperand Ops[] = { Op };
585   FoldingSetNodeID ID;
586   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
587   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
588 }
589
590 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
591 /// were replaced with those specified.  If this node is never memoized, 
592 /// return null, otherwise return a pointer to the slot it would take.  If a
593 /// node already exists with these operands, the slot will be non-null.
594 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
595                                            SDOperand Op1, SDOperand Op2,
596                                            void *&InsertPos) {
597   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
598     return 0;    // Never add these nodes.
599   
600   // Check that remaining values produced are not flags.
601   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
602     if (N->getValueType(i) == MVT::Flag)
603       return 0;   // Never CSE anything that produces a flag.
604                                               
605   SDOperand Ops[] = { Op1, Op2 };
606   FoldingSetNodeID ID;
607   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
608   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
609 }
610
611
612 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
613 /// were replaced with those specified.  If this node is never memoized, 
614 /// return null, otherwise return a pointer to the slot it would take.  If a
615 /// node already exists with these operands, the slot will be non-null.
616 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
617                                            const SDOperand *Ops,unsigned NumOps,
618                                            void *&InsertPos) {
619   if (N->getOpcode() == ISD::HANDLENODE || N->getValueType(0) == MVT::Flag)
620     return 0;    // Never add these nodes.
621   
622   // Check that remaining values produced are not flags.
623   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
624     if (N->getValueType(i) == MVT::Flag)
625       return 0;   // Never CSE anything that produces a flag.
626   
627   FoldingSetNodeID ID;
628   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
629   
630   if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
631     ID.AddInteger(LD->getAddressingMode());
632     ID.AddInteger(LD->getExtensionType());
633     ID.AddInteger((unsigned int)(LD->getLoadedVT()));
634     ID.AddPointer(LD->getSrcValue());
635     ID.AddInteger(LD->getSrcValueOffset());
636     ID.AddInteger(LD->getAlignment());
637     ID.AddInteger(LD->isVolatile());
638   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
639     ID.AddInteger(ST->getAddressingMode());
640     ID.AddInteger(ST->isTruncatingStore());
641     ID.AddInteger((unsigned int)(ST->getStoredVT()));
642     ID.AddPointer(ST->getSrcValue());
643     ID.AddInteger(ST->getSrcValueOffset());
644     ID.AddInteger(ST->getAlignment());
645     ID.AddInteger(ST->isVolatile());
646   }
647   
648   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
649 }
650
651
652 SelectionDAG::~SelectionDAG() {
653   while (!AllNodes.empty()) {
654     SDNode *N = AllNodes.begin();
655     N->SetNextInBucket(0);
656     if (N->OperandsNeedDelete)
657       delete [] N->OperandList;
658     N->OperandList = 0;
659     N->NumOperands = 0;
660     AllNodes.pop_front();
661   }
662 }
663
664 SDOperand SelectionDAG::getZeroExtendInReg(SDOperand Op, MVT::ValueType VT) {
665   if (Op.getValueType() == VT) return Op;
666   int64_t Imm = ~0ULL >> (64-MVT::getSizeInBits(VT));
667   return getNode(ISD::AND, Op.getValueType(), Op,
668                  getConstant(Imm, Op.getValueType()));
669 }
670
671 SDOperand SelectionDAG::getString(const std::string &Val) {
672   StringSDNode *&N = StringNodes[Val];
673   if (!N) {
674     N = new StringSDNode(Val);
675     AllNodes.push_back(N);
676   }
677   return SDOperand(N, 0);
678 }
679
680 SDOperand SelectionDAG::getConstant(uint64_t Val, MVT::ValueType VT, bool isT) {
681   assert(MVT::isInteger(VT) && "Cannot create FP integer constant!");
682   assert(!MVT::isVector(VT) && "Cannot create Vector ConstantSDNodes!");
683   
684   // Mask out any bits that are not valid for this constant.
685   Val &= MVT::getIntVTBitMask(VT);
686
687   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
688   FoldingSetNodeID ID;
689   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
690   ID.AddInteger(Val);
691   void *IP = 0;
692   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
693     return SDOperand(E, 0);
694   SDNode *N = new ConstantSDNode(isT, Val, VT);
695   CSEMap.InsertNode(N, IP);
696   AllNodes.push_back(N);
697   return SDOperand(N, 0);
698 }
699
700 SDOperand SelectionDAG::getConstantFP(const APFloat& V, MVT::ValueType VT,
701                                       bool isTarget) {
702   assert(MVT::isFloatingPoint(VT) && "Cannot create integer FP constant!");
703                                 
704   MVT::ValueType EltVT =
705     MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
706
707   // Do the map lookup using the actual bit pattern for the floating point
708   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
709   // we don't have issues with SNANs.
710   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
711   FoldingSetNodeID ID;
712   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
713   ID.AddAPFloat(V);
714   void *IP = 0;
715   SDNode *N = NULL;
716   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
717     if (!MVT::isVector(VT))
718       return SDOperand(N, 0);
719   if (!N) {
720     N = new ConstantFPSDNode(isTarget, V, EltVT);
721     CSEMap.InsertNode(N, IP);
722     AllNodes.push_back(N);
723   }
724
725   SDOperand Result(N, 0);
726   if (MVT::isVector(VT)) {
727     SmallVector<SDOperand, 8> Ops;
728     Ops.assign(MVT::getVectorNumElements(VT), Result);
729     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
730   }
731   return Result;
732 }
733
734 SDOperand SelectionDAG::getConstantFP(double Val, MVT::ValueType VT,
735                                       bool isTarget) {
736   MVT::ValueType EltVT =
737     MVT::isVector(VT) ? MVT::getVectorElementType(VT) : VT;
738   if (EltVT==MVT::f32)
739     return getConstantFP(APFloat((float)Val), VT, isTarget);
740   else
741     return getConstantFP(APFloat(Val), VT, isTarget);
742 }
743
744 SDOperand SelectionDAG::getGlobalAddress(const GlobalValue *GV,
745                                          MVT::ValueType VT, int Offset,
746                                          bool isTargetGA) {
747   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
748   unsigned Opc;
749   if (GVar && GVar->isThreadLocal())
750     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
751   else
752     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
753   FoldingSetNodeID ID;
754   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
755   ID.AddPointer(GV);
756   ID.AddInteger(Offset);
757   void *IP = 0;
758   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
759    return SDOperand(E, 0);
760   SDNode *N = new GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
761   CSEMap.InsertNode(N, IP);
762   AllNodes.push_back(N);
763   return SDOperand(N, 0);
764 }
765
766 SDOperand SelectionDAG::getFrameIndex(int FI, MVT::ValueType VT,
767                                       bool isTarget) {
768   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
769   FoldingSetNodeID ID;
770   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
771   ID.AddInteger(FI);
772   void *IP = 0;
773   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
774     return SDOperand(E, 0);
775   SDNode *N = new FrameIndexSDNode(FI, VT, isTarget);
776   CSEMap.InsertNode(N, IP);
777   AllNodes.push_back(N);
778   return SDOperand(N, 0);
779 }
780
781 SDOperand SelectionDAG::getJumpTable(int JTI, MVT::ValueType VT, bool isTarget){
782   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
783   FoldingSetNodeID ID;
784   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
785   ID.AddInteger(JTI);
786   void *IP = 0;
787   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
788     return SDOperand(E, 0);
789   SDNode *N = new JumpTableSDNode(JTI, VT, isTarget);
790   CSEMap.InsertNode(N, IP);
791   AllNodes.push_back(N);
792   return SDOperand(N, 0);
793 }
794
795 SDOperand SelectionDAG::getConstantPool(Constant *C, MVT::ValueType VT,
796                                         unsigned Alignment, int Offset,
797                                         bool isTarget) {
798   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
799   FoldingSetNodeID ID;
800   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
801   ID.AddInteger(Alignment);
802   ID.AddInteger(Offset);
803   ID.AddPointer(C);
804   void *IP = 0;
805   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
806     return SDOperand(E, 0);
807   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
808   CSEMap.InsertNode(N, IP);
809   AllNodes.push_back(N);
810   return SDOperand(N, 0);
811 }
812
813
814 SDOperand SelectionDAG::getConstantPool(MachineConstantPoolValue *C,
815                                         MVT::ValueType VT,
816                                         unsigned Alignment, int Offset,
817                                         bool isTarget) {
818   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
819   FoldingSetNodeID ID;
820   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
821   ID.AddInteger(Alignment);
822   ID.AddInteger(Offset);
823   C->AddSelectionDAGCSEId(ID);
824   void *IP = 0;
825   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
826     return SDOperand(E, 0);
827   SDNode *N = new ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
828   CSEMap.InsertNode(N, IP);
829   AllNodes.push_back(N);
830   return SDOperand(N, 0);
831 }
832
833
834 SDOperand SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
835   FoldingSetNodeID ID;
836   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
837   ID.AddPointer(MBB);
838   void *IP = 0;
839   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
840     return SDOperand(E, 0);
841   SDNode *N = new BasicBlockSDNode(MBB);
842   CSEMap.InsertNode(N, IP);
843   AllNodes.push_back(N);
844   return SDOperand(N, 0);
845 }
846
847 SDOperand SelectionDAG::getValueType(MVT::ValueType VT) {
848   if ((unsigned)VT >= ValueTypeNodes.size())
849     ValueTypeNodes.resize(VT+1);
850   if (ValueTypeNodes[VT] == 0) {
851     ValueTypeNodes[VT] = new VTSDNode(VT);
852     AllNodes.push_back(ValueTypeNodes[VT]);
853   }
854
855   return SDOperand(ValueTypeNodes[VT], 0);
856 }
857
858 SDOperand SelectionDAG::getExternalSymbol(const char *Sym, MVT::ValueType VT) {
859   SDNode *&N = ExternalSymbols[Sym];
860   if (N) return SDOperand(N, 0);
861   N = new ExternalSymbolSDNode(false, Sym, VT);
862   AllNodes.push_back(N);
863   return SDOperand(N, 0);
864 }
865
866 SDOperand SelectionDAG::getTargetExternalSymbol(const char *Sym,
867                                                 MVT::ValueType VT) {
868   SDNode *&N = TargetExternalSymbols[Sym];
869   if (N) return SDOperand(N, 0);
870   N = new ExternalSymbolSDNode(true, Sym, VT);
871   AllNodes.push_back(N);
872   return SDOperand(N, 0);
873 }
874
875 SDOperand SelectionDAG::getCondCode(ISD::CondCode Cond) {
876   if ((unsigned)Cond >= CondCodeNodes.size())
877     CondCodeNodes.resize(Cond+1);
878   
879   if (CondCodeNodes[Cond] == 0) {
880     CondCodeNodes[Cond] = new CondCodeSDNode(Cond);
881     AllNodes.push_back(CondCodeNodes[Cond]);
882   }
883   return SDOperand(CondCodeNodes[Cond], 0);
884 }
885
886 SDOperand SelectionDAG::getRegister(unsigned RegNo, MVT::ValueType VT) {
887   FoldingSetNodeID ID;
888   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
889   ID.AddInteger(RegNo);
890   void *IP = 0;
891   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
892     return SDOperand(E, 0);
893   SDNode *N = new RegisterSDNode(RegNo, VT);
894   CSEMap.InsertNode(N, IP);
895   AllNodes.push_back(N);
896   return SDOperand(N, 0);
897 }
898
899 SDOperand SelectionDAG::getSrcValue(const Value *V, int Offset) {
900   assert((!V || isa<PointerType>(V->getType())) &&
901          "SrcValue is not a pointer?");
902
903   FoldingSetNodeID ID;
904   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
905   ID.AddPointer(V);
906   ID.AddInteger(Offset);
907   void *IP = 0;
908   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
909     return SDOperand(E, 0);
910   SDNode *N = new SrcValueSDNode(V, Offset);
911   CSEMap.InsertNode(N, IP);
912   AllNodes.push_back(N);
913   return SDOperand(N, 0);
914 }
915
916 SDOperand SelectionDAG::FoldSetCC(MVT::ValueType VT, SDOperand N1,
917                                   SDOperand N2, ISD::CondCode Cond) {
918   // These setcc operations always fold.
919   switch (Cond) {
920   default: break;
921   case ISD::SETFALSE:
922   case ISD::SETFALSE2: return getConstant(0, VT);
923   case ISD::SETTRUE:
924   case ISD::SETTRUE2:  return getConstant(1, VT);
925     
926   case ISD::SETOEQ:
927   case ISD::SETOGT:
928   case ISD::SETOGE:
929   case ISD::SETOLT:
930   case ISD::SETOLE:
931   case ISD::SETONE:
932   case ISD::SETO:
933   case ISD::SETUO:
934   case ISD::SETUEQ:
935   case ISD::SETUNE:
936     assert(!MVT::isInteger(N1.getValueType()) && "Illegal setcc for integer!");
937     break;
938   }
939   
940   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val)) {
941     uint64_t C2 = N2C->getValue();
942     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val)) {
943       uint64_t C1 = N1C->getValue();
944       
945       // Sign extend the operands if required
946       if (ISD::isSignedIntSetCC(Cond)) {
947         C1 = N1C->getSignExtended();
948         C2 = N2C->getSignExtended();
949       }
950       
951       switch (Cond) {
952       default: assert(0 && "Unknown integer setcc!");
953       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
954       case ISD::SETNE:  return getConstant(C1 != C2, VT);
955       case ISD::SETULT: return getConstant(C1 <  C2, VT);
956       case ISD::SETUGT: return getConstant(C1 >  C2, VT);
957       case ISD::SETULE: return getConstant(C1 <= C2, VT);
958       case ISD::SETUGE: return getConstant(C1 >= C2, VT);
959       case ISD::SETLT:  return getConstant((int64_t)C1 <  (int64_t)C2, VT);
960       case ISD::SETGT:  return getConstant((int64_t)C1 >  (int64_t)C2, VT);
961       case ISD::SETLE:  return getConstant((int64_t)C1 <= (int64_t)C2, VT);
962       case ISD::SETGE:  return getConstant((int64_t)C1 >= (int64_t)C2, VT);
963       }
964     }
965   }
966   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.Val))
967     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.Val)) {
968
969       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
970       switch (Cond) {
971       default: break;
972       case ISD::SETEQ:  if (R==APFloat::cmpUnordered) 
973                           return getNode(ISD::UNDEF, VT);
974                         // fall through
975       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
976       case ISD::SETNE:  if (R==APFloat::cmpUnordered) 
977                           return getNode(ISD::UNDEF, VT);
978                         // fall through
979       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
980                                            R==APFloat::cmpLessThan, VT);
981       case ISD::SETLT:  if (R==APFloat::cmpUnordered) 
982                           return getNode(ISD::UNDEF, VT);
983                         // fall through
984       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
985       case ISD::SETGT:  if (R==APFloat::cmpUnordered) 
986                           return getNode(ISD::UNDEF, VT);
987                         // fall through
988       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
989       case ISD::SETLE:  if (R==APFloat::cmpUnordered) 
990                           return getNode(ISD::UNDEF, VT);
991                         // fall through
992       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
993                                            R==APFloat::cmpEqual, VT);
994       case ISD::SETGE:  if (R==APFloat::cmpUnordered) 
995                           return getNode(ISD::UNDEF, VT);
996                         // fall through
997       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
998                                            R==APFloat::cmpEqual, VT);
999       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
1000       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
1001       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
1002                                            R==APFloat::cmpEqual, VT);
1003       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
1004       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
1005                                            R==APFloat::cmpLessThan, VT);
1006       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
1007                                            R==APFloat::cmpUnordered, VT);
1008       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
1009       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
1010       }
1011     } else {
1012       // Ensure that the constant occurs on the RHS.
1013       return getSetCC(VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
1014     }
1015       
1016   // Could not fold it.
1017   return SDOperand();
1018 }
1019
1020 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
1021 /// this predicate to simplify operations downstream.  Mask is known to be zero
1022 /// for bits that V cannot have.
1023 bool SelectionDAG::MaskedValueIsZero(SDOperand Op, uint64_t Mask, 
1024                                      unsigned Depth) const {
1025   // The masks are not wide enough to represent this type!  Should use APInt.
1026   if (Op.getValueType() == MVT::i128)
1027     return false;
1028   
1029   uint64_t KnownZero, KnownOne;
1030   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1031   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1032   return (KnownZero & Mask) == Mask;
1033 }
1034
1035 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
1036 /// known to be either zero or one and return them in the KnownZero/KnownOne
1037 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
1038 /// processing.
1039 void SelectionDAG::ComputeMaskedBits(SDOperand Op, uint64_t Mask, 
1040                                      uint64_t &KnownZero, uint64_t &KnownOne,
1041                                      unsigned Depth) const {
1042   KnownZero = KnownOne = 0;   // Don't know anything.
1043   if (Depth == 6 || Mask == 0)
1044     return;  // Limit search depth.
1045   
1046   // The masks are not wide enough to represent this type!  Should use APInt.
1047   if (Op.getValueType() == MVT::i128)
1048     return;
1049   
1050   uint64_t KnownZero2, KnownOne2;
1051
1052   switch (Op.getOpcode()) {
1053   case ISD::Constant:
1054     // We know all of the bits for a constant!
1055     KnownOne = cast<ConstantSDNode>(Op)->getValue() & Mask;
1056     KnownZero = ~KnownOne & Mask;
1057     return;
1058   case ISD::AND:
1059     // If either the LHS or the RHS are Zero, the result is zero.
1060     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1061     Mask &= ~KnownZero;
1062     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1063     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1064     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1065
1066     // Output known-1 bits are only known if set in both the LHS & RHS.
1067     KnownOne &= KnownOne2;
1068     // Output known-0 are known to be clear if zero in either the LHS | RHS.
1069     KnownZero |= KnownZero2;
1070     return;
1071   case ISD::OR:
1072     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1073     Mask &= ~KnownOne;
1074     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1075     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1076     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1077     
1078     // Output known-0 bits are only known if clear in both the LHS & RHS.
1079     KnownZero &= KnownZero2;
1080     // Output known-1 are known to be set if set in either the LHS | RHS.
1081     KnownOne |= KnownOne2;
1082     return;
1083   case ISD::XOR: {
1084     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1085     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1086     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1087     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1088     
1089     // Output known-0 bits are known if clear or set in both the LHS & RHS.
1090     uint64_t KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
1091     // Output known-1 are known to be set if set in only one of the LHS, RHS.
1092     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
1093     KnownZero = KnownZeroOut;
1094     return;
1095   }
1096   case ISD::SELECT:
1097     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
1098     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
1099     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1100     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1101     
1102     // Only known if known in both the LHS and RHS.
1103     KnownOne &= KnownOne2;
1104     KnownZero &= KnownZero2;
1105     return;
1106   case ISD::SELECT_CC:
1107     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
1108     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
1109     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1110     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1111     
1112     // Only known if known in both the LHS and RHS.
1113     KnownOne &= KnownOne2;
1114     KnownZero &= KnownZero2;
1115     return;
1116   case ISD::SETCC:
1117     // If we know the result of a setcc has the top bits zero, use this info.
1118     if (TLI.getSetCCResultContents() == TargetLowering::ZeroOrOneSetCCResult)
1119       KnownZero |= (MVT::getIntVTBitMask(Op.getValueType()) ^ 1ULL);
1120     return;
1121   case ISD::SHL:
1122     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
1123     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1124       ComputeMaskedBits(Op.getOperand(0), Mask >> SA->getValue(),
1125                         KnownZero, KnownOne, Depth+1);
1126       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1127       KnownZero <<= SA->getValue();
1128       KnownOne  <<= SA->getValue();
1129       KnownZero |= (1ULL << SA->getValue())-1;  // low bits known zero.
1130     }
1131     return;
1132   case ISD::SRL:
1133     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
1134     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1135       MVT::ValueType VT = Op.getValueType();
1136       unsigned ShAmt = SA->getValue();
1137
1138       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1139       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt) & TypeMask,
1140                         KnownZero, KnownOne, Depth+1);
1141       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1142       KnownZero &= TypeMask;
1143       KnownOne  &= TypeMask;
1144       KnownZero >>= ShAmt;
1145       KnownOne  >>= ShAmt;
1146
1147       uint64_t HighBits = (1ULL << ShAmt)-1;
1148       HighBits <<= MVT::getSizeInBits(VT)-ShAmt;
1149       KnownZero |= HighBits;  // High bits known zero.
1150     }
1151     return;
1152   case ISD::SRA:
1153     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1154       MVT::ValueType VT = Op.getValueType();
1155       unsigned ShAmt = SA->getValue();
1156
1157       // Compute the new bits that are at the top now.
1158       uint64_t TypeMask = MVT::getIntVTBitMask(VT);
1159
1160       uint64_t InDemandedMask = (Mask << ShAmt) & TypeMask;
1161       // If any of the demanded bits are produced by the sign extension, we also
1162       // demand the input sign bit.
1163       uint64_t HighBits = (1ULL << ShAmt)-1;
1164       HighBits <<= MVT::getSizeInBits(VT) - ShAmt;
1165       if (HighBits & Mask)
1166         InDemandedMask |= MVT::getIntVTSignBit(VT);
1167       
1168       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
1169                         Depth+1);
1170       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1171       KnownZero &= TypeMask;
1172       KnownOne  &= TypeMask;
1173       KnownZero >>= ShAmt;
1174       KnownOne  >>= ShAmt;
1175       
1176       // Handle the sign bits.
1177       uint64_t SignBit = MVT::getIntVTSignBit(VT);
1178       SignBit >>= ShAmt;  // Adjust to where it is now in the mask.
1179       
1180       if (KnownZero & SignBit) {       
1181         KnownZero |= HighBits;  // New bits are known zero.
1182       } else if (KnownOne & SignBit) {
1183         KnownOne  |= HighBits;  // New bits are known one.
1184       }
1185     }
1186     return;
1187   case ISD::SIGN_EXTEND_INREG: {
1188     MVT::ValueType EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1189     
1190     // Sign extension.  Compute the demanded bits in the result that are not 
1191     // present in the input.
1192     uint64_t NewBits = ~MVT::getIntVTBitMask(EVT) & Mask;
1193
1194     uint64_t InSignBit = MVT::getIntVTSignBit(EVT);
1195     int64_t InputDemandedBits = Mask & MVT::getIntVTBitMask(EVT);
1196     
1197     // If the sign extended bits are demanded, we know that the sign
1198     // bit is demanded.
1199     if (NewBits)
1200       InputDemandedBits |= InSignBit;
1201     
1202     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
1203                       KnownZero, KnownOne, Depth+1);
1204     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1205     
1206     // If the sign bit of the input is known set or clear, then we know the
1207     // top bits of the result.
1208     if (KnownZero & InSignBit) {          // Input sign bit known clear
1209       KnownZero |= NewBits;
1210       KnownOne  &= ~NewBits;
1211     } else if (KnownOne & InSignBit) {    // Input sign bit known set
1212       KnownOne  |= NewBits;
1213       KnownZero &= ~NewBits;
1214     } else {                              // Input sign bit unknown
1215       KnownZero &= ~NewBits;
1216       KnownOne  &= ~NewBits;
1217     }
1218     return;
1219   }
1220   case ISD::CTTZ:
1221   case ISD::CTLZ:
1222   case ISD::CTPOP: {
1223     MVT::ValueType VT = Op.getValueType();
1224     unsigned LowBits = Log2_32(MVT::getSizeInBits(VT))+1;
1225     KnownZero = ~((1ULL << LowBits)-1) & MVT::getIntVTBitMask(VT);
1226     KnownOne  = 0;
1227     return;
1228   }
1229   case ISD::LOAD: {
1230     if (ISD::isZEXTLoad(Op.Val)) {
1231       LoadSDNode *LD = cast<LoadSDNode>(Op);
1232       MVT::ValueType VT = LD->getLoadedVT();
1233       KnownZero |= ~MVT::getIntVTBitMask(VT) & Mask;
1234     }
1235     return;
1236   }
1237   case ISD::ZERO_EXTEND: {
1238     uint64_t InMask  = MVT::getIntVTBitMask(Op.getOperand(0).getValueType());
1239     uint64_t NewBits = (~InMask) & Mask;
1240     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1241                       KnownOne, Depth+1);
1242     KnownZero |= NewBits & Mask;
1243     KnownOne  &= ~NewBits;
1244     return;
1245   }
1246   case ISD::SIGN_EXTEND: {
1247     MVT::ValueType InVT = Op.getOperand(0).getValueType();
1248     unsigned InBits    = MVT::getSizeInBits(InVT);
1249     uint64_t InMask    = MVT::getIntVTBitMask(InVT);
1250     uint64_t InSignBit = 1ULL << (InBits-1);
1251     uint64_t NewBits   = (~InMask) & Mask;
1252     uint64_t InDemandedBits = Mask & InMask;
1253
1254     // If any of the sign extended bits are demanded, we know that the sign
1255     // bit is demanded.
1256     if (NewBits & Mask)
1257       InDemandedBits |= InSignBit;
1258     
1259     ComputeMaskedBits(Op.getOperand(0), InDemandedBits, KnownZero, 
1260                       KnownOne, Depth+1);
1261     // If the sign bit is known zero or one, the  top bits match.
1262     if (KnownZero & InSignBit) {
1263       KnownZero |= NewBits;
1264       KnownOne  &= ~NewBits;
1265     } else if (KnownOne & InSignBit) {
1266       KnownOne  |= NewBits;
1267       KnownZero &= ~NewBits;
1268     } else {   // Otherwise, top bits aren't known.
1269       KnownOne  &= ~NewBits;
1270       KnownZero &= ~NewBits;
1271     }
1272     return;
1273   }
1274   case ISD::ANY_EXTEND: {
1275     MVT::ValueType VT = Op.getOperand(0).getValueType();
1276     ComputeMaskedBits(Op.getOperand(0), Mask & MVT::getIntVTBitMask(VT),
1277                       KnownZero, KnownOne, Depth+1);
1278     return;
1279   }
1280   case ISD::TRUNCATE: {
1281     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1282     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1283     uint64_t OutMask = MVT::getIntVTBitMask(Op.getValueType());
1284     KnownZero &= OutMask;
1285     KnownOne &= OutMask;
1286     break;
1287   }
1288   case ISD::AssertZext: {
1289     MVT::ValueType VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
1290     uint64_t InMask = MVT::getIntVTBitMask(VT);
1291     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
1292                       KnownOne, Depth+1);
1293     KnownZero |= (~InMask) & Mask;
1294     return;
1295   }
1296   case ISD::ADD: {
1297     // If either the LHS or the RHS are Zero, the result is zero.
1298     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1299     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
1300     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
1301     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
1302     
1303     // Output known-0 bits are known if clear or set in both the low clear bits
1304     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1305     // low 3 bits clear.
1306     uint64_t KnownZeroOut = std::min(CountTrailingZeros_64(~KnownZero), 
1307                                      CountTrailingZeros_64(~KnownZero2));
1308     
1309     KnownZero = (1ULL << KnownZeroOut) - 1;
1310     KnownOne = 0;
1311     return;
1312   }
1313   case ISD::SUB: {
1314     ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0));
1315     if (!CLHS) return;
1316
1317     // We know that the top bits of C-X are clear if X contains less bits
1318     // than C (i.e. no wrap-around can happen).  For example, 20-X is
1319     // positive if we can prove that X is >= 0 and < 16.
1320     MVT::ValueType VT = CLHS->getValueType(0);
1321     if ((CLHS->getValue() & MVT::getIntVTSignBit(VT)) == 0) {  // sign bit clear
1322       unsigned NLZ = CountLeadingZeros_64(CLHS->getValue()+1);
1323       uint64_t MaskV = (1ULL << (63-NLZ))-1; // NLZ can't be 64 with no sign bit
1324       MaskV = ~MaskV & MVT::getIntVTBitMask(VT);
1325       ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero, KnownOne, Depth+1);
1326
1327       // If all of the MaskV bits are known to be zero, then we know the output
1328       // top bits are zero, because we now know that the output is from [0-C].
1329       if ((KnownZero & MaskV) == MaskV) {
1330         unsigned NLZ2 = CountLeadingZeros_64(CLHS->getValue());
1331         KnownZero = ~((1ULL << (64-NLZ2))-1) & Mask;  // Top bits known zero.
1332         KnownOne = 0;   // No one bits known.
1333       } else {
1334         KnownZero = KnownOne = 0;  // Otherwise, nothing known.
1335       }
1336     }
1337     return;
1338   }
1339   default:
1340     // Allow the target to implement this method for its nodes.
1341     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
1342   case ISD::INTRINSIC_WO_CHAIN:
1343   case ISD::INTRINSIC_W_CHAIN:
1344   case ISD::INTRINSIC_VOID:
1345       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
1346     }
1347     return;
1348   }
1349 }
1350
1351 /// ComputeNumSignBits - Return the number of times the sign bit of the
1352 /// register is replicated into the other bits.  We know that at least 1 bit
1353 /// is always equal to the sign bit (itself), but other cases can give us
1354 /// information.  For example, immediately after an "SRA X, 2", we know that
1355 /// the top 3 bits are all equal to each other, so we return 3.
1356 unsigned SelectionDAG::ComputeNumSignBits(SDOperand Op, unsigned Depth) const{
1357   MVT::ValueType VT = Op.getValueType();
1358   assert(MVT::isInteger(VT) && "Invalid VT!");
1359   unsigned VTBits = MVT::getSizeInBits(VT);
1360   unsigned Tmp, Tmp2;
1361   
1362   if (Depth == 6)
1363     return 1;  // Limit search depth.
1364
1365   switch (Op.getOpcode()) {
1366   default: break;
1367   case ISD::AssertSext:
1368     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1369     return VTBits-Tmp+1;
1370   case ISD::AssertZext:
1371     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1372     return VTBits-Tmp;
1373     
1374   case ISD::Constant: {
1375     uint64_t Val = cast<ConstantSDNode>(Op)->getValue();
1376     // If negative, invert the bits, then look at it.
1377     if (Val & MVT::getIntVTSignBit(VT))
1378       Val = ~Val;
1379     
1380     // Shift the bits so they are the leading bits in the int64_t.
1381     Val <<= 64-VTBits;
1382     
1383     // Return # leading zeros.  We use 'min' here in case Val was zero before
1384     // shifting.  We don't want to return '64' as for an i32 "0".
1385     return std::min(VTBits, CountLeadingZeros_64(Val));
1386   }
1387     
1388   case ISD::SIGN_EXTEND:
1389     Tmp = VTBits-MVT::getSizeInBits(Op.getOperand(0).getValueType());
1390     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
1391     
1392   case ISD::SIGN_EXTEND_INREG:
1393     // Max of the input and what this extends.
1394     Tmp = MVT::getSizeInBits(cast<VTSDNode>(Op.getOperand(1))->getVT());
1395     Tmp = VTBits-Tmp+1;
1396     
1397     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1398     return std::max(Tmp, Tmp2);
1399
1400   case ISD::SRA:
1401     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1402     // SRA X, C   -> adds C sign bits.
1403     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1404       Tmp += C->getValue();
1405       if (Tmp > VTBits) Tmp = VTBits;
1406     }
1407     return Tmp;
1408   case ISD::SHL:
1409     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1410       // shl destroys sign bits.
1411       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1412       if (C->getValue() >= VTBits ||      // Bad shift.
1413           C->getValue() >= Tmp) break;    // Shifted all sign bits out.
1414       return Tmp - C->getValue();
1415     }
1416     break;
1417   case ISD::AND:
1418   case ISD::OR:
1419   case ISD::XOR:    // NOT is handled here.
1420     // Logical binary ops preserve the number of sign bits.
1421     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1422     if (Tmp == 1) return 1;  // Early out.
1423     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1424     return std::min(Tmp, Tmp2);
1425
1426   case ISD::SELECT:
1427     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1428     if (Tmp == 1) return 1;  // Early out.
1429     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1430     return std::min(Tmp, Tmp2);
1431     
1432   case ISD::SETCC:
1433     // If setcc returns 0/-1, all bits are sign bits.
1434     if (TLI.getSetCCResultContents() ==
1435         TargetLowering::ZeroOrNegativeOneSetCCResult)
1436       return VTBits;
1437     break;
1438   case ISD::ROTL:
1439   case ISD::ROTR:
1440     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1441       unsigned RotAmt = C->getValue() & (VTBits-1);
1442       
1443       // Handle rotate right by N like a rotate left by 32-N.
1444       if (Op.getOpcode() == ISD::ROTR)
1445         RotAmt = (VTBits-RotAmt) & (VTBits-1);
1446
1447       // If we aren't rotating out all of the known-in sign bits, return the
1448       // number that are left.  This handles rotl(sext(x), 1) for example.
1449       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1450       if (Tmp > RotAmt+1) return Tmp-RotAmt;
1451     }
1452     break;
1453   case ISD::ADD:
1454     // Add can have at most one carry bit.  Thus we know that the output
1455     // is, at worst, one more bit than the inputs.
1456     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1457     if (Tmp == 1) return 1;  // Early out.
1458       
1459     // Special case decrementing a value (ADD X, -1):
1460     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1461       if (CRHS->isAllOnesValue()) {
1462         uint64_t KnownZero, KnownOne;
1463         uint64_t Mask = MVT::getIntVTBitMask(VT);
1464         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
1465         
1466         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1467         // sign bits set.
1468         if ((KnownZero|1) == Mask)
1469           return VTBits;
1470         
1471         // If we are subtracting one from a positive number, there is no carry
1472         // out of the result.
1473         if (KnownZero & MVT::getIntVTSignBit(VT))
1474           return Tmp;
1475       }
1476       
1477     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1478     if (Tmp2 == 1) return 1;
1479       return std::min(Tmp, Tmp2)-1;
1480     break;
1481     
1482   case ISD::SUB:
1483     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
1484     if (Tmp2 == 1) return 1;
1485       
1486     // Handle NEG.
1487     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
1488       if (CLHS->getValue() == 0) {
1489         uint64_t KnownZero, KnownOne;
1490         uint64_t Mask = MVT::getIntVTBitMask(VT);
1491         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
1492         // If the input is known to be 0 or 1, the output is 0/-1, which is all
1493         // sign bits set.
1494         if ((KnownZero|1) == Mask)
1495           return VTBits;
1496         
1497         // If the input is known to be positive (the sign bit is known clear),
1498         // the output of the NEG has the same number of sign bits as the input.
1499         if (KnownZero & MVT::getIntVTSignBit(VT))
1500           return Tmp2;
1501         
1502         // Otherwise, we treat this like a SUB.
1503       }
1504     
1505     // Sub can have at most one carry bit.  Thus we know that the output
1506     // is, at worst, one more bit than the inputs.
1507     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
1508     if (Tmp == 1) return 1;  // Early out.
1509       return std::min(Tmp, Tmp2)-1;
1510     break;
1511   case ISD::TRUNCATE:
1512     // FIXME: it's tricky to do anything useful for this, but it is an important
1513     // case for targets like X86.
1514     break;
1515   }
1516   
1517   // Handle LOADX separately here. EXTLOAD case will fallthrough.
1518   if (Op.getOpcode() == ISD::LOAD) {
1519     LoadSDNode *LD = cast<LoadSDNode>(Op);
1520     unsigned ExtType = LD->getExtensionType();
1521     switch (ExtType) {
1522     default: break;
1523     case ISD::SEXTLOAD:    // '17' bits known
1524       Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1525       return VTBits-Tmp+1;
1526     case ISD::ZEXTLOAD:    // '16' bits known
1527       Tmp = MVT::getSizeInBits(LD->getLoadedVT());
1528       return VTBits-Tmp;
1529     }
1530   }
1531
1532   // Allow the target to implement this method for its nodes.
1533   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
1534       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
1535       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
1536       Op.getOpcode() == ISD::INTRINSIC_VOID) {
1537     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
1538     if (NumBits > 1) return NumBits;
1539   }
1540   
1541   // Finally, if we can prove that the top bits of the result are 0's or 1's,
1542   // use this information.
1543   uint64_t KnownZero, KnownOne;
1544   uint64_t Mask = MVT::getIntVTBitMask(VT);
1545   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
1546   
1547   uint64_t SignBit = MVT::getIntVTSignBit(VT);
1548   if (KnownZero & SignBit) {        // SignBit is 0
1549     Mask = KnownZero;
1550   } else if (KnownOne & SignBit) {  // SignBit is 1;
1551     Mask = KnownOne;
1552   } else {
1553     // Nothing known.
1554     return 1;
1555   }
1556   
1557   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
1558   // the number of identical bits in the top of the input value.
1559   Mask ^= ~0ULL;
1560   Mask <<= 64-VTBits;
1561   // Return # leading zeros.  We use 'min' here in case Val was zero before
1562   // shifting.  We don't want to return '64' as for an i32 "0".
1563   return std::min(VTBits, CountLeadingZeros_64(Mask));
1564 }
1565
1566
1567 /// getNode - Gets or creates the specified node.
1568 ///
1569 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT) {
1570   FoldingSetNodeID ID;
1571   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
1572   void *IP = 0;
1573   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1574     return SDOperand(E, 0);
1575   SDNode *N = new SDNode(Opcode, SDNode::getSDVTList(VT));
1576   CSEMap.InsertNode(N, IP);
1577   
1578   AllNodes.push_back(N);
1579   return SDOperand(N, 0);
1580 }
1581
1582 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1583                                 SDOperand Operand) {
1584   unsigned Tmp1;
1585   // Constant fold unary operations with an integer constant operand.
1586   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.Val)) {
1587     uint64_t Val = C->getValue();
1588     switch (Opcode) {
1589     default: break;
1590     case ISD::SIGN_EXTEND: return getConstant(C->getSignExtended(), VT);
1591     case ISD::ANY_EXTEND:
1592     case ISD::ZERO_EXTEND: return getConstant(Val, VT);
1593     case ISD::TRUNCATE:    return getConstant(Val, VT);
1594     case ISD::SINT_TO_FP:  return getConstantFP(C->getSignExtended(), VT);
1595     case ISD::UINT_TO_FP:  return getConstantFP(C->getValue(), VT);
1596     case ISD::BIT_CONVERT:
1597       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
1598         return getConstantFP(BitsToFloat(Val), VT);
1599       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
1600         return getConstantFP(BitsToDouble(Val), VT);
1601       break;
1602     case ISD::BSWAP:
1603       switch(VT) {
1604       default: assert(0 && "Invalid bswap!"); break;
1605       case MVT::i16: return getConstant(ByteSwap_16((unsigned short)Val), VT);
1606       case MVT::i32: return getConstant(ByteSwap_32((unsigned)Val), VT);
1607       case MVT::i64: return getConstant(ByteSwap_64(Val), VT);
1608       }
1609       break;
1610     case ISD::CTPOP:
1611       switch(VT) {
1612       default: assert(0 && "Invalid ctpop!"); break;
1613       case MVT::i1: return getConstant(Val != 0, VT);
1614       case MVT::i8: 
1615         Tmp1 = (unsigned)Val & 0xFF;
1616         return getConstant(CountPopulation_32(Tmp1), VT);
1617       case MVT::i16:
1618         Tmp1 = (unsigned)Val & 0xFFFF;
1619         return getConstant(CountPopulation_32(Tmp1), VT);
1620       case MVT::i32:
1621         return getConstant(CountPopulation_32((unsigned)Val), VT);
1622       case MVT::i64:
1623         return getConstant(CountPopulation_64(Val), VT);
1624       }
1625     case ISD::CTLZ:
1626       switch(VT) {
1627       default: assert(0 && "Invalid ctlz!"); break;
1628       case MVT::i1: return getConstant(Val == 0, VT);
1629       case MVT::i8: 
1630         Tmp1 = (unsigned)Val & 0xFF;
1631         return getConstant(CountLeadingZeros_32(Tmp1)-24, VT);
1632       case MVT::i16:
1633         Tmp1 = (unsigned)Val & 0xFFFF;
1634         return getConstant(CountLeadingZeros_32(Tmp1)-16, VT);
1635       case MVT::i32:
1636         return getConstant(CountLeadingZeros_32((unsigned)Val), VT);
1637       case MVT::i64:
1638         return getConstant(CountLeadingZeros_64(Val), VT);
1639       }
1640     case ISD::CTTZ:
1641       switch(VT) {
1642       default: assert(0 && "Invalid cttz!"); break;
1643       case MVT::i1: return getConstant(Val == 0, VT);
1644       case MVT::i8: 
1645         Tmp1 = (unsigned)Val | 0x100;
1646         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1647       case MVT::i16:
1648         Tmp1 = (unsigned)Val | 0x10000;
1649         return getConstant(CountTrailingZeros_32(Tmp1), VT);
1650       case MVT::i32:
1651         return getConstant(CountTrailingZeros_32((unsigned)Val), VT);
1652       case MVT::i64:
1653         return getConstant(CountTrailingZeros_64(Val), VT);
1654       }
1655     }
1656   }
1657
1658   // Constant fold unary operations with a floating point constant operand.
1659   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.Val)) {
1660     APFloat V = C->getValueAPF();    // make copy
1661     switch (Opcode) {
1662     case ISD::FNEG:
1663       V.changeSign();
1664       return getConstantFP(V, VT);
1665     case ISD::FABS:
1666       V.clearSign();
1667       return getConstantFP(V, VT);
1668     case ISD::FP_ROUND:
1669     case ISD::FP_EXTEND:
1670       // This can return overflow, underflow, or inexact; we don't care.
1671       // FIXME need to be more flexible about rounding mode.
1672       (void) V.convert(VT==MVT::f32 ? APFloat::IEEEsingle : 
1673                                       APFloat::IEEEdouble,
1674                        APFloat::rmNearestTiesToEven);
1675       return getConstantFP(V, VT);
1676     case ISD::FP_TO_SINT:
1677     case ISD::FP_TO_UINT: {
1678       integerPart x;
1679       assert(integerPartWidth >= 64);
1680       // FIXME need to be more flexible about rounding mode.
1681       APFloat::opStatus s = V.convertToInteger(&x, 64U,
1682                             Opcode==ISD::FP_TO_SINT,
1683                             APFloat::rmTowardZero);
1684       if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
1685         break;
1686       return getConstant(x, VT);
1687     }
1688     case ISD::BIT_CONVERT:
1689       if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
1690         return getConstant((uint32_t)V.convertToAPInt().getZExtValue(), VT);
1691       else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
1692         return getConstant(V.convertToAPInt().getZExtValue(), VT);
1693       break;
1694     }
1695   }
1696
1697   unsigned OpOpcode = Operand.Val->getOpcode();
1698   switch (Opcode) {
1699   case ISD::TokenFactor:
1700     return Operand;         // Factor of one node?  No factor.
1701   case ISD::FP_ROUND:
1702   case ISD::FP_EXTEND:
1703     assert(MVT::isFloatingPoint(VT) &&
1704            MVT::isFloatingPoint(Operand.getValueType()) && "Invalid FP cast!");
1705     break;
1706   case ISD::SIGN_EXTEND:
1707     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1708            "Invalid SIGN_EXTEND!");
1709     if (Operand.getValueType() == VT) return Operand;   // noop extension
1710     assert(Operand.getValueType() < VT && "Invalid sext node, dst < src!");
1711     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
1712       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1713     break;
1714   case ISD::ZERO_EXTEND:
1715     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1716            "Invalid ZERO_EXTEND!");
1717     if (Operand.getValueType() == VT) return Operand;   // noop extension
1718     assert(Operand.getValueType() < VT && "Invalid zext node, dst < src!");
1719     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
1720       return getNode(ISD::ZERO_EXTEND, VT, Operand.Val->getOperand(0));
1721     break;
1722   case ISD::ANY_EXTEND:
1723     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1724            "Invalid ANY_EXTEND!");
1725     if (Operand.getValueType() == VT) return Operand;   // noop extension
1726     assert(Operand.getValueType() < VT && "Invalid anyext node, dst < src!");
1727     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
1728       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
1729       return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1730     break;
1731   case ISD::TRUNCATE:
1732     assert(MVT::isInteger(VT) && MVT::isInteger(Operand.getValueType()) &&
1733            "Invalid TRUNCATE!");
1734     if (Operand.getValueType() == VT) return Operand;   // noop truncate
1735     assert(Operand.getValueType() > VT && "Invalid truncate node, src < dst!");
1736     if (OpOpcode == ISD::TRUNCATE)
1737       return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1738     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
1739              OpOpcode == ISD::ANY_EXTEND) {
1740       // If the source is smaller than the dest, we still need an extend.
1741       if (Operand.Val->getOperand(0).getValueType() < VT)
1742         return getNode(OpOpcode, VT, Operand.Val->getOperand(0));
1743       else if (Operand.Val->getOperand(0).getValueType() > VT)
1744         return getNode(ISD::TRUNCATE, VT, Operand.Val->getOperand(0));
1745       else
1746         return Operand.Val->getOperand(0);
1747     }
1748     break;
1749   case ISD::BIT_CONVERT:
1750     // Basic sanity checking.
1751     assert(MVT::getSizeInBits(VT) == MVT::getSizeInBits(Operand.getValueType())
1752            && "Cannot BIT_CONVERT between types of different sizes!");
1753     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
1754     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
1755       return getNode(ISD::BIT_CONVERT, VT, Operand.getOperand(0));
1756     if (OpOpcode == ISD::UNDEF)
1757       return getNode(ISD::UNDEF, VT);
1758     break;
1759   case ISD::SCALAR_TO_VECTOR:
1760     assert(MVT::isVector(VT) && !MVT::isVector(Operand.getValueType()) &&
1761            MVT::getVectorElementType(VT) == Operand.getValueType() &&
1762            "Illegal SCALAR_TO_VECTOR node!");
1763     break;
1764   case ISD::FNEG:
1765     if (OpOpcode == ISD::FSUB)   // -(X-Y) -> (Y-X)
1766       return getNode(ISD::FSUB, VT, Operand.Val->getOperand(1),
1767                      Operand.Val->getOperand(0));
1768     if (OpOpcode == ISD::FNEG)  // --X -> X
1769       return Operand.Val->getOperand(0);
1770     break;
1771   case ISD::FABS:
1772     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
1773       return getNode(ISD::FABS, VT, Operand.Val->getOperand(0));
1774     break;
1775   }
1776
1777   SDNode *N;
1778   SDVTList VTs = getVTList(VT);
1779   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
1780     FoldingSetNodeID ID;
1781     SDOperand Ops[1] = { Operand };
1782     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
1783     void *IP = 0;
1784     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
1785       return SDOperand(E, 0);
1786     N = new UnarySDNode(Opcode, VTs, Operand);
1787     CSEMap.InsertNode(N, IP);
1788   } else {
1789     N = new UnarySDNode(Opcode, VTs, Operand);
1790   }
1791   AllNodes.push_back(N);
1792   return SDOperand(N, 0);
1793 }
1794
1795
1796
1797 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
1798                                 SDOperand N1, SDOperand N2) {
1799 #ifndef NDEBUG
1800   switch (Opcode) {
1801   case ISD::TokenFactor:
1802     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
1803            N2.getValueType() == MVT::Other && "Invalid token factor!");
1804     break;
1805   case ISD::AND:
1806   case ISD::OR:
1807   case ISD::XOR:
1808   case ISD::UDIV:
1809   case ISD::UREM:
1810   case ISD::MULHU:
1811   case ISD::MULHS:
1812     assert(MVT::isInteger(VT) && "This operator does not apply to FP types!");
1813     // fall through
1814   case ISD::ADD:
1815   case ISD::SUB:
1816   case ISD::MUL:
1817   case ISD::SDIV:
1818   case ISD::SREM:
1819     assert(MVT::isInteger(N1.getValueType()) && "Should use F* for FP ops");
1820     // fall through.
1821   case ISD::FADD:
1822   case ISD::FSUB:
1823   case ISD::FMUL:
1824   case ISD::FDIV:
1825   case ISD::FREM:
1826     assert(N1.getValueType() == N2.getValueType() &&
1827            N1.getValueType() == VT && "Binary operator types must match!");
1828     break;
1829   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
1830     assert(N1.getValueType() == VT &&
1831            MVT::isFloatingPoint(N1.getValueType()) && 
1832            MVT::isFloatingPoint(N2.getValueType()) &&
1833            "Invalid FCOPYSIGN!");
1834     break;
1835   case ISD::SHL:
1836   case ISD::SRA:
1837   case ISD::SRL:
1838   case ISD::ROTL:
1839   case ISD::ROTR:
1840     assert(VT == N1.getValueType() &&
1841            "Shift operators return type must be the same as their first arg");
1842     assert(MVT::isInteger(VT) && MVT::isInteger(N2.getValueType()) &&
1843            VT != MVT::i1 && "Shifts only work on integers");
1844     break;
1845   case ISD::FP_ROUND_INREG: {
1846     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1847     assert(VT == N1.getValueType() && "Not an inreg round!");
1848     assert(MVT::isFloatingPoint(VT) && MVT::isFloatingPoint(EVT) &&
1849            "Cannot FP_ROUND_INREG integer types");
1850     assert(EVT <= VT && "Not rounding down!");
1851     break;
1852   }
1853   case ISD::AssertSext:
1854   case ISD::AssertZext:
1855   case ISD::SIGN_EXTEND_INREG: {
1856     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
1857     assert(VT == N1.getValueType() && "Not an inreg extend!");
1858     assert(MVT::isInteger(VT) && MVT::isInteger(EVT) &&
1859            "Cannot *_EXTEND_INREG FP types");
1860     assert(EVT <= VT && "Not extending!");
1861   }
1862
1863   default: break;
1864   }
1865 #endif
1866
1867   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
1868   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
1869   if (N1C) {
1870     if (Opcode == ISD::SIGN_EXTEND_INREG) {
1871       int64_t Val = N1C->getValue();
1872       unsigned FromBits = MVT::getSizeInBits(cast<VTSDNode>(N2)->getVT());
1873       Val <<= 64-FromBits;
1874       Val >>= 64-FromBits;
1875       return getConstant(Val, VT);
1876     }
1877     
1878     if (N2C) {
1879       uint64_t C1 = N1C->getValue(), C2 = N2C->getValue();
1880       switch (Opcode) {
1881       case ISD::ADD: return getConstant(C1 + C2, VT);
1882       case ISD::SUB: return getConstant(C1 - C2, VT);
1883       case ISD::MUL: return getConstant(C1 * C2, VT);
1884       case ISD::UDIV:
1885         if (C2) return getConstant(C1 / C2, VT);
1886         break;
1887       case ISD::UREM :
1888         if (C2) return getConstant(C1 % C2, VT);
1889         break;
1890       case ISD::SDIV :
1891         if (C2) return getConstant(N1C->getSignExtended() /
1892                                    N2C->getSignExtended(), VT);
1893         break;
1894       case ISD::SREM :
1895         if (C2) return getConstant(N1C->getSignExtended() %
1896                                    N2C->getSignExtended(), VT);
1897         break;
1898       case ISD::AND  : return getConstant(C1 & C2, VT);
1899       case ISD::OR   : return getConstant(C1 | C2, VT);
1900       case ISD::XOR  : return getConstant(C1 ^ C2, VT);
1901       case ISD::SHL  : return getConstant(C1 << C2, VT);
1902       case ISD::SRL  : return getConstant(C1 >> C2, VT);
1903       case ISD::SRA  : return getConstant(N1C->getSignExtended() >>(int)C2, VT);
1904       case ISD::ROTL : 
1905         return getConstant((C1 << C2) | (C1 >> (MVT::getSizeInBits(VT) - C2)),
1906                            VT);
1907       case ISD::ROTR : 
1908         return getConstant((C1 >> C2) | (C1 << (MVT::getSizeInBits(VT) - C2)), 
1909                            VT);
1910       default: break;
1911       }
1912     } else {      // Cannonicalize constant to RHS if commutative
1913       if (isCommutativeBinOp(Opcode)) {
1914         std::swap(N1C, N2C);
1915         std::swap(N1, N2);
1916       }
1917     }
1918   }
1919
1920   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.Val);
1921   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.Val);
1922   if (N1CFP) {
1923     if (N2CFP) {
1924       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
1925       APFloat::opStatus s;
1926       switch (Opcode) {
1927       case ISD::FADD: 
1928         s = V1.add(V2, APFloat::rmNearestTiesToEven);
1929         if (s!=APFloat::opInvalidOp)
1930           return getConstantFP(V1, VT);
1931         break;
1932       case ISD::FSUB: 
1933         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
1934         if (s!=APFloat::opInvalidOp)
1935           return getConstantFP(V1, VT);
1936         break;
1937       case ISD::FMUL:
1938         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
1939         if (s!=APFloat::opInvalidOp)
1940           return getConstantFP(V1, VT);
1941         break;
1942       case ISD::FDIV:
1943         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
1944         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
1945           return getConstantFP(V1, VT);
1946         break;
1947       case ISD::FREM :
1948         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
1949         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
1950           return getConstantFP(V1, VT);
1951         break;
1952       case ISD::FCOPYSIGN:
1953         V1.copySign(V2);
1954         return getConstantFP(V1, VT);
1955       default: break;
1956       }
1957     } else {      // Cannonicalize constant to RHS if commutative
1958       if (isCommutativeBinOp(Opcode)) {
1959         std::swap(N1CFP, N2CFP);
1960         std::swap(N1, N2);
1961       }
1962     }
1963   }
1964   
1965   // Canonicalize an UNDEF to the RHS, even over a constant.
1966   if (N1.getOpcode() == ISD::UNDEF) {
1967     if (isCommutativeBinOp(Opcode)) {
1968       std::swap(N1, N2);
1969     } else {
1970       switch (Opcode) {
1971       case ISD::FP_ROUND_INREG:
1972       case ISD::SIGN_EXTEND_INREG:
1973       case ISD::SUB:
1974       case ISD::FSUB:
1975       case ISD::FDIV:
1976       case ISD::FREM:
1977       case ISD::SRA:
1978         return N1;     // fold op(undef, arg2) -> undef
1979       case ISD::UDIV:
1980       case ISD::SDIV:
1981       case ISD::UREM:
1982       case ISD::SREM:
1983       case ISD::SRL:
1984       case ISD::SHL:
1985         if (!MVT::isVector(VT)) 
1986           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
1987         // For vectors, we can't easily build an all zero vector, just return
1988         // the LHS.
1989         return N2;
1990       }
1991     }
1992   }
1993   
1994   // Fold a bunch of operators when the RHS is undef. 
1995   if (N2.getOpcode() == ISD::UNDEF) {
1996     switch (Opcode) {
1997     case ISD::ADD:
1998     case ISD::ADDC:
1999     case ISD::ADDE:
2000     case ISD::SUB:
2001     case ISD::FADD:
2002     case ISD::FSUB:
2003     case ISD::FMUL:
2004     case ISD::FDIV:
2005     case ISD::FREM:
2006     case ISD::UDIV:
2007     case ISD::SDIV:
2008     case ISD::UREM:
2009     case ISD::SREM:
2010     case ISD::XOR:
2011       return N2;       // fold op(arg1, undef) -> undef
2012     case ISD::MUL: 
2013     case ISD::AND:
2014     case ISD::SRL:
2015     case ISD::SHL:
2016       if (!MVT::isVector(VT)) 
2017         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2018       // For vectors, we can't easily build an all zero vector, just return
2019       // the LHS.
2020       return N1;
2021     case ISD::OR:
2022       if (!MVT::isVector(VT)) 
2023         return getConstant(MVT::getIntVTBitMask(VT), VT);
2024       // For vectors, we can't easily build an all one vector, just return
2025       // the LHS.
2026       return N1;
2027     case ISD::SRA:
2028       return N1;
2029     }
2030   }
2031
2032   // Fold operations.
2033   switch (Opcode) {
2034   case ISD::TokenFactor:
2035     // Fold trivial token factors.
2036     if (N1.getOpcode() == ISD::EntryToken) return N2;
2037     if (N2.getOpcode() == ISD::EntryToken) return N1;
2038     break;
2039       
2040   case ISD::AND:
2041     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2042     // worth handling here.
2043     if (N2C && N2C->getValue() == 0)
2044       return N2;
2045     break;
2046   case ISD::OR:
2047   case ISD::XOR:
2048     // (X ^| 0) -> X.  This commonly occurs when legalizing i64 values, so it's
2049     // worth handling here.
2050     if (N2C && N2C->getValue() == 0)
2051       return N1;
2052     break;
2053   case ISD::FP_ROUND_INREG:
2054     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2055     break;
2056   case ISD::SIGN_EXTEND_INREG: {
2057     MVT::ValueType EVT = cast<VTSDNode>(N2)->getVT();
2058     if (EVT == VT) return N1;  // Not actually extending
2059     break;
2060   }
2061   case ISD::EXTRACT_VECTOR_ELT:
2062     assert(N2C && "Bad EXTRACT_VECTOR_ELT!");
2063
2064     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2065     // expanding copies of large vectors from registers.
2066     if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
2067         N1.getNumOperands() > 0) {
2068       unsigned Factor =
2069         MVT::getVectorNumElements(N1.getOperand(0).getValueType());
2070       return getNode(ISD::EXTRACT_VECTOR_ELT, VT,
2071                      N1.getOperand(N2C->getValue() / Factor),
2072                      getConstant(N2C->getValue() % Factor, N2.getValueType()));
2073     }
2074
2075     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2076     // expanding large vector constants.
2077     if (N1.getOpcode() == ISD::BUILD_VECTOR)
2078       return N1.getOperand(N2C->getValue());
2079
2080     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2081     // operations are lowered to scalars.
2082     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT)
2083       if (ConstantSDNode *IEC = dyn_cast<ConstantSDNode>(N1.getOperand(2))) {
2084         if (IEC == N2C)
2085           return N1.getOperand(1);
2086         else
2087           return getNode(ISD::EXTRACT_VECTOR_ELT, VT, N1.getOperand(0), N2);
2088       }
2089     break;
2090   case ISD::EXTRACT_ELEMENT:
2091     assert(N2C && (unsigned)N2C->getValue() < 2 && "Bad EXTRACT_ELEMENT!");
2092     
2093     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2094     // 64-bit integers into 32-bit parts.  Instead of building the extract of
2095     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
2096     if (N1.getOpcode() == ISD::BUILD_PAIR)
2097       return N1.getOperand(N2C->getValue());
2098     
2099     // EXTRACT_ELEMENT of a constant int is also very common.
2100     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2101       unsigned Shift = MVT::getSizeInBits(VT) * N2C->getValue();
2102       return getConstant(C->getValue() >> Shift, VT);
2103     }
2104     break;
2105
2106   // FIXME: figure out how to safely handle things like
2107   // int foo(int x) { return 1 << (x & 255); }
2108   // int bar() { return foo(256); }
2109 #if 0
2110   case ISD::SHL:
2111   case ISD::SRL:
2112   case ISD::SRA:
2113     if (N2.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2114         cast<VTSDNode>(N2.getOperand(1))->getVT() != MVT::i1)
2115       return getNode(Opcode, VT, N1, N2.getOperand(0));
2116     else if (N2.getOpcode() == ISD::AND)
2117       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N2.getOperand(1))) {
2118         // If the and is only masking out bits that cannot effect the shift,
2119         // eliminate the and.
2120         unsigned NumBits = MVT::getSizeInBits(VT);
2121         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2122           return getNode(Opcode, VT, N1, N2.getOperand(0));
2123       }
2124     break;
2125 #endif
2126   }
2127
2128   // Memoize this node if possible.
2129   SDNode *N;
2130   SDVTList VTs = getVTList(VT);
2131   if (VT != MVT::Flag) {
2132     SDOperand Ops[] = { N1, N2 };
2133     FoldingSetNodeID ID;
2134     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
2135     void *IP = 0;
2136     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2137       return SDOperand(E, 0);
2138     N = new BinarySDNode(Opcode, VTs, N1, N2);
2139     CSEMap.InsertNode(N, IP);
2140   } else {
2141     N = new BinarySDNode(Opcode, VTs, N1, N2);
2142   }
2143
2144   AllNodes.push_back(N);
2145   return SDOperand(N, 0);
2146 }
2147
2148 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2149                                 SDOperand N1, SDOperand N2, SDOperand N3) {
2150   // Perform various simplifications.
2151   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.Val);
2152   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.Val);
2153   switch (Opcode) {
2154   case ISD::SETCC: {
2155     // Use FoldSetCC to simplify SETCC's.
2156     SDOperand Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get());
2157     if (Simp.Val) return Simp;
2158     break;
2159   }
2160   case ISD::SELECT:
2161     if (N1C)
2162       if (N1C->getValue())
2163         return N2;             // select true, X, Y -> X
2164       else
2165         return N3;             // select false, X, Y -> Y
2166
2167     if (N2 == N3) return N2;   // select C, X, X -> X
2168     break;
2169   case ISD::BRCOND:
2170     if (N2C)
2171       if (N2C->getValue()) // Unconditional branch
2172         return getNode(ISD::BR, MVT::Other, N1, N3);
2173       else
2174         return N1;         // Never-taken branch
2175     break;
2176   case ISD::VECTOR_SHUFFLE:
2177     assert(VT == N1.getValueType() && VT == N2.getValueType() &&
2178            MVT::isVector(VT) && MVT::isVector(N3.getValueType()) &&
2179            N3.getOpcode() == ISD::BUILD_VECTOR &&
2180            MVT::getVectorNumElements(VT) == N3.getNumOperands() &&
2181            "Illegal VECTOR_SHUFFLE node!");
2182     break;
2183   case ISD::BIT_CONVERT:
2184     // Fold bit_convert nodes from a type to themselves.
2185     if (N1.getValueType() == VT)
2186       return N1;
2187     break;
2188   }
2189
2190   // Memoize node if it doesn't produce a flag.
2191   SDNode *N;
2192   SDVTList VTs = getVTList(VT);
2193   if (VT != MVT::Flag) {
2194     SDOperand Ops[] = { N1, N2, N3 };
2195     FoldingSetNodeID ID;
2196     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
2197     void *IP = 0;
2198     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2199       return SDOperand(E, 0);
2200     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2201     CSEMap.InsertNode(N, IP);
2202   } else {
2203     N = new TernarySDNode(Opcode, VTs, N1, N2, N3);
2204   }
2205   AllNodes.push_back(N);
2206   return SDOperand(N, 0);
2207 }
2208
2209 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2210                                 SDOperand N1, SDOperand N2, SDOperand N3,
2211                                 SDOperand N4) {
2212   SDOperand Ops[] = { N1, N2, N3, N4 };
2213   return getNode(Opcode, VT, Ops, 4);
2214 }
2215
2216 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2217                                 SDOperand N1, SDOperand N2, SDOperand N3,
2218                                 SDOperand N4, SDOperand N5) {
2219   SDOperand Ops[] = { N1, N2, N3, N4, N5 };
2220   return getNode(Opcode, VT, Ops, 5);
2221 }
2222
2223 SDOperand SelectionDAG::getLoad(MVT::ValueType VT,
2224                                 SDOperand Chain, SDOperand Ptr,
2225                                 const Value *SV, int SVOffset,
2226                                 bool isVolatile, unsigned Alignment) {
2227   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2228     const Type *Ty = 0;
2229     if (VT != MVT::iPTR) {
2230       Ty = MVT::getTypeForValueType(VT);
2231     } else if (SV) {
2232       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2233       assert(PT && "Value for load must be a pointer");
2234       Ty = PT->getElementType();
2235     }  
2236     assert(Ty && "Could not get type information for load");
2237     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2238   }
2239   SDVTList VTs = getVTList(VT, MVT::Other);
2240   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2241   SDOperand Ops[] = { Chain, Ptr, Undef };
2242   FoldingSetNodeID ID;
2243   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2244   ID.AddInteger(ISD::UNINDEXED);
2245   ID.AddInteger(ISD::NON_EXTLOAD);
2246   ID.AddInteger((unsigned int)VT);
2247   ID.AddPointer(SV);
2248   ID.AddInteger(SVOffset);
2249   ID.AddInteger(Alignment);
2250   ID.AddInteger(isVolatile);
2251   void *IP = 0;
2252   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2253     return SDOperand(E, 0);
2254   SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED,
2255                              ISD::NON_EXTLOAD, VT, SV, SVOffset, Alignment,
2256                              isVolatile);
2257   CSEMap.InsertNode(N, IP);
2258   AllNodes.push_back(N);
2259   return SDOperand(N, 0);
2260 }
2261
2262 SDOperand SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT::ValueType VT,
2263                                    SDOperand Chain, SDOperand Ptr,
2264                                    const Value *SV,
2265                                    int SVOffset, MVT::ValueType EVT,
2266                                    bool isVolatile, unsigned Alignment) {
2267   // If they are asking for an extending load from/to the same thing, return a
2268   // normal load.
2269   if (VT == EVT)
2270     ExtType = ISD::NON_EXTLOAD;
2271
2272   if (MVT::isVector(VT))
2273     assert(EVT == MVT::getVectorElementType(VT) && "Invalid vector extload!");
2274   else
2275     assert(EVT < VT && "Should only be an extending load, not truncating!");
2276   assert((ExtType == ISD::EXTLOAD || MVT::isInteger(VT)) &&
2277          "Cannot sign/zero extend a FP/Vector load!");
2278   assert(MVT::isInteger(VT) == MVT::isInteger(EVT) &&
2279          "Cannot convert from FP to Int or Int -> FP!");
2280
2281   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2282     const Type *Ty = 0;
2283     if (VT != MVT::iPTR) {
2284       Ty = MVT::getTypeForValueType(VT);
2285     } else if (SV) {
2286       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2287       assert(PT && "Value for load must be a pointer");
2288       Ty = PT->getElementType();
2289     }  
2290     assert(Ty && "Could not get type information for load");
2291     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2292   }
2293   SDVTList VTs = getVTList(VT, MVT::Other);
2294   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2295   SDOperand Ops[] = { Chain, Ptr, Undef };
2296   FoldingSetNodeID ID;
2297   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2298   ID.AddInteger(ISD::UNINDEXED);
2299   ID.AddInteger(ExtType);
2300   ID.AddInteger((unsigned int)EVT);
2301   ID.AddPointer(SV);
2302   ID.AddInteger(SVOffset);
2303   ID.AddInteger(Alignment);
2304   ID.AddInteger(isVolatile);
2305   void *IP = 0;
2306   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2307     return SDOperand(E, 0);
2308   SDNode *N = new LoadSDNode(Ops, VTs, ISD::UNINDEXED, ExtType, EVT,
2309                              SV, SVOffset, Alignment, isVolatile);
2310   CSEMap.InsertNode(N, IP);
2311   AllNodes.push_back(N);
2312   return SDOperand(N, 0);
2313 }
2314
2315 SDOperand
2316 SelectionDAG::getIndexedLoad(SDOperand OrigLoad, SDOperand Base,
2317                              SDOperand Offset, ISD::MemIndexedMode AM) {
2318   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
2319   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
2320          "Load is already a indexed load!");
2321   MVT::ValueType VT = OrigLoad.getValueType();
2322   SDVTList VTs = getVTList(VT, Base.getValueType(), MVT::Other);
2323   SDOperand Ops[] = { LD->getChain(), Base, Offset };
2324   FoldingSetNodeID ID;
2325   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
2326   ID.AddInteger(AM);
2327   ID.AddInteger(LD->getExtensionType());
2328   ID.AddInteger((unsigned int)(LD->getLoadedVT()));
2329   ID.AddPointer(LD->getSrcValue());
2330   ID.AddInteger(LD->getSrcValueOffset());
2331   ID.AddInteger(LD->getAlignment());
2332   ID.AddInteger(LD->isVolatile());
2333   void *IP = 0;
2334   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2335     return SDOperand(E, 0);
2336   SDNode *N = new LoadSDNode(Ops, VTs, AM,
2337                              LD->getExtensionType(), LD->getLoadedVT(),
2338                              LD->getSrcValue(), LD->getSrcValueOffset(),
2339                              LD->getAlignment(), LD->isVolatile());
2340   CSEMap.InsertNode(N, IP);
2341   AllNodes.push_back(N);
2342   return SDOperand(N, 0);
2343 }
2344
2345 SDOperand SelectionDAG::getStore(SDOperand Chain, SDOperand Val,
2346                                  SDOperand Ptr, const Value *SV, int SVOffset,
2347                                  bool isVolatile, unsigned Alignment) {
2348   MVT::ValueType VT = Val.getValueType();
2349
2350   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2351     const Type *Ty = 0;
2352     if (VT != MVT::iPTR) {
2353       Ty = MVT::getTypeForValueType(VT);
2354     } else if (SV) {
2355       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2356       assert(PT && "Value for store must be a pointer");
2357       Ty = PT->getElementType();
2358     }
2359     assert(Ty && "Could not get type information for store");
2360     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2361   }
2362   SDVTList VTs = getVTList(MVT::Other);
2363   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2364   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2365   FoldingSetNodeID ID;
2366   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2367   ID.AddInteger(ISD::UNINDEXED);
2368   ID.AddInteger(false);
2369   ID.AddInteger((unsigned int)VT);
2370   ID.AddPointer(SV);
2371   ID.AddInteger(SVOffset);
2372   ID.AddInteger(Alignment);
2373   ID.AddInteger(isVolatile);
2374   void *IP = 0;
2375   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2376     return SDOperand(E, 0);
2377   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
2378                               VT, SV, SVOffset, Alignment, isVolatile);
2379   CSEMap.InsertNode(N, IP);
2380   AllNodes.push_back(N);
2381   return SDOperand(N, 0);
2382 }
2383
2384 SDOperand SelectionDAG::getTruncStore(SDOperand Chain, SDOperand Val,
2385                                       SDOperand Ptr, const Value *SV,
2386                                       int SVOffset, MVT::ValueType SVT,
2387                                       bool isVolatile, unsigned Alignment) {
2388   MVT::ValueType VT = Val.getValueType();
2389   bool isTrunc = VT != SVT;
2390
2391   assert(VT > SVT && "Not a truncation?");
2392   assert(MVT::isInteger(VT) == MVT::isInteger(SVT) &&
2393          "Can't do FP-INT conversion!");
2394
2395   if (Alignment == 0) { // Ensure that codegen never sees alignment 0
2396     const Type *Ty = 0;
2397     if (VT != MVT::iPTR) {
2398       Ty = MVT::getTypeForValueType(VT);
2399     } else if (SV) {
2400       const PointerType *PT = dyn_cast<PointerType>(SV->getType());
2401       assert(PT && "Value for store must be a pointer");
2402       Ty = PT->getElementType();
2403     }
2404     assert(Ty && "Could not get type information for store");
2405     Alignment = TLI.getTargetData()->getABITypeAlignment(Ty);
2406   }
2407   SDVTList VTs = getVTList(MVT::Other);
2408   SDOperand Undef = getNode(ISD::UNDEF, Ptr.getValueType());
2409   SDOperand Ops[] = { Chain, Val, Ptr, Undef };
2410   FoldingSetNodeID ID;
2411   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2412   ID.AddInteger(ISD::UNINDEXED);
2413   ID.AddInteger(isTrunc);
2414   ID.AddInteger((unsigned int)SVT);
2415   ID.AddPointer(SV);
2416   ID.AddInteger(SVOffset);
2417   ID.AddInteger(Alignment);
2418   ID.AddInteger(isVolatile);
2419   void *IP = 0;
2420   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2421     return SDOperand(E, 0);
2422   SDNode *N = new StoreSDNode(Ops, VTs, ISD::UNINDEXED, isTrunc,
2423                               SVT, SV, SVOffset, Alignment, isVolatile);
2424   CSEMap.InsertNode(N, IP);
2425   AllNodes.push_back(N);
2426   return SDOperand(N, 0);
2427 }
2428
2429 SDOperand
2430 SelectionDAG::getIndexedStore(SDOperand OrigStore, SDOperand Base,
2431                               SDOperand Offset, ISD::MemIndexedMode AM) {
2432   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
2433   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
2434          "Store is already a indexed store!");
2435   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
2436   SDOperand Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
2437   FoldingSetNodeID ID;
2438   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
2439   ID.AddInteger(AM);
2440   ID.AddInteger(ST->isTruncatingStore());
2441   ID.AddInteger((unsigned int)(ST->getStoredVT()));
2442   ID.AddPointer(ST->getSrcValue());
2443   ID.AddInteger(ST->getSrcValueOffset());
2444   ID.AddInteger(ST->getAlignment());
2445   ID.AddInteger(ST->isVolatile());
2446   void *IP = 0;
2447   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2448     return SDOperand(E, 0);
2449   SDNode *N = new StoreSDNode(Ops, VTs, AM,
2450                               ST->isTruncatingStore(), ST->getStoredVT(),
2451                               ST->getSrcValue(), ST->getSrcValueOffset(),
2452                               ST->getAlignment(), ST->isVolatile());
2453   CSEMap.InsertNode(N, IP);
2454   AllNodes.push_back(N);
2455   return SDOperand(N, 0);
2456 }
2457
2458 SDOperand SelectionDAG::getVAArg(MVT::ValueType VT,
2459                                  SDOperand Chain, SDOperand Ptr,
2460                                  SDOperand SV) {
2461   SDOperand Ops[] = { Chain, Ptr, SV };
2462   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
2463 }
2464
2465 SDOperand SelectionDAG::getNode(unsigned Opcode, MVT::ValueType VT,
2466                                 const SDOperand *Ops, unsigned NumOps) {
2467   switch (NumOps) {
2468   case 0: return getNode(Opcode, VT);
2469   case 1: return getNode(Opcode, VT, Ops[0]);
2470   case 2: return getNode(Opcode, VT, Ops[0], Ops[1]);
2471   case 3: return getNode(Opcode, VT, Ops[0], Ops[1], Ops[2]);
2472   default: break;
2473   }
2474   
2475   switch (Opcode) {
2476   default: break;
2477   case ISD::SELECT_CC: {
2478     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
2479     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
2480            "LHS and RHS of condition must have same type!");
2481     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2482            "True and False arms of SelectCC must have same type!");
2483     assert(Ops[2].getValueType() == VT &&
2484            "select_cc node must be of same type as true and false value!");
2485     break;
2486   }
2487   case ISD::BR_CC: {
2488     assert(NumOps == 5 && "BR_CC takes 5 operands!");
2489     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
2490            "LHS/RHS of comparison should match types!");
2491     break;
2492   }
2493   }
2494
2495   // Memoize nodes.
2496   SDNode *N;
2497   SDVTList VTs = getVTList(VT);
2498   if (VT != MVT::Flag) {
2499     FoldingSetNodeID ID;
2500     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
2501     void *IP = 0;
2502     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2503       return SDOperand(E, 0);
2504     N = new SDNode(Opcode, VTs, Ops, NumOps);
2505     CSEMap.InsertNode(N, IP);
2506   } else {
2507     N = new SDNode(Opcode, VTs, Ops, NumOps);
2508   }
2509   AllNodes.push_back(N);
2510   return SDOperand(N, 0);
2511 }
2512
2513 SDOperand SelectionDAG::getNode(unsigned Opcode,
2514                                 std::vector<MVT::ValueType> &ResultTys,
2515                                 const SDOperand *Ops, unsigned NumOps) {
2516   return getNode(Opcode, getNodeValueTypes(ResultTys), ResultTys.size(),
2517                  Ops, NumOps);
2518 }
2519
2520 SDOperand SelectionDAG::getNode(unsigned Opcode,
2521                                 const MVT::ValueType *VTs, unsigned NumVTs,
2522                                 const SDOperand *Ops, unsigned NumOps) {
2523   if (NumVTs == 1)
2524     return getNode(Opcode, VTs[0], Ops, NumOps);
2525   return getNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps);
2526 }  
2527   
2528 SDOperand SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
2529                                 const SDOperand *Ops, unsigned NumOps) {
2530   if (VTList.NumVTs == 1)
2531     return getNode(Opcode, VTList.VTs[0], Ops, NumOps);
2532
2533   switch (Opcode) {
2534   // FIXME: figure out how to safely handle things like
2535   // int foo(int x) { return 1 << (x & 255); }
2536   // int bar() { return foo(256); }
2537 #if 0
2538   case ISD::SRA_PARTS:
2539   case ISD::SRL_PARTS:
2540   case ISD::SHL_PARTS:
2541     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
2542         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
2543       return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2544     else if (N3.getOpcode() == ISD::AND)
2545       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
2546         // If the and is only masking out bits that cannot effect the shift,
2547         // eliminate the and.
2548         unsigned NumBits = MVT::getSizeInBits(VT)*2;
2549         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
2550           return getNode(Opcode, VT, N1, N2, N3.getOperand(0));
2551       }
2552     break;
2553 #endif
2554   }
2555
2556   // Memoize the node unless it returns a flag.
2557   SDNode *N;
2558   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
2559     FoldingSetNodeID ID;
2560     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
2561     void *IP = 0;
2562     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2563       return SDOperand(E, 0);
2564     if (NumOps == 1)
2565       N = new UnarySDNode(Opcode, VTList, Ops[0]);
2566     else if (NumOps == 2)
2567       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2568     else if (NumOps == 3)
2569       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2570     else
2571       N = new SDNode(Opcode, VTList, Ops, NumOps);
2572     CSEMap.InsertNode(N, IP);
2573   } else {
2574     if (NumOps == 1)
2575       N = new UnarySDNode(Opcode, VTList, Ops[0]);
2576     else if (NumOps == 2)
2577       N = new BinarySDNode(Opcode, VTList, Ops[0], Ops[1]);
2578     else if (NumOps == 3)
2579       N = new TernarySDNode(Opcode, VTList, Ops[0], Ops[1], Ops[2]);
2580     else
2581       N = new SDNode(Opcode, VTList, Ops, NumOps);
2582   }
2583   AllNodes.push_back(N);
2584   return SDOperand(N, 0);
2585 }
2586
2587 SDVTList SelectionDAG::getVTList(MVT::ValueType VT) {
2588   if (!MVT::isExtendedVT(VT))
2589     return makeVTList(SDNode::getValueTypeList(VT), 1);
2590
2591   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2592        E = VTList.end(); I != E; ++I) {
2593     if (I->size() == 1 && (*I)[0] == VT)
2594       return makeVTList(&(*I)[0], 1);
2595   }
2596   std::vector<MVT::ValueType> V;
2597   V.push_back(VT);
2598   VTList.push_front(V);
2599   return makeVTList(&(*VTList.begin())[0], 1);
2600 }
2601
2602 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2) {
2603   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2604        E = VTList.end(); I != E; ++I) {
2605     if (I->size() == 2 && (*I)[0] == VT1 && (*I)[1] == VT2)
2606       return makeVTList(&(*I)[0], 2);
2607   }
2608   std::vector<MVT::ValueType> V;
2609   V.push_back(VT1);
2610   V.push_back(VT2);
2611   VTList.push_front(V);
2612   return makeVTList(&(*VTList.begin())[0], 2);
2613 }
2614 SDVTList SelectionDAG::getVTList(MVT::ValueType VT1, MVT::ValueType VT2,
2615                                  MVT::ValueType VT3) {
2616   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2617        E = VTList.end(); I != E; ++I) {
2618     if (I->size() == 3 && (*I)[0] == VT1 && (*I)[1] == VT2 &&
2619         (*I)[2] == VT3)
2620       return makeVTList(&(*I)[0], 3);
2621   }
2622   std::vector<MVT::ValueType> V;
2623   V.push_back(VT1);
2624   V.push_back(VT2);
2625   V.push_back(VT3);
2626   VTList.push_front(V);
2627   return makeVTList(&(*VTList.begin())[0], 3);
2628 }
2629
2630 SDVTList SelectionDAG::getVTList(const MVT::ValueType *VTs, unsigned NumVTs) {
2631   switch (NumVTs) {
2632     case 0: assert(0 && "Cannot have nodes without results!");
2633     case 1: return getVTList(VTs[0]);
2634     case 2: return getVTList(VTs[0], VTs[1]);
2635     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
2636     default: break;
2637   }
2638
2639   for (std::list<std::vector<MVT::ValueType> >::iterator I = VTList.begin(),
2640        E = VTList.end(); I != E; ++I) {
2641     if (I->size() != NumVTs || VTs[0] != (*I)[0] || VTs[1] != (*I)[1]) continue;
2642    
2643     bool NoMatch = false;
2644     for (unsigned i = 2; i != NumVTs; ++i)
2645       if (VTs[i] != (*I)[i]) {
2646         NoMatch = true;
2647         break;
2648       }
2649     if (!NoMatch)
2650       return makeVTList(&*I->begin(), NumVTs);
2651   }
2652   
2653   VTList.push_front(std::vector<MVT::ValueType>(VTs, VTs+NumVTs));
2654   return makeVTList(&*VTList.begin()->begin(), NumVTs);
2655 }
2656
2657
2658 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
2659 /// specified operands.  If the resultant node already exists in the DAG,
2660 /// this does not modify the specified node, instead it returns the node that
2661 /// already exists.  If the resultant node does not exist in the DAG, the
2662 /// input node is returned.  As a degenerate case, if you specify the same
2663 /// input operands as the node already has, the input node is returned.
2664 SDOperand SelectionDAG::
2665 UpdateNodeOperands(SDOperand InN, SDOperand Op) {
2666   SDNode *N = InN.Val;
2667   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
2668   
2669   // Check to see if there is no change.
2670   if (Op == N->getOperand(0)) return InN;
2671   
2672   // See if the modified node already exists.
2673   void *InsertPos = 0;
2674   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
2675     return SDOperand(Existing, InN.ResNo);
2676   
2677   // Nope it doesn't.  Remove the node from it's current place in the maps.
2678   if (InsertPos)
2679     RemoveNodeFromCSEMaps(N);
2680   
2681   // Now we update the operands.
2682   N->OperandList[0].Val->removeUser(N);
2683   Op.Val->addUser(N);
2684   N->OperandList[0] = Op;
2685   
2686   // If this gets put into a CSE map, add it.
2687   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2688   return InN;
2689 }
2690
2691 SDOperand SelectionDAG::
2692 UpdateNodeOperands(SDOperand InN, SDOperand Op1, SDOperand Op2) {
2693   SDNode *N = InN.Val;
2694   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
2695   
2696   // Check to see if there is no change.
2697   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
2698     return InN;   // No operands changed, just return the input node.
2699   
2700   // See if the modified node already exists.
2701   void *InsertPos = 0;
2702   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
2703     return SDOperand(Existing, InN.ResNo);
2704   
2705   // Nope it doesn't.  Remove the node from it's current place in the maps.
2706   if (InsertPos)
2707     RemoveNodeFromCSEMaps(N);
2708   
2709   // Now we update the operands.
2710   if (N->OperandList[0] != Op1) {
2711     N->OperandList[0].Val->removeUser(N);
2712     Op1.Val->addUser(N);
2713     N->OperandList[0] = Op1;
2714   }
2715   if (N->OperandList[1] != Op2) {
2716     N->OperandList[1].Val->removeUser(N);
2717     Op2.Val->addUser(N);
2718     N->OperandList[1] = Op2;
2719   }
2720   
2721   // If this gets put into a CSE map, add it.
2722   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2723   return InN;
2724 }
2725
2726 SDOperand SelectionDAG::
2727 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, SDOperand Op3) {
2728   SDOperand Ops[] = { Op1, Op2, Op3 };
2729   return UpdateNodeOperands(N, Ops, 3);
2730 }
2731
2732 SDOperand SelectionDAG::
2733 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2, 
2734                    SDOperand Op3, SDOperand Op4) {
2735   SDOperand Ops[] = { Op1, Op2, Op3, Op4 };
2736   return UpdateNodeOperands(N, Ops, 4);
2737 }
2738
2739 SDOperand SelectionDAG::
2740 UpdateNodeOperands(SDOperand N, SDOperand Op1, SDOperand Op2,
2741                    SDOperand Op3, SDOperand Op4, SDOperand Op5) {
2742   SDOperand Ops[] = { Op1, Op2, Op3, Op4, Op5 };
2743   return UpdateNodeOperands(N, Ops, 5);
2744 }
2745
2746
2747 SDOperand SelectionDAG::
2748 UpdateNodeOperands(SDOperand InN, SDOperand *Ops, unsigned NumOps) {
2749   SDNode *N = InN.Val;
2750   assert(N->getNumOperands() == NumOps &&
2751          "Update with wrong number of operands");
2752   
2753   // Check to see if there is no change.
2754   bool AnyChange = false;
2755   for (unsigned i = 0; i != NumOps; ++i) {
2756     if (Ops[i] != N->getOperand(i)) {
2757       AnyChange = true;
2758       break;
2759     }
2760   }
2761   
2762   // No operands changed, just return the input node.
2763   if (!AnyChange) return InN;
2764   
2765   // See if the modified node already exists.
2766   void *InsertPos = 0;
2767   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
2768     return SDOperand(Existing, InN.ResNo);
2769   
2770   // Nope it doesn't.  Remove the node from it's current place in the maps.
2771   if (InsertPos)
2772     RemoveNodeFromCSEMaps(N);
2773   
2774   // Now we update the operands.
2775   for (unsigned i = 0; i != NumOps; ++i) {
2776     if (N->OperandList[i] != Ops[i]) {
2777       N->OperandList[i].Val->removeUser(N);
2778       Ops[i].Val->addUser(N);
2779       N->OperandList[i] = Ops[i];
2780     }
2781   }
2782
2783   // If this gets put into a CSE map, add it.
2784   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
2785   return InN;
2786 }
2787
2788
2789 /// MorphNodeTo - This frees the operands of the current node, resets the
2790 /// opcode, types, and operands to the specified value.  This should only be
2791 /// used by the SelectionDAG class.
2792 void SDNode::MorphNodeTo(unsigned Opc, SDVTList L,
2793                          const SDOperand *Ops, unsigned NumOps) {
2794   NodeType = Opc;
2795   ValueList = L.VTs;
2796   NumValues = L.NumVTs;
2797   
2798   // Clear the operands list, updating used nodes to remove this from their
2799   // use list.
2800   for (op_iterator I = op_begin(), E = op_end(); I != E; ++I)
2801     I->Val->removeUser(this);
2802   
2803   // If NumOps is larger than the # of operands we currently have, reallocate
2804   // the operand list.
2805   if (NumOps > NumOperands) {
2806     if (OperandsNeedDelete)
2807       delete [] OperandList;
2808     OperandList = new SDOperand[NumOps];
2809     OperandsNeedDelete = true;
2810   }
2811   
2812   // Assign the new operands.
2813   NumOperands = NumOps;
2814   
2815   for (unsigned i = 0, e = NumOps; i != e; ++i) {
2816     OperandList[i] = Ops[i];
2817     SDNode *N = OperandList[i].Val;
2818     N->Uses.push_back(this);
2819   }
2820 }
2821
2822 /// SelectNodeTo - These are used for target selectors to *mutate* the
2823 /// specified node to have the specified return type, Target opcode, and
2824 /// operands.  Note that target opcodes are stored as
2825 /// ISD::BUILTIN_OP_END+TargetOpcode in the node opcode field.
2826 ///
2827 /// Note that SelectNodeTo returns the resultant node.  If there is already a
2828 /// node of the specified opcode and operands, it returns that node instead of
2829 /// the current one.
2830 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2831                                    MVT::ValueType VT) {
2832   SDVTList VTs = getVTList(VT);
2833   FoldingSetNodeID ID;
2834   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2835   void *IP = 0;
2836   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2837     return ON;
2838    
2839   RemoveNodeFromCSEMaps(N);
2840   
2841   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, 0, 0);
2842
2843   CSEMap.InsertNode(N, IP);
2844   return N;
2845 }
2846
2847 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2848                                    MVT::ValueType VT, SDOperand Op1) {
2849   // If an identical node already exists, use it.
2850   SDVTList VTs = getVTList(VT);
2851   SDOperand Ops[] = { Op1 };
2852   
2853   FoldingSetNodeID ID;
2854   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2855   void *IP = 0;
2856   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2857     return ON;
2858                                        
2859   RemoveNodeFromCSEMaps(N);
2860   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 1);
2861   CSEMap.InsertNode(N, IP);
2862   return N;
2863 }
2864
2865 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2866                                    MVT::ValueType VT, SDOperand Op1,
2867                                    SDOperand Op2) {
2868   // If an identical node already exists, use it.
2869   SDVTList VTs = getVTList(VT);
2870   SDOperand Ops[] = { Op1, Op2 };
2871   
2872   FoldingSetNodeID ID;
2873   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2874   void *IP = 0;
2875   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2876     return ON;
2877                                        
2878   RemoveNodeFromCSEMaps(N);
2879   
2880   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2881   
2882   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2883   return N;
2884 }
2885
2886 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2887                                    MVT::ValueType VT, SDOperand Op1,
2888                                    SDOperand Op2, SDOperand Op3) {
2889   // If an identical node already exists, use it.
2890   SDVTList VTs = getVTList(VT);
2891   SDOperand Ops[] = { Op1, Op2, Op3 };
2892   FoldingSetNodeID ID;
2893   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2894   void *IP = 0;
2895   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2896     return ON;
2897                                        
2898   RemoveNodeFromCSEMaps(N);
2899   
2900   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2901
2902   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2903   return N;
2904 }
2905
2906 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2907                                    MVT::ValueType VT, const SDOperand *Ops,
2908                                    unsigned NumOps) {
2909   // If an identical node already exists, use it.
2910   SDVTList VTs = getVTList(VT);
2911   FoldingSetNodeID ID;
2912   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2913   void *IP = 0;
2914   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2915     return ON;
2916                                        
2917   RemoveNodeFromCSEMaps(N);
2918   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, NumOps);
2919   
2920   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2921   return N;
2922 }
2923
2924 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc, 
2925                                    MVT::ValueType VT1, MVT::ValueType VT2,
2926                                    SDOperand Op1, SDOperand Op2) {
2927   SDVTList VTs = getVTList(VT1, VT2);
2928   FoldingSetNodeID ID;
2929   SDOperand Ops[] = { Op1, Op2 };
2930   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2931   void *IP = 0;
2932   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2933     return ON;
2934
2935   RemoveNodeFromCSEMaps(N);
2936   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 2);
2937   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2938   return N;
2939 }
2940
2941 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned TargetOpc,
2942                                    MVT::ValueType VT1, MVT::ValueType VT2,
2943                                    SDOperand Op1, SDOperand Op2, 
2944                                    SDOperand Op3) {
2945   // If an identical node already exists, use it.
2946   SDVTList VTs = getVTList(VT1, VT2);
2947   SDOperand Ops[] = { Op1, Op2, Op3 };
2948   FoldingSetNodeID ID;
2949   AddNodeIDNode(ID, ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2950   void *IP = 0;
2951   if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
2952     return ON;
2953
2954   RemoveNodeFromCSEMaps(N);
2955
2956   N->MorphNodeTo(ISD::BUILTIN_OP_END+TargetOpc, VTs, Ops, 3);
2957   CSEMap.InsertNode(N, IP);   // Memoize the new node.
2958   return N;
2959 }
2960
2961
2962 /// getTargetNode - These are used for target selectors to create a new node
2963 /// with specified return type(s), target opcode, and operands.
2964 ///
2965 /// Note that getTargetNode returns the resultant node.  If there is already a
2966 /// node of the specified opcode and operands, it returns that node instead of
2967 /// the current one.
2968 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT) {
2969   return getNode(ISD::BUILTIN_OP_END+Opcode, VT).Val;
2970 }
2971 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2972                                     SDOperand Op1) {
2973   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1).Val;
2974 }
2975 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2976                                     SDOperand Op1, SDOperand Op2) {
2977   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2).Val;
2978 }
2979 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2980                                     SDOperand Op1, SDOperand Op2,
2981                                     SDOperand Op3) {
2982   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Op1, Op2, Op3).Val;
2983 }
2984 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT,
2985                                     const SDOperand *Ops, unsigned NumOps) {
2986   return getNode(ISD::BUILTIN_OP_END+Opcode, VT, Ops, NumOps).Val;
2987 }
2988 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2989                                     MVT::ValueType VT2, SDOperand Op1) {
2990   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2991   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, &Op1, 1).Val;
2992 }
2993 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
2994                                     MVT::ValueType VT2, SDOperand Op1,
2995                                     SDOperand Op2) {
2996   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
2997   SDOperand Ops[] = { Op1, Op2 };
2998   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 2).Val;
2999 }
3000 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3001                                     MVT::ValueType VT2, SDOperand Op1,
3002                                     SDOperand Op2, SDOperand Op3) {
3003   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3004   SDOperand Ops[] = { Op1, Op2, Op3 };
3005   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, 3).Val;
3006 }
3007 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3008                                     MVT::ValueType VT2,
3009                                     const SDOperand *Ops, unsigned NumOps) {
3010   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2);
3011   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 2, Ops, NumOps).Val;
3012 }
3013 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3014                                     MVT::ValueType VT2, MVT::ValueType VT3,
3015                                     SDOperand Op1, SDOperand Op2) {
3016   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3017   SDOperand Ops[] = { Op1, Op2 };
3018   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 2).Val;
3019 }
3020 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1,
3021                                     MVT::ValueType VT2, MVT::ValueType VT3,
3022                                     SDOperand Op1, SDOperand Op2,
3023                                     SDOperand Op3) {
3024   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3025   SDOperand Ops[] = { Op1, Op2, Op3 };
3026   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, 3).Val;
3027 }
3028 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3029                                     MVT::ValueType VT2, MVT::ValueType VT3,
3030                                     const SDOperand *Ops, unsigned NumOps) {
3031   const MVT::ValueType *VTs = getNodeValueTypes(VT1, VT2, VT3);
3032   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 3, Ops, NumOps).Val;
3033 }
3034 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT::ValueType VT1, 
3035                                     MVT::ValueType VT2, MVT::ValueType VT3,
3036                                     MVT::ValueType VT4,
3037                                     const SDOperand *Ops, unsigned NumOps) {
3038   std::vector<MVT::ValueType> VTList;
3039   VTList.push_back(VT1);
3040   VTList.push_back(VT2);
3041   VTList.push_back(VT3);
3042   VTList.push_back(VT4);
3043   const MVT::ValueType *VTs = getNodeValueTypes(VTList);
3044   return getNode(ISD::BUILTIN_OP_END+Opcode, VTs, 4, Ops, NumOps).Val;
3045 }
3046
3047 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3048 /// This can cause recursive merging of nodes in the DAG.
3049 ///
3050 /// This version assumes From/To have a single result value.
3051 ///
3052 void SelectionDAG::ReplaceAllUsesWith(SDOperand FromN, SDOperand ToN,
3053                                       std::vector<SDNode*> *Deleted) {
3054   SDNode *From = FromN.Val, *To = ToN.Val;
3055   assert(From->getNumValues() == 1 && To->getNumValues() == 1 &&
3056          "Cannot replace with this method!");
3057   assert(From != To && "Cannot replace uses of with self");
3058   
3059   while (!From->use_empty()) {
3060     // Process users until they are all gone.
3061     SDNode *U = *From->use_begin();
3062     
3063     // This node is about to morph, remove its old self from the CSE maps.
3064     RemoveNodeFromCSEMaps(U);
3065     
3066     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3067          I != E; ++I)
3068       if (I->Val == From) {
3069         From->removeUser(U);
3070         I->Val = To;
3071         To->addUser(U);
3072       }
3073
3074     // Now that we have modified U, add it back to the CSE maps.  If it already
3075     // exists there, recursively merge the results together.
3076     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3077       ReplaceAllUsesWith(U, Existing, Deleted);
3078       // U is now dead.
3079       if (Deleted) Deleted->push_back(U);
3080       DeleteNodeNotInCSEMaps(U);
3081     }
3082   }
3083 }
3084
3085 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3086 /// This can cause recursive merging of nodes in the DAG.
3087 ///
3088 /// This version assumes From/To have matching types and numbers of result
3089 /// values.
3090 ///
3091 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
3092                                       std::vector<SDNode*> *Deleted) {
3093   assert(From != To && "Cannot replace uses of with self");
3094   assert(From->getNumValues() == To->getNumValues() &&
3095          "Cannot use this version of ReplaceAllUsesWith!");
3096   if (From->getNumValues() == 1) {  // If possible, use the faster version.
3097     ReplaceAllUsesWith(SDOperand(From, 0), SDOperand(To, 0), Deleted);
3098     return;
3099   }
3100   
3101   while (!From->use_empty()) {
3102     // Process users until they are all gone.
3103     SDNode *U = *From->use_begin();
3104     
3105     // This node is about to morph, remove its old self from the CSE maps.
3106     RemoveNodeFromCSEMaps(U);
3107     
3108     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3109          I != E; ++I)
3110       if (I->Val == From) {
3111         From->removeUser(U);
3112         I->Val = To;
3113         To->addUser(U);
3114       }
3115         
3116     // Now that we have modified U, add it back to the CSE maps.  If it already
3117     // exists there, recursively merge the results together.
3118     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3119       ReplaceAllUsesWith(U, Existing, Deleted);
3120       // U is now dead.
3121       if (Deleted) Deleted->push_back(U);
3122       DeleteNodeNotInCSEMaps(U);
3123     }
3124   }
3125 }
3126
3127 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
3128 /// This can cause recursive merging of nodes in the DAG.
3129 ///
3130 /// This version can replace From with any result values.  To must match the
3131 /// number and types of values returned by From.
3132 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
3133                                       const SDOperand *To,
3134                                       std::vector<SDNode*> *Deleted) {
3135   if (From->getNumValues() == 1 && To[0].Val->getNumValues() == 1) {
3136     // Degenerate case handled above.
3137     ReplaceAllUsesWith(SDOperand(From, 0), To[0], Deleted);
3138     return;
3139   }
3140
3141   while (!From->use_empty()) {
3142     // Process users until they are all gone.
3143     SDNode *U = *From->use_begin();
3144     
3145     // This node is about to morph, remove its old self from the CSE maps.
3146     RemoveNodeFromCSEMaps(U);
3147     
3148     for (SDOperand *I = U->OperandList, *E = U->OperandList+U->NumOperands;
3149          I != E; ++I)
3150       if (I->Val == From) {
3151         const SDOperand &ToOp = To[I->ResNo];
3152         From->removeUser(U);
3153         *I = ToOp;
3154         ToOp.Val->addUser(U);
3155       }
3156         
3157     // Now that we have modified U, add it back to the CSE maps.  If it already
3158     // exists there, recursively merge the results together.
3159     if (SDNode *Existing = AddNonLeafNodeToCSEMaps(U)) {
3160       ReplaceAllUsesWith(U, Existing, Deleted);
3161       // U is now dead.
3162       if (Deleted) Deleted->push_back(U);
3163       DeleteNodeNotInCSEMaps(U);
3164     }
3165   }
3166 }
3167
3168 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
3169 /// uses of other values produced by From.Val alone.  The Deleted vector is
3170 /// handled the same was as for ReplaceAllUsesWith.
3171 void SelectionDAG::ReplaceAllUsesOfValueWith(SDOperand From, SDOperand To,
3172                                              std::vector<SDNode*> &Deleted) {
3173   assert(From != To && "Cannot replace a value with itself");
3174   // Handle the simple, trivial, case efficiently.
3175   if (From.Val->getNumValues() == 1 && To.Val->getNumValues() == 1) {
3176     ReplaceAllUsesWith(From, To, &Deleted);
3177     return;
3178   }
3179   
3180   // Get all of the users of From.Val.  We want these in a nice,
3181   // deterministically ordered and uniqued set, so we use a SmallSetVector.
3182   SmallSetVector<SDNode*, 16> Users(From.Val->use_begin(), From.Val->use_end());
3183
3184   while (!Users.empty()) {
3185     // We know that this user uses some value of From.  If it is the right
3186     // value, update it.
3187     SDNode *User = Users.back();
3188     Users.pop_back();
3189     
3190     for (SDOperand *Op = User->OperandList,
3191          *E = User->OperandList+User->NumOperands; Op != E; ++Op) {
3192       if (*Op == From) {
3193         // Okay, we know this user needs to be updated.  Remove its old self
3194         // from the CSE maps.
3195         RemoveNodeFromCSEMaps(User);
3196         
3197         // Update all operands that match "From".
3198         for (; Op != E; ++Op) {
3199           if (*Op == From) {
3200             From.Val->removeUser(User);
3201             *Op = To;
3202             To.Val->addUser(User);
3203           }
3204         }
3205                    
3206         // Now that we have modified User, add it back to the CSE maps.  If it
3207         // already exists there, recursively merge the results together.
3208         if (SDNode *Existing = AddNonLeafNodeToCSEMaps(User)) {
3209           unsigned NumDeleted = Deleted.size();
3210           ReplaceAllUsesWith(User, Existing, &Deleted);
3211           
3212           // User is now dead.
3213           Deleted.push_back(User);
3214           DeleteNodeNotInCSEMaps(User);
3215           
3216           // We have to be careful here, because ReplaceAllUsesWith could have
3217           // deleted a user of From, which means there may be dangling pointers
3218           // in the "Users" setvector.  Scan over the deleted node pointers and
3219           // remove them from the setvector.
3220           for (unsigned i = NumDeleted, e = Deleted.size(); i != e; ++i)
3221             Users.remove(Deleted[i]);
3222         }
3223         break;   // Exit the operand scanning loop.
3224       }
3225     }
3226   }
3227 }
3228
3229
3230 /// AssignNodeIds - Assign a unique node id for each node in the DAG based on
3231 /// their allnodes order. It returns the maximum id.
3232 unsigned SelectionDAG::AssignNodeIds() {
3233   unsigned Id = 0;
3234   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I){
3235     SDNode *N = I;
3236     N->setNodeId(Id++);
3237   }
3238   return Id;
3239 }
3240
3241 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
3242 /// based on their topological order. It returns the maximum id and a vector
3243 /// of the SDNodes* in assigned order by reference.
3244 unsigned SelectionDAG::AssignTopologicalOrder(std::vector<SDNode*> &TopOrder) {
3245   unsigned DAGSize = AllNodes.size();
3246   std::vector<unsigned> InDegree(DAGSize);
3247   std::vector<SDNode*> Sources;
3248
3249   // Use a two pass approach to avoid using a std::map which is slow.
3250   unsigned Id = 0;
3251   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I){
3252     SDNode *N = I;
3253     N->setNodeId(Id++);
3254     unsigned Degree = N->use_size();
3255     InDegree[N->getNodeId()] = Degree;
3256     if (Degree == 0)
3257       Sources.push_back(N);
3258   }
3259
3260   TopOrder.clear();
3261   while (!Sources.empty()) {
3262     SDNode *N = Sources.back();
3263     Sources.pop_back();
3264     TopOrder.push_back(N);
3265     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
3266       SDNode *P = I->Val;
3267       unsigned Degree = --InDegree[P->getNodeId()];
3268       if (Degree == 0)
3269         Sources.push_back(P);
3270     }
3271   }
3272
3273   // Second pass, assign the actual topological order as node ids.
3274   Id = 0;
3275   for (std::vector<SDNode*>::iterator TI = TopOrder.begin(),TE = TopOrder.end();
3276        TI != TE; ++TI)
3277     (*TI)->setNodeId(Id++);
3278
3279   return Id;
3280 }
3281
3282
3283
3284 //===----------------------------------------------------------------------===//
3285 //                              SDNode Class
3286 //===----------------------------------------------------------------------===//
3287
3288 // Out-of-line virtual method to give class a home.
3289 void SDNode::ANCHOR() {}
3290 void UnarySDNode::ANCHOR() {}
3291 void BinarySDNode::ANCHOR() {}
3292 void TernarySDNode::ANCHOR() {}
3293 void HandleSDNode::ANCHOR() {}
3294 void StringSDNode::ANCHOR() {}
3295 void ConstantSDNode::ANCHOR() {}
3296 void ConstantFPSDNode::ANCHOR() {}
3297 void GlobalAddressSDNode::ANCHOR() {}
3298 void FrameIndexSDNode::ANCHOR() {}
3299 void JumpTableSDNode::ANCHOR() {}
3300 void ConstantPoolSDNode::ANCHOR() {}
3301 void BasicBlockSDNode::ANCHOR() {}
3302 void SrcValueSDNode::ANCHOR() {}
3303 void RegisterSDNode::ANCHOR() {}
3304 void ExternalSymbolSDNode::ANCHOR() {}
3305 void CondCodeSDNode::ANCHOR() {}
3306 void VTSDNode::ANCHOR() {}
3307 void LoadSDNode::ANCHOR() {}
3308 void StoreSDNode::ANCHOR() {}
3309
3310 HandleSDNode::~HandleSDNode() {
3311   SDVTList VTs = { 0, 0 };
3312   MorphNodeTo(ISD::HANDLENODE, VTs, 0, 0);  // Drops operand uses.
3313 }
3314
3315 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
3316                                          MVT::ValueType VT, int o)
3317   : SDNode(isa<GlobalVariable>(GA) &&
3318            cast<GlobalVariable>(GA)->isThreadLocal() ?
3319            // Thread Local
3320            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
3321            // Non Thread Local
3322            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
3323            getSDVTList(VT)), Offset(o) {
3324   TheGlobal = const_cast<GlobalValue*>(GA);
3325 }
3326
3327 /// Profile - Gather unique data for the node.
3328 ///
3329 void SDNode::Profile(FoldingSetNodeID &ID) {
3330   AddNodeIDNode(ID, this);
3331 }
3332
3333 /// getValueTypeList - Return a pointer to the specified value type.
3334 ///
3335 MVT::ValueType *SDNode::getValueTypeList(MVT::ValueType VT) {
3336   static MVT::ValueType VTs[MVT::LAST_VALUETYPE];
3337   VTs[VT] = VT;
3338   return &VTs[VT];
3339 }
3340   
3341 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
3342 /// indicated value.  This method ignores uses of other values defined by this
3343 /// operation.
3344 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
3345   assert(Value < getNumValues() && "Bad value!");
3346
3347   // If there is only one value, this is easy.
3348   if (getNumValues() == 1)
3349     return use_size() == NUses;
3350   if (use_size() < NUses) return false;
3351
3352   SDOperand TheValue(const_cast<SDNode *>(this), Value);
3353
3354   SmallPtrSet<SDNode*, 32> UsersHandled;
3355
3356   for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3357     SDNode *User = *UI;
3358     if (User->getNumOperands() == 1 ||
3359         UsersHandled.insert(User))     // First time we've seen this?
3360       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3361         if (User->getOperand(i) == TheValue) {
3362           if (NUses == 0)
3363             return false;   // too many uses
3364           --NUses;
3365         }
3366   }
3367
3368   // Found exactly the right number of uses?
3369   return NUses == 0;
3370 }
3371
3372
3373 /// hasAnyUseOfValue - Return true if there are any use of the indicated
3374 /// value. This method ignores uses of other values defined by this operation.
3375 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
3376   assert(Value < getNumValues() && "Bad value!");
3377
3378   if (use_size() == 0) return false;
3379
3380   SDOperand TheValue(const_cast<SDNode *>(this), Value);
3381
3382   SmallPtrSet<SDNode*, 32> UsersHandled;
3383
3384   for (SDNode::use_iterator UI = Uses.begin(), E = Uses.end(); UI != E; ++UI) {
3385     SDNode *User = *UI;
3386     if (User->getNumOperands() == 1 ||
3387         UsersHandled.insert(User))     // First time we've seen this?
3388       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i)
3389         if (User->getOperand(i) == TheValue) {
3390           return true;
3391         }
3392   }
3393
3394   return false;
3395 }
3396
3397
3398 /// isOnlyUse - Return true if this node is the only use of N.
3399 ///
3400 bool SDNode::isOnlyUse(SDNode *N) const {
3401   bool Seen = false;
3402   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
3403     SDNode *User = *I;
3404     if (User == this)
3405       Seen = true;
3406     else
3407       return false;
3408   }
3409
3410   return Seen;
3411 }
3412
3413 /// isOperand - Return true if this node is an operand of N.
3414 ///
3415 bool SDOperand::isOperand(SDNode *N) const {
3416   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3417     if (*this == N->getOperand(i))
3418       return true;
3419   return false;
3420 }
3421
3422 bool SDNode::isOperand(SDNode *N) const {
3423   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
3424     if (this == N->OperandList[i].Val)
3425       return true;
3426   return false;
3427 }
3428
3429 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
3430                             SmallPtrSet<SDNode *, 32> &Visited) {
3431   if (found || !Visited.insert(N))
3432     return;
3433
3434   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
3435     SDNode *Op = N->getOperand(i).Val;
3436     if (Op == P) {
3437       found = true;
3438       return;
3439     }
3440     findPredecessor(Op, P, found, Visited);
3441   }
3442 }
3443
3444 /// isPredecessor - Return true if this node is a predecessor of N. This node
3445 /// is either an operand of N or it can be reached by recursively traversing
3446 /// up the operands.
3447 /// NOTE: this is an expensive method. Use it carefully.
3448 bool SDNode::isPredecessor(SDNode *N) const {
3449   SmallPtrSet<SDNode *, 32> Visited;
3450   bool found = false;
3451   findPredecessor(N, this, found, Visited);
3452   return found;
3453 }
3454
3455 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
3456   assert(Num < NumOperands && "Invalid child # of SDNode!");
3457   return cast<ConstantSDNode>(OperandList[Num])->getValue();
3458 }
3459
3460 std::string SDNode::getOperationName(const SelectionDAG *G) const {
3461   switch (getOpcode()) {
3462   default:
3463     if (getOpcode() < ISD::BUILTIN_OP_END)
3464       return "<<Unknown DAG Node>>";
3465     else {
3466       if (G) {
3467         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
3468           if (getOpcode()-ISD::BUILTIN_OP_END < TII->getNumOpcodes())
3469             return TII->getName(getOpcode()-ISD::BUILTIN_OP_END);
3470
3471         TargetLowering &TLI = G->getTargetLoweringInfo();
3472         const char *Name =
3473           TLI.getTargetNodeName(getOpcode());
3474         if (Name) return Name;
3475       }
3476
3477       return "<<Unknown Target Node>>";
3478     }
3479    
3480   case ISD::PCMARKER:      return "PCMarker";
3481   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
3482   case ISD::SRCVALUE:      return "SrcValue";
3483   case ISD::EntryToken:    return "EntryToken";
3484   case ISD::TokenFactor:   return "TokenFactor";
3485   case ISD::AssertSext:    return "AssertSext";
3486   case ISD::AssertZext:    return "AssertZext";
3487
3488   case ISD::STRING:        return "String";
3489   case ISD::BasicBlock:    return "BasicBlock";
3490   case ISD::VALUETYPE:     return "ValueType";
3491   case ISD::Register:      return "Register";
3492
3493   case ISD::Constant:      return "Constant";
3494   case ISD::ConstantFP:    return "ConstantFP";
3495   case ISD::GlobalAddress: return "GlobalAddress";
3496   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
3497   case ISD::FrameIndex:    return "FrameIndex";
3498   case ISD::JumpTable:     return "JumpTable";
3499   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
3500   case ISD::RETURNADDR: return "RETURNADDR";
3501   case ISD::FRAMEADDR: return "FRAMEADDR";
3502   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
3503   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
3504   case ISD::EHSELECTION: return "EHSELECTION";
3505   case ISD::EH_RETURN: return "EH_RETURN";
3506   case ISD::ConstantPool:  return "ConstantPool";
3507   case ISD::ExternalSymbol: return "ExternalSymbol";
3508   case ISD::INTRINSIC_WO_CHAIN: {
3509     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getValue();
3510     return Intrinsic::getName((Intrinsic::ID)IID);
3511   }
3512   case ISD::INTRINSIC_VOID:
3513   case ISD::INTRINSIC_W_CHAIN: {
3514     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getValue();
3515     return Intrinsic::getName((Intrinsic::ID)IID);
3516   }
3517
3518   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
3519   case ISD::TargetConstant: return "TargetConstant";
3520   case ISD::TargetConstantFP:return "TargetConstantFP";
3521   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
3522   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
3523   case ISD::TargetFrameIndex: return "TargetFrameIndex";
3524   case ISD::TargetJumpTable:  return "TargetJumpTable";
3525   case ISD::TargetConstantPool:  return "TargetConstantPool";
3526   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
3527
3528   case ISD::CopyToReg:     return "CopyToReg";
3529   case ISD::CopyFromReg:   return "CopyFromReg";
3530   case ISD::UNDEF:         return "undef";
3531   case ISD::MERGE_VALUES:  return "merge_values";
3532   case ISD::INLINEASM:     return "inlineasm";
3533   case ISD::LABEL:         return "label";
3534   case ISD::HANDLENODE:    return "handlenode";
3535   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
3536   case ISD::CALL:          return "call";
3537     
3538   // Unary operators
3539   case ISD::FABS:   return "fabs";
3540   case ISD::FNEG:   return "fneg";
3541   case ISD::FSQRT:  return "fsqrt";
3542   case ISD::FSIN:   return "fsin";
3543   case ISD::FCOS:   return "fcos";
3544   case ISD::FPOWI:  return "fpowi";
3545
3546   // Binary operators
3547   case ISD::ADD:    return "add";
3548   case ISD::SUB:    return "sub";
3549   case ISD::MUL:    return "mul";
3550   case ISD::MULHU:  return "mulhu";
3551   case ISD::MULHS:  return "mulhs";
3552   case ISD::SDIV:   return "sdiv";
3553   case ISD::UDIV:   return "udiv";
3554   case ISD::SREM:   return "srem";
3555   case ISD::UREM:   return "urem";
3556   case ISD::AND:    return "and";
3557   case ISD::OR:     return "or";
3558   case ISD::XOR:    return "xor";
3559   case ISD::SHL:    return "shl";
3560   case ISD::SRA:    return "sra";
3561   case ISD::SRL:    return "srl";
3562   case ISD::ROTL:   return "rotl";
3563   case ISD::ROTR:   return "rotr";
3564   case ISD::FADD:   return "fadd";
3565   case ISD::FSUB:   return "fsub";
3566   case ISD::FMUL:   return "fmul";
3567   case ISD::FDIV:   return "fdiv";
3568   case ISD::FREM:   return "frem";
3569   case ISD::FCOPYSIGN: return "fcopysign";
3570
3571   case ISD::SETCC:       return "setcc";
3572   case ISD::SELECT:      return "select";
3573   case ISD::SELECT_CC:   return "select_cc";
3574   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
3575   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
3576   case ISD::CONCAT_VECTORS:      return "concat_vectors";
3577   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
3578   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
3579   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
3580   case ISD::CARRY_FALSE:         return "carry_false";
3581   case ISD::ADDC:        return "addc";
3582   case ISD::ADDE:        return "adde";
3583   case ISD::SUBC:        return "subc";
3584   case ISD::SUBE:        return "sube";
3585   case ISD::SHL_PARTS:   return "shl_parts";
3586   case ISD::SRA_PARTS:   return "sra_parts";
3587   case ISD::SRL_PARTS:   return "srl_parts";
3588   
3589   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
3590   case ISD::INSERT_SUBREG:      return "insert_subreg";
3591   
3592   // Conversion operators.
3593   case ISD::SIGN_EXTEND: return "sign_extend";
3594   case ISD::ZERO_EXTEND: return "zero_extend";
3595   case ISD::ANY_EXTEND:  return "any_extend";
3596   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
3597   case ISD::TRUNCATE:    return "truncate";
3598   case ISD::FP_ROUND:    return "fp_round";
3599   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
3600   case ISD::FP_EXTEND:   return "fp_extend";
3601
3602   case ISD::SINT_TO_FP:  return "sint_to_fp";
3603   case ISD::UINT_TO_FP:  return "uint_to_fp";
3604   case ISD::FP_TO_SINT:  return "fp_to_sint";
3605   case ISD::FP_TO_UINT:  return "fp_to_uint";
3606   case ISD::BIT_CONVERT: return "bit_convert";
3607
3608     // Control flow instructions
3609   case ISD::BR:      return "br";
3610   case ISD::BRIND:   return "brind";
3611   case ISD::BR_JT:   return "br_jt";
3612   case ISD::BRCOND:  return "brcond";
3613   case ISD::BR_CC:   return "br_cc";
3614   case ISD::RET:     return "ret";
3615   case ISD::CALLSEQ_START:  return "callseq_start";
3616   case ISD::CALLSEQ_END:    return "callseq_end";
3617
3618     // Other operators
3619   case ISD::LOAD:               return "load";
3620   case ISD::STORE:              return "store";
3621   case ISD::VAARG:              return "vaarg";
3622   case ISD::VACOPY:             return "vacopy";
3623   case ISD::VAEND:              return "vaend";
3624   case ISD::VASTART:            return "vastart";
3625   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
3626   case ISD::EXTRACT_ELEMENT:    return "extract_element";
3627   case ISD::BUILD_PAIR:         return "build_pair";
3628   case ISD::STACKSAVE:          return "stacksave";
3629   case ISD::STACKRESTORE:       return "stackrestore";
3630     
3631   // Block memory operations.
3632   case ISD::MEMSET:  return "memset";
3633   case ISD::MEMCPY:  return "memcpy";
3634   case ISD::MEMMOVE: return "memmove";
3635
3636   // Bit manipulation
3637   case ISD::BSWAP:   return "bswap";
3638   case ISD::CTPOP:   return "ctpop";
3639   case ISD::CTTZ:    return "cttz";
3640   case ISD::CTLZ:    return "ctlz";
3641
3642   // Debug info
3643   case ISD::LOCATION: return "location";
3644   case ISD::DEBUG_LOC: return "debug_loc";
3645
3646   // Trampolines
3647   case ISD::TRAMPOLINE: return "trampoline";
3648
3649   case ISD::CONDCODE:
3650     switch (cast<CondCodeSDNode>(this)->get()) {
3651     default: assert(0 && "Unknown setcc condition!");
3652     case ISD::SETOEQ:  return "setoeq";
3653     case ISD::SETOGT:  return "setogt";
3654     case ISD::SETOGE:  return "setoge";
3655     case ISD::SETOLT:  return "setolt";
3656     case ISD::SETOLE:  return "setole";
3657     case ISD::SETONE:  return "setone";
3658
3659     case ISD::SETO:    return "seto";
3660     case ISD::SETUO:   return "setuo";
3661     case ISD::SETUEQ:  return "setue";
3662     case ISD::SETUGT:  return "setugt";
3663     case ISD::SETUGE:  return "setuge";
3664     case ISD::SETULT:  return "setult";
3665     case ISD::SETULE:  return "setule";
3666     case ISD::SETUNE:  return "setune";
3667
3668     case ISD::SETEQ:   return "seteq";
3669     case ISD::SETGT:   return "setgt";
3670     case ISD::SETGE:   return "setge";
3671     case ISD::SETLT:   return "setlt";
3672     case ISD::SETLE:   return "setle";
3673     case ISD::SETNE:   return "setne";
3674     }
3675   }
3676 }
3677
3678 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
3679   switch (AM) {
3680   default:
3681     return "";
3682   case ISD::PRE_INC:
3683     return "<pre-inc>";
3684   case ISD::PRE_DEC:
3685     return "<pre-dec>";
3686   case ISD::POST_INC:
3687     return "<post-inc>";
3688   case ISD::POST_DEC:
3689     return "<post-dec>";
3690   }
3691 }
3692
3693 void SDNode::dump() const { dump(0); }
3694 void SDNode::dump(const SelectionDAG *G) const {
3695   cerr << (void*)this << ": ";
3696
3697   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
3698     if (i) cerr << ",";
3699     if (getValueType(i) == MVT::Other)
3700       cerr << "ch";
3701     else
3702       cerr << MVT::getValueTypeString(getValueType(i));
3703   }
3704   cerr << " = " << getOperationName(G);
3705
3706   cerr << " ";
3707   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
3708     if (i) cerr << ", ";
3709     cerr << (void*)getOperand(i).Val;
3710     if (unsigned RN = getOperand(i).ResNo)
3711       cerr << ":" << RN;
3712   }
3713
3714   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
3715     cerr << "<" << CSDN->getValue() << ">";
3716   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
3717     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
3718       cerr << "<" << CSDN->getValueAPF().convertToFloat() << ">";
3719     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
3720       cerr << "<" << CSDN->getValueAPF().convertToDouble() << ">";
3721     else {
3722       cerr << "<APFloat(";
3723       CSDN->getValueAPF().convertToAPInt().dump();
3724       cerr << ")>";
3725     }
3726   } else if (const GlobalAddressSDNode *GADN =
3727              dyn_cast<GlobalAddressSDNode>(this)) {
3728     int offset = GADN->getOffset();
3729     cerr << "<";
3730     WriteAsOperand(*cerr.stream(), GADN->getGlobal()) << ">";
3731     if (offset > 0)
3732       cerr << " + " << offset;
3733     else
3734       cerr << " " << offset;
3735   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
3736     cerr << "<" << FIDN->getIndex() << ">";
3737   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
3738     cerr << "<" << JTDN->getIndex() << ">";
3739   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
3740     int offset = CP->getOffset();
3741     if (CP->isMachineConstantPoolEntry())
3742       cerr << "<" << *CP->getMachineCPVal() << ">";
3743     else
3744       cerr << "<" << *CP->getConstVal() << ">";
3745     if (offset > 0)
3746       cerr << " + " << offset;
3747     else
3748       cerr << " " << offset;
3749   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
3750     cerr << "<";
3751     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
3752     if (LBB)
3753       cerr << LBB->getName() << " ";
3754     cerr << (const void*)BBDN->getBasicBlock() << ">";
3755   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
3756     if (G && R->getReg() && MRegisterInfo::isPhysicalRegister(R->getReg())) {
3757       cerr << " " <<G->getTarget().getRegisterInfo()->getName(R->getReg());
3758     } else {
3759       cerr << " #" << R->getReg();
3760     }
3761   } else if (const ExternalSymbolSDNode *ES =
3762              dyn_cast<ExternalSymbolSDNode>(this)) {
3763     cerr << "'" << ES->getSymbol() << "'";
3764   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
3765     if (M->getValue())
3766       cerr << "<" << M->getValue() << ":" << M->getOffset() << ">";
3767     else
3768       cerr << "<null:" << M->getOffset() << ">";
3769   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
3770     cerr << ":" << MVT::getValueTypeString(N->getVT());
3771   } else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
3772     bool doExt = true;
3773     switch (LD->getExtensionType()) {
3774     default: doExt = false; break;
3775     case ISD::EXTLOAD:
3776       cerr << " <anyext ";
3777       break;
3778     case ISD::SEXTLOAD:
3779       cerr << " <sext ";
3780       break;
3781     case ISD::ZEXTLOAD:
3782       cerr << " <zext ";
3783       break;
3784     }
3785     if (doExt)
3786       cerr << MVT::getValueTypeString(LD->getLoadedVT()) << ">";
3787
3788     const char *AM = getIndexedModeName(LD->getAddressingMode());
3789     if (*AM)
3790       cerr << " " << AM;
3791   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
3792     if (ST->isTruncatingStore())
3793       cerr << " <trunc "
3794            << MVT::getValueTypeString(ST->getStoredVT()) << ">";
3795
3796     const char *AM = getIndexedModeName(ST->getAddressingMode());
3797     if (*AM)
3798       cerr << " " << AM;
3799   }
3800 }
3801
3802 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
3803   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
3804     if (N->getOperand(i).Val->hasOneUse())
3805       DumpNodes(N->getOperand(i).Val, indent+2, G);
3806     else
3807       cerr << "\n" << std::string(indent+2, ' ')
3808            << (void*)N->getOperand(i).Val << ": <multiple use>";
3809
3810
3811   cerr << "\n" << std::string(indent, ' ');
3812   N->dump(G);
3813 }
3814
3815 void SelectionDAG::dump() const {
3816   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
3817   std::vector<const SDNode*> Nodes;
3818   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
3819        I != E; ++I)
3820     Nodes.push_back(I);
3821   
3822   std::sort(Nodes.begin(), Nodes.end());
3823
3824   for (unsigned i = 0, e = Nodes.size(); i != e; ++i) {
3825     if (!Nodes[i]->hasOneUse() && Nodes[i] != getRoot().Val)
3826       DumpNodes(Nodes[i], 2, this);
3827   }
3828
3829   if (getRoot().Val) DumpNodes(getRoot().Val, 2, this);
3830
3831   cerr << "\n\n";
3832 }
3833
3834 const Type *ConstantPoolSDNode::getType() const {
3835   if (isMachineConstantPoolEntry())
3836     return Val.MachineCPVal->getType();
3837   return Val.ConstVal->getType();
3838 }