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