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