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