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