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