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