OSDN Git Service

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