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