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