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