SelectionDAG.cpp revision 80220369b040dd9769e4c4b65d2d018210c3b240
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>
55using namespace llvm;
56
57/// makeVTList - Return an instance of the SDVTList struct initialized with the
58/// specified members.
59static SDVTList makeVTList(const EVT *VTs, unsigned NumVTs) {
60  SDVTList Res = {VTs, NumVTs};
61  return Res;
62}
63
64static 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
75SelectionDAG::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.
85bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
86  return getValueAPF().bitwiseIsEqual(V);
87}
88
89bool 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.
112bool 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.
153bool 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.
193bool 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).
214ISD::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.
226ISD::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).
243static 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.
263ISD::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.
287ISD::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///
317static 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.
323static 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///
329static 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///
339static 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
347static 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.
357static 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.
460static 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///
475static inline unsigned
476encodeMemSDNodeFlags(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.
493static bool doNotCSE(SDNode *N) {
494  if (N->getValueType(0) == MVT::Glue)
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::Glue)
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.
514void 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.
534void 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
564void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
565  SmallVector<SDNode*, 16> DeadNodes(1, N);
566  RemoveDeadNodes(DeadNodes, UpdateListener);
567}
568
569void 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
578void 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
588void 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.
611bool 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::Glue &&
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///
667void
668SelectionDAG::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.
698SDNode *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.
715SDNode *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.
734SDNode *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.
749static 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.
784static 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.
812static 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///
824unsigned 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...
833SelectionDAG::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
842void SelectionDAG::init(MachineFunction &mf) {
843  MF = &mf;
844  Context = &mf.getFunction()->getContext();
845}
846
847SelectionDAG::~SelectionDAG() {
848  allnodes_clear();
849  delete Ordering;
850  delete DbgInfo;
851}
852
853void SelectionDAG::allnodes_clear() {
854  assert(&*AllNodes.begin() == &EntryNode);
855  AllNodes.remove(AllNodes.begin());
856  while (!AllNodes.empty())
857    DeallocateNode(AllNodes.begin());
858}
859
860void 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
880SDValue 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
886SDValue 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
892SDValue 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///
906SDValue 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
913SDValue 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
921SDValue SelectionDAG::getConstant(const APInt &Val, EVT VT, bool isT) {
922  return getConstant(*ConstantInt::get(*Context, Val), VT, isT);
923}
924
925SDValue 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
957SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
958  return getConstant(Val, TLI.getPointerTy(), isTarget);
959}
960
961
962SDValue SelectionDAG::getConstantFP(const APFloat& V, EVT VT, bool isTarget) {
963  return getConstantFP(*ConstantFP::get(*getContext(), V), VT, isTarget);
964}
965
966SDValue 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
1000SDValue 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
1018SDValue 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
1060SDValue 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
1075SDValue 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
1095SDValue 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
1122SDValue 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
1148SDValue 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
1162SDValue 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
1176SDValue 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
1184SDValue 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
1195SDValue 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.
1211static 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
1222SDValue 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
1312SDValue 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
1336SDValue 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
1350SDValue 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
1366SDValue 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
1385SDValue 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.
1404SDValue 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.
1422SDValue 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.
1433SDValue 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.
1446SDValue 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
1460SDValue 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.
1564bool 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.
1576bool 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.
1588void 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  case ISD::ADDE: {
1961    // Output known-0 bits are known if clear or set in both the low clear bits
1962    // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
1963    // low 3 bits clear.
1964    APInt Mask2 = APInt::getLowBitsSet(BitWidth,
1965                                       BitWidth - Mask.countLeadingZeros());
1966    ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
1967    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1968    unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
1969
1970    ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
1971    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1972    KnownZeroOut = std::min(KnownZeroOut,
1973                            KnownZero2.countTrailingOnes());
1974
1975    if (Op.getOpcode() == ISD::ADD) {
1976      KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
1977      return;
1978    }
1979
1980    // With ADDE, a carry bit may be added in, so we can only use this
1981    // information if we know (at least) that the low two bits are clear.  We
1982    // then return to the caller that the low bit is unknown but that other bits
1983    // are known zero.
1984    if (KnownZeroOut >= 2) // ADDE
1985      KnownZero |= APInt::getBitsSet(BitWidth, 1, KnownZeroOut);
1986    return;
1987  }
1988  case ISD::SREM:
1989    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
1990      const APInt &RA = Rem->getAPIntValue().abs();
1991      if (RA.isPowerOf2()) {
1992        APInt LowBits = RA - 1;
1993        APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
1994        ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
1995
1996        // The low bits of the first operand are unchanged by the srem.
1997        KnownZero = KnownZero2 & LowBits;
1998        KnownOne = KnownOne2 & LowBits;
1999
2000        // If the first operand is non-negative or has all low bits zero, then
2001        // the upper bits are all zero.
2002        if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
2003          KnownZero |= ~LowBits;
2004
2005        // If the first operand is negative and not all low bits are zero, then
2006        // the upper bits are all one.
2007        if (KnownOne2[BitWidth-1] && ((KnownOne2 & LowBits) != 0))
2008          KnownOne |= ~LowBits;
2009
2010        KnownZero &= Mask;
2011        KnownOne &= Mask;
2012
2013        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2014      }
2015    }
2016    return;
2017  case ISD::UREM: {
2018    if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2019      const APInt &RA = Rem->getAPIntValue();
2020      if (RA.isPowerOf2()) {
2021        APInt LowBits = (RA - 1);
2022        APInt Mask2 = LowBits & Mask;
2023        KnownZero |= ~LowBits & Mask;
2024        ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
2025        assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
2026        break;
2027      }
2028    }
2029
2030    // Since the result is less than or equal to either operand, any leading
2031    // zero bits in either operand must also exist in the result.
2032    APInt AllOnes = APInt::getAllOnesValue(BitWidth);
2033    ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
2034                      Depth+1);
2035    ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
2036                      Depth+1);
2037
2038    uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
2039                                KnownZero2.countLeadingOnes());
2040    KnownOne.clearAllBits();
2041    KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
2042    return;
2043  }
2044  default:
2045    // Allow the target to implement this method for its nodes.
2046    if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
2047  case ISD::INTRINSIC_WO_CHAIN:
2048  case ISD::INTRINSIC_W_CHAIN:
2049  case ISD::INTRINSIC_VOID:
2050      TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this,
2051                                         Depth);
2052    }
2053    return;
2054  }
2055}
2056
2057/// ComputeNumSignBits - Return the number of times the sign bit of the
2058/// register is replicated into the other bits.  We know that at least 1 bit
2059/// is always equal to the sign bit (itself), but other cases can give us
2060/// information.  For example, immediately after an "SRA X, 2", we know that
2061/// the top 3 bits are all equal to each other, so we return 3.
2062unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
2063  EVT VT = Op.getValueType();
2064  assert(VT.isInteger() && "Invalid VT!");
2065  unsigned VTBits = VT.getScalarType().getSizeInBits();
2066  unsigned Tmp, Tmp2;
2067  unsigned FirstAnswer = 1;
2068
2069  if (Depth == 6)
2070    return 1;  // Limit search depth.
2071
2072  switch (Op.getOpcode()) {
2073  default: break;
2074  case ISD::AssertSext:
2075    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2076    return VTBits-Tmp+1;
2077  case ISD::AssertZext:
2078    Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
2079    return VTBits-Tmp;
2080
2081  case ISD::Constant: {
2082    const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
2083    // If negative, return # leading ones.
2084    if (Val.isNegative())
2085      return Val.countLeadingOnes();
2086
2087    // Return # leading zeros.
2088    return Val.countLeadingZeros();
2089  }
2090
2091  case ISD::SIGN_EXTEND:
2092    Tmp = VTBits-Op.getOperand(0).getValueType().getScalarType().getSizeInBits();
2093    return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
2094
2095  case ISD::SIGN_EXTEND_INREG:
2096    // Max of the input and what this extends.
2097    Tmp =
2098      cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarType().getSizeInBits();
2099    Tmp = VTBits-Tmp+1;
2100
2101    Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2102    return std::max(Tmp, Tmp2);
2103
2104  case ISD::SRA:
2105    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2106    // SRA X, C   -> adds C sign bits.
2107    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2108      Tmp += C->getZExtValue();
2109      if (Tmp > VTBits) Tmp = VTBits;
2110    }
2111    return Tmp;
2112  case ISD::SHL:
2113    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2114      // shl destroys sign bits.
2115      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2116      if (C->getZExtValue() >= VTBits ||      // Bad shift.
2117          C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
2118      return Tmp - C->getZExtValue();
2119    }
2120    break;
2121  case ISD::AND:
2122  case ISD::OR:
2123  case ISD::XOR:    // NOT is handled here.
2124    // Logical binary ops preserve the number of sign bits at the worst.
2125    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2126    if (Tmp != 1) {
2127      Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2128      FirstAnswer = std::min(Tmp, Tmp2);
2129      // We computed what we know about the sign bits as our first
2130      // answer. Now proceed to the generic code that uses
2131      // ComputeMaskedBits, and pick whichever answer is better.
2132    }
2133    break;
2134
2135  case ISD::SELECT:
2136    Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2137    if (Tmp == 1) return 1;  // Early out.
2138    Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
2139    return std::min(Tmp, Tmp2);
2140
2141  case ISD::SADDO:
2142  case ISD::UADDO:
2143  case ISD::SSUBO:
2144  case ISD::USUBO:
2145  case ISD::SMULO:
2146  case ISD::UMULO:
2147    if (Op.getResNo() != 1)
2148      break;
2149    // The boolean result conforms to getBooleanContents.  Fall through.
2150  case ISD::SETCC:
2151    // If setcc returns 0/-1, all bits are sign bits.
2152    if (TLI.getBooleanContents() ==
2153        TargetLowering::ZeroOrNegativeOneBooleanContent)
2154      return VTBits;
2155    break;
2156  case ISD::ROTL:
2157  case ISD::ROTR:
2158    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
2159      unsigned RotAmt = C->getZExtValue() & (VTBits-1);
2160
2161      // Handle rotate right by N like a rotate left by 32-N.
2162      if (Op.getOpcode() == ISD::ROTR)
2163        RotAmt = (VTBits-RotAmt) & (VTBits-1);
2164
2165      // If we aren't rotating out all of the known-in sign bits, return the
2166      // number that are left.  This handles rotl(sext(x), 1) for example.
2167      Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2168      if (Tmp > RotAmt+1) return Tmp-RotAmt;
2169    }
2170    break;
2171  case ISD::ADD:
2172    // Add can have at most one carry bit.  Thus we know that the output
2173    // is, at worst, one more bit than the inputs.
2174    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2175    if (Tmp == 1) return 1;  // Early out.
2176
2177    // Special case decrementing a value (ADD X, -1):
2178    if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
2179      if (CRHS->isAllOnesValue()) {
2180        APInt KnownZero, KnownOne;
2181        APInt Mask = APInt::getAllOnesValue(VTBits);
2182        ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
2183
2184        // If the input is known to be 0 or 1, the output is 0/-1, which is all
2185        // sign bits set.
2186        if ((KnownZero | APInt(VTBits, 1)) == Mask)
2187          return VTBits;
2188
2189        // If we are subtracting one from a positive number, there is no carry
2190        // out of the result.
2191        if (KnownZero.isNegative())
2192          return Tmp;
2193      }
2194
2195    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2196    if (Tmp2 == 1) return 1;
2197      return std::min(Tmp, Tmp2)-1;
2198    break;
2199
2200  case ISD::SUB:
2201    Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
2202    if (Tmp2 == 1) return 1;
2203
2204    // Handle NEG.
2205    if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
2206      if (CLHS->isNullValue()) {
2207        APInt KnownZero, KnownOne;
2208        APInt Mask = APInt::getAllOnesValue(VTBits);
2209        ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
2210        // If the input is known to be 0 or 1, the output is 0/-1, which is all
2211        // sign bits set.
2212        if ((KnownZero | APInt(VTBits, 1)) == Mask)
2213          return VTBits;
2214
2215        // If the input is known to be positive (the sign bit is known clear),
2216        // the output of the NEG has the same number of sign bits as the input.
2217        if (KnownZero.isNegative())
2218          return Tmp2;
2219
2220        // Otherwise, we treat this like a SUB.
2221      }
2222
2223    // Sub can have at most one carry bit.  Thus we know that the output
2224    // is, at worst, one more bit than the inputs.
2225    Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
2226    if (Tmp == 1) return 1;  // Early out.
2227      return std::min(Tmp, Tmp2)-1;
2228    break;
2229  case ISD::TRUNCATE:
2230    // FIXME: it's tricky to do anything useful for this, but it is an important
2231    // case for targets like X86.
2232    break;
2233  }
2234
2235  // Handle LOADX separately here. EXTLOAD case will fallthrough.
2236  if (Op.getOpcode() == ISD::LOAD) {
2237    LoadSDNode *LD = cast<LoadSDNode>(Op);
2238    unsigned ExtType = LD->getExtensionType();
2239    switch (ExtType) {
2240    default: break;
2241    case ISD::SEXTLOAD:    // '17' bits known
2242      Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2243      return VTBits-Tmp+1;
2244    case ISD::ZEXTLOAD:    // '16' bits known
2245      Tmp = LD->getMemoryVT().getScalarType().getSizeInBits();
2246      return VTBits-Tmp;
2247    }
2248  }
2249
2250  // Allow the target to implement this method for its nodes.
2251  if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
2252      Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
2253      Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
2254      Op.getOpcode() == ISD::INTRINSIC_VOID) {
2255    unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
2256    if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
2257  }
2258
2259  // Finally, if we can prove that the top bits of the result are 0's or 1's,
2260  // use this information.
2261  APInt KnownZero, KnownOne;
2262  APInt Mask = APInt::getAllOnesValue(VTBits);
2263  ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
2264
2265  if (KnownZero.isNegative()) {        // sign bit is 0
2266    Mask = KnownZero;
2267  } else if (KnownOne.isNegative()) {  // sign bit is 1;
2268    Mask = KnownOne;
2269  } else {
2270    // Nothing known.
2271    return FirstAnswer;
2272  }
2273
2274  // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
2275  // the number of identical bits in the top of the input value.
2276  Mask = ~Mask;
2277  Mask <<= Mask.getBitWidth()-VTBits;
2278  // Return # leading zeros.  We use 'min' here in case Val was zero before
2279  // shifting.  We don't want to return '64' as for an i32 "0".
2280  return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
2281}
2282
2283bool SelectionDAG::isKnownNeverNaN(SDValue Op) const {
2284  // If we're told that NaNs won't happen, assume they won't.
2285  if (NoNaNsFPMath)
2286    return true;
2287
2288  // If the value is a constant, we can obviously see if it is a NaN or not.
2289  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2290    return !C->getValueAPF().isNaN();
2291
2292  // TODO: Recognize more cases here.
2293
2294  return false;
2295}
2296
2297bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
2298  // If the value is a constant, we can obviously see if it is a zero or not.
2299  if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
2300    return !C->isZero();
2301
2302  // TODO: Recognize more cases here.
2303
2304  return false;
2305}
2306
2307bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
2308  // Check the obvious case.
2309  if (A == B) return true;
2310
2311  // For for negative and positive zero.
2312  if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
2313    if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
2314      if (CA->isZero() && CB->isZero()) return true;
2315
2316  // Otherwise they may not be equal.
2317  return false;
2318}
2319
2320bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
2321  GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
2322  if (!GA) return false;
2323  if (GA->getOffset() != 0) return false;
2324  const GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
2325  if (!GV) return false;
2326  return MF->getMMI().hasDebugInfo();
2327}
2328
2329
2330/// getNode - Gets or creates the specified node.
2331///
2332SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT) {
2333  FoldingSetNodeID ID;
2334  AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
2335  void *IP = 0;
2336  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2337    return SDValue(E, 0);
2338
2339  SDNode *N = new (NodeAllocator) SDNode(Opcode, DL, getVTList(VT));
2340  CSEMap.InsertNode(N, IP);
2341
2342  AllNodes.push_back(N);
2343#ifndef NDEBUG
2344  VerifySDNode(N);
2345#endif
2346  return SDValue(N, 0);
2347}
2348
2349SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
2350                              EVT VT, SDValue Operand) {
2351  // Constant fold unary operations with an integer constant operand.
2352  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
2353    const APInt &Val = C->getAPIntValue();
2354    switch (Opcode) {
2355    default: break;
2356    case ISD::SIGN_EXTEND:
2357      return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), VT);
2358    case ISD::ANY_EXTEND:
2359    case ISD::ZERO_EXTEND:
2360    case ISD::TRUNCATE:
2361      return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), VT);
2362    case ISD::UINT_TO_FP:
2363    case ISD::SINT_TO_FP: {
2364      // No compile time operations on ppcf128.
2365      if (VT == MVT::ppcf128) break;
2366      APFloat apf(APInt::getNullValue(VT.getSizeInBits()));
2367      (void)apf.convertFromAPInt(Val,
2368                                 Opcode==ISD::SINT_TO_FP,
2369                                 APFloat::rmNearestTiesToEven);
2370      return getConstantFP(apf, VT);
2371    }
2372    case ISD::BITCAST:
2373      if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
2374        return getConstantFP(Val.bitsToFloat(), VT);
2375      else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
2376        return getConstantFP(Val.bitsToDouble(), VT);
2377      break;
2378    case ISD::BSWAP:
2379      return getConstant(Val.byteSwap(), VT);
2380    case ISD::CTPOP:
2381      return getConstant(Val.countPopulation(), VT);
2382    case ISD::CTLZ:
2383      return getConstant(Val.countLeadingZeros(), VT);
2384    case ISD::CTTZ:
2385      return getConstant(Val.countTrailingZeros(), VT);
2386    }
2387  }
2388
2389  // Constant fold unary operations with a floating point constant operand.
2390  if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
2391    APFloat V = C->getValueAPF();    // make copy
2392    if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
2393      switch (Opcode) {
2394      case ISD::FNEG:
2395        V.changeSign();
2396        return getConstantFP(V, VT);
2397      case ISD::FABS:
2398        V.clearSign();
2399        return getConstantFP(V, VT);
2400      case ISD::FP_ROUND:
2401      case ISD::FP_EXTEND: {
2402        bool ignored;
2403        // This can return overflow, underflow, or inexact; we don't care.
2404        // FIXME need to be more flexible about rounding mode.
2405        (void)V.convert(*EVTToAPFloatSemantics(VT),
2406                        APFloat::rmNearestTiesToEven, &ignored);
2407        return getConstantFP(V, VT);
2408      }
2409      case ISD::FP_TO_SINT:
2410      case ISD::FP_TO_UINT: {
2411        integerPart x[2];
2412        bool ignored;
2413        assert(integerPartWidth >= 64);
2414        // FIXME need to be more flexible about rounding mode.
2415        APFloat::opStatus s = V.convertToInteger(x, VT.getSizeInBits(),
2416                              Opcode==ISD::FP_TO_SINT,
2417                              APFloat::rmTowardZero, &ignored);
2418        if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
2419          break;
2420        APInt api(VT.getSizeInBits(), 2, x);
2421        return getConstant(api, VT);
2422      }
2423      case ISD::BITCAST:
2424        if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
2425          return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
2426        else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
2427          return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
2428        break;
2429      }
2430    }
2431  }
2432
2433  unsigned OpOpcode = Operand.getNode()->getOpcode();
2434  switch (Opcode) {
2435  case ISD::TokenFactor:
2436  case ISD::MERGE_VALUES:
2437  case ISD::CONCAT_VECTORS:
2438    return Operand;         // Factor, merge or concat of one node?  No need.
2439  case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
2440  case ISD::FP_EXTEND:
2441    assert(VT.isFloatingPoint() &&
2442           Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
2443    if (Operand.getValueType() == VT) return Operand;  // noop conversion.
2444    assert((!VT.isVector() ||
2445            VT.getVectorNumElements() ==
2446            Operand.getValueType().getVectorNumElements()) &&
2447           "Vector element count mismatch!");
2448    if (Operand.getOpcode() == ISD::UNDEF)
2449      return getUNDEF(VT);
2450    break;
2451  case ISD::SIGN_EXTEND:
2452    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2453           "Invalid SIGN_EXTEND!");
2454    if (Operand.getValueType() == VT) return Operand;   // noop extension
2455    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2456           "Invalid sext node, dst < src!");
2457    assert((!VT.isVector() ||
2458            VT.getVectorNumElements() ==
2459            Operand.getValueType().getVectorNumElements()) &&
2460           "Vector element count mismatch!");
2461    if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
2462      return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2463    break;
2464  case ISD::ZERO_EXTEND:
2465    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2466           "Invalid ZERO_EXTEND!");
2467    if (Operand.getValueType() == VT) return Operand;   // noop extension
2468    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2469           "Invalid zext node, dst < src!");
2470    assert((!VT.isVector() ||
2471            VT.getVectorNumElements() ==
2472            Operand.getValueType().getVectorNumElements()) &&
2473           "Vector element count mismatch!");
2474    if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
2475      return getNode(ISD::ZERO_EXTEND, DL, VT,
2476                     Operand.getNode()->getOperand(0));
2477    break;
2478  case ISD::ANY_EXTEND:
2479    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2480           "Invalid ANY_EXTEND!");
2481    if (Operand.getValueType() == VT) return Operand;   // noop extension
2482    assert(Operand.getValueType().getScalarType().bitsLT(VT.getScalarType()) &&
2483           "Invalid anyext node, dst < src!");
2484    assert((!VT.isVector() ||
2485            VT.getVectorNumElements() ==
2486            Operand.getValueType().getVectorNumElements()) &&
2487           "Vector element count mismatch!");
2488
2489    if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2490        OpOpcode == ISD::ANY_EXTEND)
2491      // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
2492      return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2493
2494    // (ext (trunx x)) -> x
2495    if (OpOpcode == ISD::TRUNCATE) {
2496      SDValue OpOp = Operand.getNode()->getOperand(0);
2497      if (OpOp.getValueType() == VT)
2498        return OpOp;
2499    }
2500    break;
2501  case ISD::TRUNCATE:
2502    assert(VT.isInteger() && Operand.getValueType().isInteger() &&
2503           "Invalid TRUNCATE!");
2504    if (Operand.getValueType() == VT) return Operand;   // noop truncate
2505    assert(Operand.getValueType().getScalarType().bitsGT(VT.getScalarType()) &&
2506           "Invalid truncate node, src < dst!");
2507    assert((!VT.isVector() ||
2508            VT.getVectorNumElements() ==
2509            Operand.getValueType().getVectorNumElements()) &&
2510           "Vector element count mismatch!");
2511    if (OpOpcode == ISD::TRUNCATE)
2512      return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2513    else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
2514             OpOpcode == ISD::ANY_EXTEND) {
2515      // If the source is smaller than the dest, we still need an extend.
2516      if (Operand.getNode()->getOperand(0).getValueType().getScalarType()
2517            .bitsLT(VT.getScalarType()))
2518        return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
2519      else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
2520        return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
2521      else
2522        return Operand.getNode()->getOperand(0);
2523    }
2524    break;
2525  case ISD::BITCAST:
2526    // Basic sanity checking.
2527    assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
2528           && "Cannot BITCAST between types of different sizes!");
2529    if (VT == Operand.getValueType()) return Operand;  // noop conversion.
2530    if (OpOpcode == ISD::BITCAST)  // bitconv(bitconv(x)) -> bitconv(x)
2531      return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
2532    if (OpOpcode == ISD::UNDEF)
2533      return getUNDEF(VT);
2534    break;
2535  case ISD::SCALAR_TO_VECTOR:
2536    assert(VT.isVector() && !Operand.getValueType().isVector() &&
2537           (VT.getVectorElementType() == Operand.getValueType() ||
2538            (VT.getVectorElementType().isInteger() &&
2539             Operand.getValueType().isInteger() &&
2540             VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
2541           "Illegal SCALAR_TO_VECTOR node!");
2542    if (OpOpcode == ISD::UNDEF)
2543      return getUNDEF(VT);
2544    // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
2545    if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
2546        isa<ConstantSDNode>(Operand.getOperand(1)) &&
2547        Operand.getConstantOperandVal(1) == 0 &&
2548        Operand.getOperand(0).getValueType() == VT)
2549      return Operand.getOperand(0);
2550    break;
2551  case ISD::FNEG:
2552    // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
2553    if (UnsafeFPMath && OpOpcode == ISD::FSUB)
2554      return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
2555                     Operand.getNode()->getOperand(0));
2556    if (OpOpcode == ISD::FNEG)  // --X -> X
2557      return Operand.getNode()->getOperand(0);
2558    break;
2559  case ISD::FABS:
2560    if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
2561      return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
2562    break;
2563  }
2564
2565  SDNode *N;
2566  SDVTList VTs = getVTList(VT);
2567  if (VT != MVT::Glue) { // Don't CSE flag producing nodes
2568    FoldingSetNodeID ID;
2569    SDValue Ops[1] = { Operand };
2570    AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
2571    void *IP = 0;
2572    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
2573      return SDValue(E, 0);
2574
2575    N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2576    CSEMap.InsertNode(N, IP);
2577  } else {
2578    N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTs, Operand);
2579  }
2580
2581  AllNodes.push_back(N);
2582#ifndef NDEBUG
2583  VerifySDNode(N);
2584#endif
2585  return SDValue(N, 0);
2586}
2587
2588SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
2589                                             EVT VT,
2590                                             ConstantSDNode *Cst1,
2591                                             ConstantSDNode *Cst2) {
2592  const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
2593
2594  switch (Opcode) {
2595  case ISD::ADD:  return getConstant(C1 + C2, VT);
2596  case ISD::SUB:  return getConstant(C1 - C2, VT);
2597  case ISD::MUL:  return getConstant(C1 * C2, VT);
2598  case ISD::UDIV:
2599    if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
2600    break;
2601  case ISD::UREM:
2602    if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
2603    break;
2604  case ISD::SDIV:
2605    if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
2606    break;
2607  case ISD::SREM:
2608    if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
2609    break;
2610  case ISD::AND:  return getConstant(C1 & C2, VT);
2611  case ISD::OR:   return getConstant(C1 | C2, VT);
2612  case ISD::XOR:  return getConstant(C1 ^ C2, VT);
2613  case ISD::SHL:  return getConstant(C1 << C2, VT);
2614  case ISD::SRL:  return getConstant(C1.lshr(C2), VT);
2615  case ISD::SRA:  return getConstant(C1.ashr(C2), VT);
2616  case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
2617  case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
2618  default: break;
2619  }
2620
2621  return SDValue();
2622}
2623
2624SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
2625                              SDValue N1, SDValue N2) {
2626  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
2627  ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
2628  switch (Opcode) {
2629  default: break;
2630  case ISD::TokenFactor:
2631    assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
2632           N2.getValueType() == MVT::Other && "Invalid token factor!");
2633    // Fold trivial token factors.
2634    if (N1.getOpcode() == ISD::EntryToken) return N2;
2635    if (N2.getOpcode() == ISD::EntryToken) return N1;
2636    if (N1 == N2) return N1;
2637    break;
2638  case ISD::CONCAT_VECTORS:
2639    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
2640    // one big BUILD_VECTOR.
2641    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
2642        N2.getOpcode() == ISD::BUILD_VECTOR) {
2643      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
2644                                    N1.getNode()->op_end());
2645      Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
2646      return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
2647    }
2648    break;
2649  case ISD::AND:
2650    assert(VT.isInteger() && "This operator does not apply to FP types!");
2651    assert(N1.getValueType() == N2.getValueType() &&
2652           N1.getValueType() == VT && "Binary operator types must match!");
2653    // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
2654    // worth handling here.
2655    if (N2C && N2C->isNullValue())
2656      return N2;
2657    if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
2658      return N1;
2659    break;
2660  case ISD::OR:
2661  case ISD::XOR:
2662  case ISD::ADD:
2663  case ISD::SUB:
2664    assert(VT.isInteger() && "This operator does not apply to FP types!");
2665    assert(N1.getValueType() == N2.getValueType() &&
2666           N1.getValueType() == VT && "Binary operator types must match!");
2667    // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
2668    // it's worth handling here.
2669    if (N2C && N2C->isNullValue())
2670      return N1;
2671    break;
2672  case ISD::UDIV:
2673  case ISD::UREM:
2674  case ISD::MULHU:
2675  case ISD::MULHS:
2676  case ISD::MUL:
2677  case ISD::SDIV:
2678  case ISD::SREM:
2679    assert(VT.isInteger() && "This operator does not apply to FP types!");
2680    assert(N1.getValueType() == N2.getValueType() &&
2681           N1.getValueType() == VT && "Binary operator types must match!");
2682    break;
2683  case ISD::FADD:
2684  case ISD::FSUB:
2685  case ISD::FMUL:
2686  case ISD::FDIV:
2687  case ISD::FREM:
2688    if (UnsafeFPMath) {
2689      if (Opcode == ISD::FADD) {
2690        // 0+x --> x
2691        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
2692          if (CFP->getValueAPF().isZero())
2693            return N2;
2694        // x+0 --> x
2695        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2696          if (CFP->getValueAPF().isZero())
2697            return N1;
2698      } else if (Opcode == ISD::FSUB) {
2699        // x-0 --> x
2700        if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
2701          if (CFP->getValueAPF().isZero())
2702            return N1;
2703      }
2704    }
2705    assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
2706    assert(N1.getValueType() == N2.getValueType() &&
2707           N1.getValueType() == VT && "Binary operator types must match!");
2708    break;
2709  case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
2710    assert(N1.getValueType() == VT &&
2711           N1.getValueType().isFloatingPoint() &&
2712           N2.getValueType().isFloatingPoint() &&
2713           "Invalid FCOPYSIGN!");
2714    break;
2715  case ISD::SHL:
2716  case ISD::SRA:
2717  case ISD::SRL:
2718  case ISD::ROTL:
2719  case ISD::ROTR:
2720    assert(VT == N1.getValueType() &&
2721           "Shift operators return type must be the same as their first arg");
2722    assert(VT.isInteger() && N2.getValueType().isInteger() &&
2723           "Shifts only work on integers");
2724
2725    // Always fold shifts of i1 values so the code generator doesn't need to
2726    // handle them.  Since we know the size of the shift has to be less than the
2727    // size of the value, the shift/rotate count is guaranteed to be zero.
2728    if (VT == MVT::i1)
2729      return N1;
2730    if (N2C && N2C->isNullValue())
2731      return N1;
2732    break;
2733  case ISD::FP_ROUND_INREG: {
2734    EVT EVT = cast<VTSDNode>(N2)->getVT();
2735    assert(VT == N1.getValueType() && "Not an inreg round!");
2736    assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
2737           "Cannot FP_ROUND_INREG integer types");
2738    assert(EVT.isVector() == VT.isVector() &&
2739           "FP_ROUND_INREG type should be vector iff the operand "
2740           "type is vector!");
2741    assert((!EVT.isVector() ||
2742            EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2743           "Vector element counts must match in FP_ROUND_INREG");
2744    assert(EVT.bitsLE(VT) && "Not rounding down!");
2745    if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
2746    break;
2747  }
2748  case ISD::FP_ROUND:
2749    assert(VT.isFloatingPoint() &&
2750           N1.getValueType().isFloatingPoint() &&
2751           VT.bitsLE(N1.getValueType()) &&
2752           isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
2753    if (N1.getValueType() == VT) return N1;  // noop conversion.
2754    break;
2755  case ISD::AssertSext:
2756  case ISD::AssertZext: {
2757    EVT EVT = cast<VTSDNode>(N2)->getVT();
2758    assert(VT == N1.getValueType() && "Not an inreg extend!");
2759    assert(VT.isInteger() && EVT.isInteger() &&
2760           "Cannot *_EXTEND_INREG FP types");
2761    assert(!EVT.isVector() &&
2762           "AssertSExt/AssertZExt type should be the vector element type "
2763           "rather than the vector type!");
2764    assert(EVT.bitsLE(VT) && "Not extending!");
2765    if (VT == EVT) return N1; // noop assertion.
2766    break;
2767  }
2768  case ISD::SIGN_EXTEND_INREG: {
2769    EVT EVT = cast<VTSDNode>(N2)->getVT();
2770    assert(VT == N1.getValueType() && "Not an inreg extend!");
2771    assert(VT.isInteger() && EVT.isInteger() &&
2772           "Cannot *_EXTEND_INREG FP types");
2773    assert(EVT.isVector() == VT.isVector() &&
2774           "SIGN_EXTEND_INREG type should be vector iff the operand "
2775           "type is vector!");
2776    assert((!EVT.isVector() ||
2777            EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
2778           "Vector element counts must match in SIGN_EXTEND_INREG");
2779    assert(EVT.bitsLE(VT) && "Not extending!");
2780    if (EVT == VT) return N1;  // Not actually extending
2781
2782    if (N1C) {
2783      APInt Val = N1C->getAPIntValue();
2784      unsigned FromBits = EVT.getScalarType().getSizeInBits();
2785      Val <<= Val.getBitWidth()-FromBits;
2786      Val = Val.ashr(Val.getBitWidth()-FromBits);
2787      return getConstant(Val, VT);
2788    }
2789    break;
2790  }
2791  case ISD::EXTRACT_VECTOR_ELT:
2792    // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
2793    if (N1.getOpcode() == ISD::UNDEF)
2794      return getUNDEF(VT);
2795
2796    // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
2797    // expanding copies of large vectors from registers.
2798    if (N2C &&
2799        N1.getOpcode() == ISD::CONCAT_VECTORS &&
2800        N1.getNumOperands() > 0) {
2801      unsigned Factor =
2802        N1.getOperand(0).getValueType().getVectorNumElements();
2803      return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
2804                     N1.getOperand(N2C->getZExtValue() / Factor),
2805                     getConstant(N2C->getZExtValue() % Factor,
2806                                 N2.getValueType()));
2807    }
2808
2809    // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
2810    // expanding large vector constants.
2811    if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
2812      SDValue Elt = N1.getOperand(N2C->getZExtValue());
2813      EVT VEltTy = N1.getValueType().getVectorElementType();
2814      if (Elt.getValueType() != VEltTy) {
2815        // If the vector element type is not legal, the BUILD_VECTOR operands
2816        // are promoted and implicitly truncated.  Make that explicit here.
2817        Elt = getNode(ISD::TRUNCATE, DL, VEltTy, Elt);
2818      }
2819      if (VT != VEltTy) {
2820        // If the vector element type is not legal, the EXTRACT_VECTOR_ELT
2821        // result is implicitly extended.
2822        Elt = getNode(ISD::ANY_EXTEND, DL, VT, Elt);
2823      }
2824      return Elt;
2825    }
2826
2827    // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
2828    // operations are lowered to scalars.
2829    if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
2830      // If the indices are the same, return the inserted element else
2831      // if the indices are known different, extract the element from
2832      // the original vector.
2833      SDValue N1Op2 = N1.getOperand(2);
2834      ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2.getNode());
2835
2836      if (N1Op2C && N2C) {
2837        if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
2838          if (VT == N1.getOperand(1).getValueType())
2839            return N1.getOperand(1);
2840          else
2841            return getSExtOrTrunc(N1.getOperand(1), DL, VT);
2842        }
2843
2844        return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
2845      }
2846    }
2847    break;
2848  case ISD::EXTRACT_ELEMENT:
2849    assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
2850    assert(!N1.getValueType().isVector() && !VT.isVector() &&
2851           (N1.getValueType().isInteger() == VT.isInteger()) &&
2852           "Wrong types for EXTRACT_ELEMENT!");
2853
2854    // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
2855    // 64-bit integers into 32-bit parts.  Instead of building the extract of
2856    // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
2857    if (N1.getOpcode() == ISD::BUILD_PAIR)
2858      return N1.getOperand(N2C->getZExtValue());
2859
2860    // EXTRACT_ELEMENT of a constant int is also very common.
2861    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2862      unsigned ElementSize = VT.getSizeInBits();
2863      unsigned Shift = ElementSize * N2C->getZExtValue();
2864      APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
2865      return getConstant(ShiftedVal.trunc(ElementSize), VT);
2866    }
2867    break;
2868  case ISD::EXTRACT_SUBVECTOR:
2869    if (N1.getValueType() == VT) // Trivial extraction.
2870      return N1;
2871    break;
2872  }
2873
2874  if (N1C) {
2875    if (N2C) {
2876      SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
2877      if (SV.getNode()) return SV;
2878    } else {      // Cannonicalize constant to RHS if commutative
2879      if (isCommutativeBinOp(Opcode)) {
2880        std::swap(N1C, N2C);
2881        std::swap(N1, N2);
2882      }
2883    }
2884  }
2885
2886  // Constant fold FP operations.
2887  ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
2888  ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
2889  if (N1CFP) {
2890    if (!N2CFP && isCommutativeBinOp(Opcode)) {
2891      // Cannonicalize constant to RHS if commutative
2892      std::swap(N1CFP, N2CFP);
2893      std::swap(N1, N2);
2894    } else if (N2CFP && VT != MVT::ppcf128) {
2895      APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
2896      APFloat::opStatus s;
2897      switch (Opcode) {
2898      case ISD::FADD:
2899        s = V1.add(V2, APFloat::rmNearestTiesToEven);
2900        if (s != APFloat::opInvalidOp)
2901          return getConstantFP(V1, VT);
2902        break;
2903      case ISD::FSUB:
2904        s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
2905        if (s!=APFloat::opInvalidOp)
2906          return getConstantFP(V1, VT);
2907        break;
2908      case ISD::FMUL:
2909        s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
2910        if (s!=APFloat::opInvalidOp)
2911          return getConstantFP(V1, VT);
2912        break;
2913      case ISD::FDIV:
2914        s = V1.divide(V2, APFloat::rmNearestTiesToEven);
2915        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2916          return getConstantFP(V1, VT);
2917        break;
2918      case ISD::FREM :
2919        s = V1.mod(V2, APFloat::rmNearestTiesToEven);
2920        if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
2921          return getConstantFP(V1, VT);
2922        break;
2923      case ISD::FCOPYSIGN:
2924        V1.copySign(V2);
2925        return getConstantFP(V1, VT);
2926      default: break;
2927      }
2928    }
2929  }
2930
2931  // Canonicalize an UNDEF to the RHS, even over a constant.
2932  if (N1.getOpcode() == ISD::UNDEF) {
2933    if (isCommutativeBinOp(Opcode)) {
2934      std::swap(N1, N2);
2935    } else {
2936      switch (Opcode) {
2937      case ISD::FP_ROUND_INREG:
2938      case ISD::SIGN_EXTEND_INREG:
2939      case ISD::SUB:
2940      case ISD::FSUB:
2941      case ISD::FDIV:
2942      case ISD::FREM:
2943      case ISD::SRA:
2944        return N1;     // fold op(undef, arg2) -> undef
2945      case ISD::UDIV:
2946      case ISD::SDIV:
2947      case ISD::UREM:
2948      case ISD::SREM:
2949      case ISD::SRL:
2950      case ISD::SHL:
2951        if (!VT.isVector())
2952          return getConstant(0, VT);    // fold op(undef, arg2) -> 0
2953        // For vectors, we can't easily build an all zero vector, just return
2954        // the LHS.
2955        return N2;
2956      }
2957    }
2958  }
2959
2960  // Fold a bunch of operators when the RHS is undef.
2961  if (N2.getOpcode() == ISD::UNDEF) {
2962    switch (Opcode) {
2963    case ISD::XOR:
2964      if (N1.getOpcode() == ISD::UNDEF)
2965        // Handle undef ^ undef -> 0 special case. This is a common
2966        // idiom (misuse).
2967        return getConstant(0, VT);
2968      // fallthrough
2969    case ISD::ADD:
2970    case ISD::ADDC:
2971    case ISD::ADDE:
2972    case ISD::SUB:
2973    case ISD::UDIV:
2974    case ISD::SDIV:
2975    case ISD::UREM:
2976    case ISD::SREM:
2977      return N2;       // fold op(arg1, undef) -> undef
2978    case ISD::FADD:
2979    case ISD::FSUB:
2980    case ISD::FMUL:
2981    case ISD::FDIV:
2982    case ISD::FREM:
2983      if (UnsafeFPMath)
2984        return N2;
2985      break;
2986    case ISD::MUL:
2987    case ISD::AND:
2988    case ISD::SRL:
2989    case ISD::SHL:
2990      if (!VT.isVector())
2991        return getConstant(0, VT);  // fold op(arg1, undef) -> 0
2992      // For vectors, we can't easily build an all zero vector, just return
2993      // the LHS.
2994      return N1;
2995    case ISD::OR:
2996      if (!VT.isVector())
2997        return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
2998      // For vectors, we can't easily build an all one vector, just return
2999      // the LHS.
3000      return N1;
3001    case ISD::SRA:
3002      return N1;
3003    }
3004  }
3005
3006  // Memoize this node if possible.
3007  SDNode *N;
3008  SDVTList VTs = getVTList(VT);
3009  if (VT != MVT::Glue) {
3010    SDValue Ops[] = { N1, N2 };
3011    FoldingSetNodeID ID;
3012    AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
3013    void *IP = 0;
3014    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3015      return SDValue(E, 0);
3016
3017    N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3018    CSEMap.InsertNode(N, IP);
3019  } else {
3020    N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTs, N1, N2);
3021  }
3022
3023  AllNodes.push_back(N);
3024#ifndef NDEBUG
3025  VerifySDNode(N);
3026#endif
3027  return SDValue(N, 0);
3028}
3029
3030SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3031                              SDValue N1, SDValue N2, SDValue N3) {
3032  // Perform various simplifications.
3033  ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
3034  switch (Opcode) {
3035  case ISD::CONCAT_VECTORS:
3036    // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
3037    // one big BUILD_VECTOR.
3038    if (N1.getOpcode() == ISD::BUILD_VECTOR &&
3039        N2.getOpcode() == ISD::BUILD_VECTOR &&
3040        N3.getOpcode() == ISD::BUILD_VECTOR) {
3041      SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(),
3042                                    N1.getNode()->op_end());
3043      Elts.append(N2.getNode()->op_begin(), N2.getNode()->op_end());
3044      Elts.append(N3.getNode()->op_begin(), N3.getNode()->op_end());
3045      return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
3046    }
3047    break;
3048  case ISD::SETCC: {
3049    // Use FoldSetCC to simplify SETCC's.
3050    SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
3051    if (Simp.getNode()) return Simp;
3052    break;
3053  }
3054  case ISD::SELECT:
3055    if (N1C) {
3056     if (N1C->getZExtValue())
3057        return N2;             // select true, X, Y -> X
3058      else
3059        return N3;             // select false, X, Y -> Y
3060    }
3061
3062    if (N2 == N3) return N2;   // select C, X, X -> X
3063    break;
3064  case ISD::VECTOR_SHUFFLE:
3065    llvm_unreachable("should use getVectorShuffle constructor!");
3066    break;
3067  case ISD::BITCAST:
3068    // Fold bit_convert nodes from a type to themselves.
3069    if (N1.getValueType() == VT)
3070      return N1;
3071    break;
3072  }
3073
3074  // Memoize node if it doesn't produce a flag.
3075  SDNode *N;
3076  SDVTList VTs = getVTList(VT);
3077  if (VT != MVT::Glue) {
3078    SDValue Ops[] = { N1, N2, N3 };
3079    FoldingSetNodeID ID;
3080    AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3081    void *IP = 0;
3082    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
3083      return SDValue(E, 0);
3084
3085    N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3086    CSEMap.InsertNode(N, IP);
3087  } else {
3088    N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
3089  }
3090
3091  AllNodes.push_back(N);
3092#ifndef NDEBUG
3093  VerifySDNode(N);
3094#endif
3095  return SDValue(N, 0);
3096}
3097
3098SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3099                              SDValue N1, SDValue N2, SDValue N3,
3100                              SDValue N4) {
3101  SDValue Ops[] = { N1, N2, N3, N4 };
3102  return getNode(Opcode, DL, VT, Ops, 4);
3103}
3104
3105SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
3106                              SDValue N1, SDValue N2, SDValue N3,
3107                              SDValue N4, SDValue N5) {
3108  SDValue Ops[] = { N1, N2, N3, N4, N5 };
3109  return getNode(Opcode, DL, VT, Ops, 5);
3110}
3111
3112/// getStackArgumentTokenFactor - Compute a TokenFactor to force all
3113/// the incoming stack arguments to be loaded from the stack.
3114SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
3115  SmallVector<SDValue, 8> ArgChains;
3116
3117  // Include the original chain at the beginning of the list. When this is
3118  // used by target LowerCall hooks, this helps legalize find the
3119  // CALLSEQ_BEGIN node.
3120  ArgChains.push_back(Chain);
3121
3122  // Add a chain value for each stack argument.
3123  for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
3124       UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
3125    if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
3126      if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
3127        if (FI->getIndex() < 0)
3128          ArgChains.push_back(SDValue(L, 1));
3129
3130  // Build a tokenfactor for all the chains.
3131  return getNode(ISD::TokenFactor, Chain.getDebugLoc(), MVT::Other,
3132                 &ArgChains[0], ArgChains.size());
3133}
3134
3135/// SplatByte - Distribute ByteVal over NumBits bits.
3136static APInt SplatByte(unsigned NumBits, uint8_t ByteVal) {
3137  APInt Val = APInt(NumBits, ByteVal);
3138  unsigned Shift = 8;
3139  for (unsigned i = NumBits; i > 8; i >>= 1) {
3140    Val = (Val << Shift) | Val;
3141    Shift <<= 1;
3142  }
3143  return Val;
3144}
3145
3146/// getMemsetValue - Vectorized representation of the memset value
3147/// operand.
3148static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
3149                              DebugLoc dl) {
3150  assert(Value.getOpcode() != ISD::UNDEF);
3151
3152  unsigned NumBits = VT.getScalarType().getSizeInBits();
3153  if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
3154    APInt Val = SplatByte(NumBits, C->getZExtValue() & 255);
3155    if (VT.isInteger())
3156      return DAG.getConstant(Val, VT);
3157    return DAG.getConstantFP(APFloat(Val), VT);
3158  }
3159
3160  Value = DAG.getNode(ISD::ZERO_EXTEND, dl, VT, Value);
3161  if (NumBits > 8) {
3162    // Use a multiplication with 0x010101... to extend the input to the
3163    // required length.
3164    APInt Magic = SplatByte(NumBits, 0x01);
3165    Value = DAG.getNode(ISD::MUL, dl, VT, Value, DAG.getConstant(Magic, VT));
3166  }
3167
3168  return Value;
3169}
3170
3171/// getMemsetStringVal - Similar to getMemsetValue. Except this is only
3172/// used when a memcpy is turned into a memset when the source is a constant
3173/// string ptr.
3174static SDValue getMemsetStringVal(EVT VT, DebugLoc dl, SelectionDAG &DAG,
3175                                  const TargetLowering &TLI,
3176                                  std::string &Str, unsigned Offset) {
3177  // Handle vector with all elements zero.
3178  if (Str.empty()) {
3179    if (VT.isInteger())
3180      return DAG.getConstant(0, VT);
3181    else if (VT == MVT::f32 || VT == MVT::f64)
3182      return DAG.getConstantFP(0.0, VT);
3183    else if (VT.isVector()) {
3184      unsigned NumElts = VT.getVectorNumElements();
3185      MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
3186      return DAG.getNode(ISD::BITCAST, dl, VT,
3187                         DAG.getConstant(0, EVT::getVectorVT(*DAG.getContext(),
3188                                                             EltVT, NumElts)));
3189    } else
3190      llvm_unreachable("Expected type!");
3191  }
3192
3193  assert(!VT.isVector() && "Can't handle vector type here!");
3194  unsigned NumBits = VT.getSizeInBits();
3195  unsigned MSB = NumBits / 8;
3196  uint64_t Val = 0;
3197  if (TLI.isLittleEndian())
3198    Offset = Offset + MSB - 1;
3199  for (unsigned i = 0; i != MSB; ++i) {
3200    Val = (Val << 8) | (unsigned char)Str[Offset];
3201    Offset += TLI.isLittleEndian() ? -1 : 1;
3202  }
3203  return DAG.getConstant(Val, VT);
3204}
3205
3206/// getMemBasePlusOffset - Returns base and offset node for the
3207///
3208static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
3209                                      SelectionDAG &DAG) {
3210  EVT VT = Base.getValueType();
3211  return DAG.getNode(ISD::ADD, Base.getDebugLoc(),
3212                     VT, Base, DAG.getConstant(Offset, VT));
3213}
3214
3215/// isMemSrcFromString - Returns true if memcpy source is a string constant.
3216///
3217static bool isMemSrcFromString(SDValue Src, std::string &Str) {
3218  unsigned SrcDelta = 0;
3219  GlobalAddressSDNode *G = NULL;
3220  if (Src.getOpcode() == ISD::GlobalAddress)
3221    G = cast<GlobalAddressSDNode>(Src);
3222  else if (Src.getOpcode() == ISD::ADD &&
3223           Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
3224           Src.getOperand(1).getOpcode() == ISD::Constant) {
3225    G = cast<GlobalAddressSDNode>(Src.getOperand(0));
3226    SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
3227  }
3228  if (!G)
3229    return false;
3230
3231  const GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
3232  if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
3233    return true;
3234
3235  return false;
3236}
3237
3238/// FindOptimalMemOpLowering - Determines the optimial series memory ops
3239/// to replace the memset / memcpy. Return true if the number of memory ops
3240/// is below the threshold. It returns the types of the sequence of
3241/// memory ops to perform memset / memcpy by reference.
3242static bool FindOptimalMemOpLowering(std::vector<EVT> &MemOps,
3243                                     unsigned Limit, uint64_t Size,
3244                                     unsigned DstAlign, unsigned SrcAlign,
3245                                     bool NonScalarIntSafe,
3246                                     bool MemcpyStrSrc,
3247                                     SelectionDAG &DAG,
3248                                     const TargetLowering &TLI) {
3249  assert((SrcAlign == 0 || SrcAlign >= DstAlign) &&
3250         "Expecting memcpy / memset source to meet alignment requirement!");
3251  // If 'SrcAlign' is zero, that means the memory operation does not need load
3252  // the value, i.e. memset or memcpy from constant string. Otherwise, it's
3253  // the inferred alignment of the source. 'DstAlign', on the other hand, is the
3254  // specified alignment of the memory operation. If it is zero, that means
3255  // it's possible to change the alignment of the destination. 'MemcpyStrSrc'
3256  // indicates whether the memcpy source is constant so it does not need to be
3257  // loaded.
3258  EVT VT = TLI.getOptimalMemOpType(Size, DstAlign, SrcAlign,
3259                                   NonScalarIntSafe, MemcpyStrSrc,
3260                                   DAG.getMachineFunction());
3261
3262  if (VT == MVT::Other) {
3263    if (DstAlign >= TLI.getTargetData()->getPointerPrefAlignment() ||
3264        TLI.allowsUnalignedMemoryAccesses(VT)) {
3265      VT = TLI.getPointerTy();
3266    } else {
3267      switch (DstAlign & 7) {
3268      case 0:  VT = MVT::i64; break;
3269      case 4:  VT = MVT::i32; break;
3270      case 2:  VT = MVT::i16; break;
3271      default: VT = MVT::i8;  break;
3272      }
3273    }
3274
3275    MVT LVT = MVT::i64;
3276    while (!TLI.isTypeLegal(LVT))
3277      LVT = (MVT::SimpleValueType)(LVT.SimpleTy - 1);
3278    assert(LVT.isInteger());
3279
3280    if (VT.bitsGT(LVT))
3281      VT = LVT;
3282  }
3283
3284  // If we're optimizing for size, and there is a limit, bump the maximum number
3285  // of operations inserted down to 4.  This is a wild guess that approximates
3286  // the size of a call to memcpy or memset (3 arguments + call).
3287  if (Limit != ~0U) {
3288    const Function *F = DAG.getMachineFunction().getFunction();
3289    if (F->hasFnAttr(Attribute::OptimizeForSize))
3290      Limit = 4;
3291  }
3292
3293  unsigned NumMemOps = 0;
3294  while (Size != 0) {
3295    unsigned VTSize = VT.getSizeInBits() / 8;
3296    while (VTSize > Size) {
3297      // For now, only use non-vector load / store's for the left-over pieces.
3298      if (VT.isVector() || VT.isFloatingPoint()) {
3299        VT = MVT::i64;
3300        while (!TLI.isTypeLegal(VT))
3301          VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3302        VTSize = VT.getSizeInBits() / 8;
3303      } else {
3304        // This can result in a type that is not legal on the target, e.g.
3305        // 1 or 2 bytes on PPC.
3306        VT = (MVT::SimpleValueType)(VT.getSimpleVT().SimpleTy - 1);
3307        VTSize >>= 1;
3308      }
3309    }
3310
3311    if (++NumMemOps > Limit)
3312      return false;
3313    MemOps.push_back(VT);
3314    Size -= VTSize;
3315  }
3316
3317  return true;
3318}
3319
3320static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3321                                       SDValue Chain, SDValue Dst,
3322                                       SDValue Src, uint64_t Size,
3323                                       unsigned Align, bool isVol,
3324                                       bool AlwaysInline,
3325                                       MachinePointerInfo DstPtrInfo,
3326                                       MachinePointerInfo SrcPtrInfo) {
3327  // Turn a memcpy of undef to nop.
3328  if (Src.getOpcode() == ISD::UNDEF)
3329    return Chain;
3330
3331  // Expand memcpy to a series of load and store ops if the size operand falls
3332  // below a certain threshold.
3333  // TODO: In the AlwaysInline case, if the size is big then generate a loop
3334  // rather than maybe a humongous number of loads and stores.
3335  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3336  std::vector<EVT> MemOps;
3337  bool DstAlignCanChange = false;
3338  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3339  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3340  if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3341    DstAlignCanChange = true;
3342  unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3343  if (Align > SrcAlign)
3344    SrcAlign = Align;
3345  std::string Str;
3346  bool CopyFromStr = isMemSrcFromString(Src, Str);
3347  bool isZeroStr = CopyFromStr && Str.empty();
3348  unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy();
3349
3350  if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3351                                (DstAlignCanChange ? 0 : Align),
3352                                (isZeroStr ? 0 : SrcAlign),
3353                                true, CopyFromStr, DAG, TLI))
3354    return SDValue();
3355
3356  if (DstAlignCanChange) {
3357    const Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3358    unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3359    if (NewAlign > Align) {
3360      // Give the stack frame object a larger alignment if needed.
3361      if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3362        MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3363      Align = NewAlign;
3364    }
3365  }
3366
3367  SmallVector<SDValue, 8> OutChains;
3368  unsigned NumMemOps = MemOps.size();
3369  uint64_t SrcOff = 0, DstOff = 0;
3370  for (unsigned i = 0; i != NumMemOps; ++i) {
3371    EVT VT = MemOps[i];
3372    unsigned VTSize = VT.getSizeInBits() / 8;
3373    SDValue Value, Store;
3374
3375    if (CopyFromStr &&
3376        (isZeroStr || (VT.isInteger() && !VT.isVector()))) {
3377      // It's unlikely a store of a vector immediate can be done in a single
3378      // instruction. It would require a load from a constantpool first.
3379      // We only handle zero vectors here.
3380      // FIXME: Handle other cases where store of vector immediate is done in
3381      // a single instruction.
3382      Value = getMemsetStringVal(VT, dl, DAG, TLI, Str, SrcOff);
3383      Store = DAG.getStore(Chain, dl, Value,
3384                           getMemBasePlusOffset(Dst, DstOff, DAG),
3385                           DstPtrInfo.getWithOffset(DstOff), isVol,
3386                           false, Align);
3387    } else {
3388      // The type might not be legal for the target.  This should only happen
3389      // if the type is smaller than a legal type, as on PPC, so the right
3390      // thing to do is generate a LoadExt/StoreTrunc pair.  These simplify
3391      // to Load/Store if NVT==VT.
3392      // FIXME does the case above also need this?
3393      EVT NVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
3394      assert(NVT.bitsGE(VT));
3395      Value = DAG.getExtLoad(ISD::EXTLOAD, NVT, dl, Chain,
3396                             getMemBasePlusOffset(Src, SrcOff, DAG),
3397                             SrcPtrInfo.getWithOffset(SrcOff), VT, isVol, false,
3398                             MinAlign(SrcAlign, SrcOff));
3399      Store = DAG.getTruncStore(Chain, dl, Value,
3400                                getMemBasePlusOffset(Dst, DstOff, DAG),
3401                                DstPtrInfo.getWithOffset(DstOff), VT, isVol,
3402                                false, Align);
3403    }
3404    OutChains.push_back(Store);
3405    SrcOff += VTSize;
3406    DstOff += VTSize;
3407  }
3408
3409  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3410                     &OutChains[0], OutChains.size());
3411}
3412
3413static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, DebugLoc dl,
3414                                        SDValue Chain, SDValue Dst,
3415                                        SDValue Src, uint64_t Size,
3416                                        unsigned Align,  bool isVol,
3417                                        bool AlwaysInline,
3418                                        MachinePointerInfo DstPtrInfo,
3419                                        MachinePointerInfo SrcPtrInfo) {
3420  // Turn a memmove of undef to nop.
3421  if (Src.getOpcode() == ISD::UNDEF)
3422    return Chain;
3423
3424  // Expand memmove to a series of load and store ops if the size operand falls
3425  // below a certain threshold.
3426  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3427  std::vector<EVT> MemOps;
3428  bool DstAlignCanChange = false;
3429  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3430  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3431  if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3432    DstAlignCanChange = true;
3433  unsigned SrcAlign = DAG.InferPtrAlignment(Src);
3434  if (Align > SrcAlign)
3435    SrcAlign = Align;
3436  unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove();
3437
3438  if (!FindOptimalMemOpLowering(MemOps, Limit, Size,
3439                                (DstAlignCanChange ? 0 : Align),
3440                                SrcAlign, true, false, DAG, TLI))
3441    return SDValue();
3442
3443  if (DstAlignCanChange) {
3444    const Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3445    unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3446    if (NewAlign > Align) {
3447      // Give the stack frame object a larger alignment if needed.
3448      if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3449        MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3450      Align = NewAlign;
3451    }
3452  }
3453
3454  uint64_t SrcOff = 0, DstOff = 0;
3455  SmallVector<SDValue, 8> LoadValues;
3456  SmallVector<SDValue, 8> LoadChains;
3457  SmallVector<SDValue, 8> OutChains;
3458  unsigned NumMemOps = MemOps.size();
3459  for (unsigned i = 0; i < NumMemOps; i++) {
3460    EVT VT = MemOps[i];
3461    unsigned VTSize = VT.getSizeInBits() / 8;
3462    SDValue Value, Store;
3463
3464    Value = DAG.getLoad(VT, dl, Chain,
3465                        getMemBasePlusOffset(Src, SrcOff, DAG),
3466                        SrcPtrInfo.getWithOffset(SrcOff), isVol,
3467                        false, SrcAlign);
3468    LoadValues.push_back(Value);
3469    LoadChains.push_back(Value.getValue(1));
3470    SrcOff += VTSize;
3471  }
3472  Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3473                      &LoadChains[0], LoadChains.size());
3474  OutChains.clear();
3475  for (unsigned i = 0; i < NumMemOps; i++) {
3476    EVT VT = MemOps[i];
3477    unsigned VTSize = VT.getSizeInBits() / 8;
3478    SDValue Value, Store;
3479
3480    Store = DAG.getStore(Chain, dl, LoadValues[i],
3481                         getMemBasePlusOffset(Dst, DstOff, DAG),
3482                         DstPtrInfo.getWithOffset(DstOff), isVol, false, Align);
3483    OutChains.push_back(Store);
3484    DstOff += VTSize;
3485  }
3486
3487  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3488                     &OutChains[0], OutChains.size());
3489}
3490
3491static SDValue getMemsetStores(SelectionDAG &DAG, DebugLoc dl,
3492                               SDValue Chain, SDValue Dst,
3493                               SDValue Src, uint64_t Size,
3494                               unsigned Align, bool isVol,
3495                               MachinePointerInfo DstPtrInfo) {
3496  // Turn a memset of undef to nop.
3497  if (Src.getOpcode() == ISD::UNDEF)
3498    return Chain;
3499
3500  // Expand memset to a series of load/store ops if the size operand
3501  // falls below a certain threshold.
3502  const TargetLowering &TLI = DAG.getTargetLoweringInfo();
3503  std::vector<EVT> MemOps;
3504  bool DstAlignCanChange = false;
3505  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3506  FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
3507  if (FI && !MFI->isFixedObjectIndex(FI->getIndex()))
3508    DstAlignCanChange = true;
3509  bool NonScalarIntSafe =
3510    isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
3511  if (!FindOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(),
3512                                Size, (DstAlignCanChange ? 0 : Align), 0,
3513                                NonScalarIntSafe, false, DAG, TLI))
3514    return SDValue();
3515
3516  if (DstAlignCanChange) {
3517    const Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
3518    unsigned NewAlign = (unsigned) TLI.getTargetData()->getABITypeAlignment(Ty);
3519    if (NewAlign > Align) {
3520      // Give the stack frame object a larger alignment if needed.
3521      if (MFI->getObjectAlignment(FI->getIndex()) < NewAlign)
3522        MFI->setObjectAlignment(FI->getIndex(), NewAlign);
3523      Align = NewAlign;
3524    }
3525  }
3526
3527  SmallVector<SDValue, 8> OutChains;
3528  uint64_t DstOff = 0;
3529  unsigned NumMemOps = MemOps.size();
3530
3531  // Find the largest store and generate the bit pattern for it.
3532  EVT LargestVT = MemOps[0];
3533  for (unsigned i = 1; i < NumMemOps; i++)
3534    if (MemOps[i].bitsGT(LargestVT))
3535      LargestVT = MemOps[i];
3536  SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
3537
3538  for (unsigned i = 0; i < NumMemOps; i++) {
3539    EVT VT = MemOps[i];
3540
3541    // If this store is smaller than the largest store see whether we can get
3542    // the smaller value for free with a truncate.
3543    SDValue Value = MemSetValue;
3544    if (VT.bitsLT(LargestVT)) {
3545      if (!LargestVT.isVector() && !VT.isVector() &&
3546          TLI.isTruncateFree(LargestVT, VT))
3547        Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
3548      else
3549        Value = getMemsetValue(Src, VT, DAG, dl);
3550    }
3551    assert(Value.getValueType() == VT && "Value with wrong type.");
3552    SDValue Store = DAG.getStore(Chain, dl, Value,
3553                                 getMemBasePlusOffset(Dst, DstOff, DAG),
3554                                 DstPtrInfo.getWithOffset(DstOff),
3555                                 isVol, false, Align);
3556    OutChains.push_back(Store);
3557    DstOff += VT.getSizeInBits() / 8;
3558  }
3559
3560  return DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3561                     &OutChains[0], OutChains.size());
3562}
3563
3564SDValue SelectionDAG::getMemcpy(SDValue Chain, DebugLoc dl, SDValue Dst,
3565                                SDValue Src, SDValue Size,
3566                                unsigned Align, bool isVol, bool AlwaysInline,
3567                                MachinePointerInfo DstPtrInfo,
3568                                MachinePointerInfo SrcPtrInfo) {
3569
3570  // Check to see if we should lower the memcpy to loads and stores first.
3571  // For cases within the target-specified limits, this is the best choice.
3572  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3573  if (ConstantSize) {
3574    // Memcpy with size zero? Just return the original chain.
3575    if (ConstantSize->isNullValue())
3576      return Chain;
3577
3578    SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3579                                             ConstantSize->getZExtValue(),Align,
3580                                isVol, false, DstPtrInfo, SrcPtrInfo);
3581    if (Result.getNode())
3582      return Result;
3583  }
3584
3585  // Then check to see if we should lower the memcpy with target-specific
3586  // code. If the target chooses to do this, this is the next best.
3587  SDValue Result =
3588    TSI.EmitTargetCodeForMemcpy(*this, dl, Chain, Dst, Src, Size, Align,
3589                                isVol, AlwaysInline,
3590                                DstPtrInfo, SrcPtrInfo);
3591  if (Result.getNode())
3592    return Result;
3593
3594  // If we really need inline code and the target declined to provide it,
3595  // use a (potentially long) sequence of loads and stores.
3596  if (AlwaysInline) {
3597    assert(ConstantSize && "AlwaysInline requires a constant size!");
3598    return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
3599                                   ConstantSize->getZExtValue(), Align, isVol,
3600                                   true, DstPtrInfo, SrcPtrInfo);
3601  }
3602
3603  // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
3604  // memcpy is not guaranteed to be safe. libc memcpys aren't required to
3605  // respect volatile, so they may do things like read or write memory
3606  // beyond the given memory regions. But fixing this isn't easy, and most
3607  // people don't care.
3608
3609  // Emit a library call.
3610  TargetLowering::ArgListTy Args;
3611  TargetLowering::ArgListEntry Entry;
3612  Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3613  Entry.Node = Dst; Args.push_back(Entry);
3614  Entry.Node = Src; Args.push_back(Entry);
3615  Entry.Node = Size; Args.push_back(Entry);
3616  // FIXME: pass in DebugLoc
3617  std::pair<SDValue,SDValue> CallResult =
3618    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3619                    false, false, false, false, 0,
3620                    TLI.getLibcallCallingConv(RTLIB::MEMCPY), false,
3621                    /*isReturnValueUsed=*/false,
3622                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMCPY),
3623                                      TLI.getPointerTy()),
3624                    Args, *this, dl);
3625  return CallResult.second;
3626}
3627
3628SDValue SelectionDAG::getMemmove(SDValue Chain, DebugLoc dl, SDValue Dst,
3629                                 SDValue Src, SDValue Size,
3630                                 unsigned Align, bool isVol,
3631                                 MachinePointerInfo DstPtrInfo,
3632                                 MachinePointerInfo SrcPtrInfo) {
3633
3634  // Check to see if we should lower the memmove to loads and stores first.
3635  // For cases within the target-specified limits, this is the best choice.
3636  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3637  if (ConstantSize) {
3638    // Memmove with size zero? Just return the original chain.
3639    if (ConstantSize->isNullValue())
3640      return Chain;
3641
3642    SDValue Result =
3643      getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
3644                               ConstantSize->getZExtValue(), Align, isVol,
3645                               false, DstPtrInfo, SrcPtrInfo);
3646    if (Result.getNode())
3647      return Result;
3648  }
3649
3650  // Then check to see if we should lower the memmove with target-specific
3651  // code. If the target chooses to do this, this is the next best.
3652  SDValue Result =
3653    TSI.EmitTargetCodeForMemmove(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3654                                 DstPtrInfo, SrcPtrInfo);
3655  if (Result.getNode())
3656    return Result;
3657
3658  // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
3659  // not be safe.  See memcpy above for more details.
3660
3661  // Emit a library call.
3662  TargetLowering::ArgListTy Args;
3663  TargetLowering::ArgListEntry Entry;
3664  Entry.Ty = TLI.getTargetData()->getIntPtrType(*getContext());
3665  Entry.Node = Dst; Args.push_back(Entry);
3666  Entry.Node = Src; Args.push_back(Entry);
3667  Entry.Node = Size; Args.push_back(Entry);
3668  // FIXME:  pass in DebugLoc
3669  std::pair<SDValue,SDValue> CallResult =
3670    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3671                    false, false, false, false, 0,
3672                    TLI.getLibcallCallingConv(RTLIB::MEMMOVE), false,
3673                    /*isReturnValueUsed=*/false,
3674                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMMOVE),
3675                                      TLI.getPointerTy()),
3676                    Args, *this, dl);
3677  return CallResult.second;
3678}
3679
3680SDValue SelectionDAG::getMemset(SDValue Chain, DebugLoc dl, SDValue Dst,
3681                                SDValue Src, SDValue Size,
3682                                unsigned Align, bool isVol,
3683                                MachinePointerInfo DstPtrInfo) {
3684
3685  // Check to see if we should lower the memset to stores first.
3686  // For cases within the target-specified limits, this is the best choice.
3687  ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
3688  if (ConstantSize) {
3689    // Memset with size zero? Just return the original chain.
3690    if (ConstantSize->isNullValue())
3691      return Chain;
3692
3693    SDValue Result =
3694      getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
3695                      Align, isVol, DstPtrInfo);
3696
3697    if (Result.getNode())
3698      return Result;
3699  }
3700
3701  // Then check to see if we should lower the memset with target-specific
3702  // code. If the target chooses to do this, this is the next best.
3703  SDValue Result =
3704    TSI.EmitTargetCodeForMemset(*this, dl, Chain, Dst, Src, Size, Align, isVol,
3705                                DstPtrInfo);
3706  if (Result.getNode())
3707    return Result;
3708
3709  // Emit a library call.
3710  const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType(*getContext());
3711  TargetLowering::ArgListTy Args;
3712  TargetLowering::ArgListEntry Entry;
3713  Entry.Node = Dst; Entry.Ty = IntPtrTy;
3714  Args.push_back(Entry);
3715  // Extend or truncate the argument to be an i32 value for the call.
3716  if (Src.getValueType().bitsGT(MVT::i32))
3717    Src = getNode(ISD::TRUNCATE, dl, MVT::i32, Src);
3718  else
3719    Src = getNode(ISD::ZERO_EXTEND, dl, MVT::i32, Src);
3720  Entry.Node = Src;
3721  Entry.Ty = Type::getInt32Ty(*getContext());
3722  Entry.isSExt = true;
3723  Args.push_back(Entry);
3724  Entry.Node = Size;
3725  Entry.Ty = IntPtrTy;
3726  Entry.isSExt = false;
3727  Args.push_back(Entry);
3728  // FIXME: pass in DebugLoc
3729  std::pair<SDValue,SDValue> CallResult =
3730    TLI.LowerCallTo(Chain, Type::getVoidTy(*getContext()),
3731                    false, false, false, false, 0,
3732                    TLI.getLibcallCallingConv(RTLIB::MEMSET), false,
3733                    /*isReturnValueUsed=*/false,
3734                    getExternalSymbol(TLI.getLibcallName(RTLIB::MEMSET),
3735                                      TLI.getPointerTy()),
3736                    Args, *this, dl);
3737  return CallResult.second;
3738}
3739
3740SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3741                                SDValue Chain, SDValue Ptr, SDValue Cmp,
3742                                SDValue Swp, MachinePointerInfo PtrInfo,
3743                                unsigned Alignment) {
3744  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3745    Alignment = getEVTAlignment(MemVT);
3746
3747  MachineFunction &MF = getMachineFunction();
3748  unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3749
3750  // For now, atomics are considered to be volatile always.
3751  Flags |= MachineMemOperand::MOVolatile;
3752
3753  MachineMemOperand *MMO =
3754    MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment);
3755
3756  return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Cmp, Swp, MMO);
3757}
3758
3759SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3760                                SDValue Chain,
3761                                SDValue Ptr, SDValue Cmp,
3762                                SDValue Swp, MachineMemOperand *MMO) {
3763  assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
3764  assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
3765
3766  EVT VT = Cmp.getValueType();
3767
3768  SDVTList VTs = getVTList(VT, MVT::Other);
3769  FoldingSetNodeID ID;
3770  ID.AddInteger(MemVT.getRawBits());
3771  SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
3772  AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
3773  void* IP = 0;
3774  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3775    cast<AtomicSDNode>(E)->refineAlignment(MMO);
3776    return SDValue(E, 0);
3777  }
3778  SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3779                                               Ptr, Cmp, Swp, MMO);
3780  CSEMap.InsertNode(N, IP);
3781  AllNodes.push_back(N);
3782  return SDValue(N, 0);
3783}
3784
3785SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3786                                SDValue Chain,
3787                                SDValue Ptr, SDValue Val,
3788                                const Value* PtrVal,
3789                                unsigned Alignment) {
3790  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3791    Alignment = getEVTAlignment(MemVT);
3792
3793  MachineFunction &MF = getMachineFunction();
3794  unsigned Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
3795
3796  // For now, atomics are considered to be volatile always.
3797  Flags |= MachineMemOperand::MOVolatile;
3798
3799  MachineMemOperand *MMO =
3800    MF.getMachineMemOperand(MachinePointerInfo(PtrVal), Flags,
3801                            MemVT.getStoreSize(), Alignment);
3802
3803  return getAtomic(Opcode, dl, MemVT, Chain, Ptr, Val, MMO);
3804}
3805
3806SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, EVT MemVT,
3807                                SDValue Chain,
3808                                SDValue Ptr, SDValue Val,
3809                                MachineMemOperand *MMO) {
3810  assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
3811          Opcode == ISD::ATOMIC_LOAD_SUB ||
3812          Opcode == ISD::ATOMIC_LOAD_AND ||
3813          Opcode == ISD::ATOMIC_LOAD_OR ||
3814          Opcode == ISD::ATOMIC_LOAD_XOR ||
3815          Opcode == ISD::ATOMIC_LOAD_NAND ||
3816          Opcode == ISD::ATOMIC_LOAD_MIN ||
3817          Opcode == ISD::ATOMIC_LOAD_MAX ||
3818          Opcode == ISD::ATOMIC_LOAD_UMIN ||
3819          Opcode == ISD::ATOMIC_LOAD_UMAX ||
3820          Opcode == ISD::ATOMIC_SWAP) &&
3821         "Invalid Atomic Op");
3822
3823  EVT VT = Val.getValueType();
3824
3825  SDVTList VTs = getVTList(VT, MVT::Other);
3826  FoldingSetNodeID ID;
3827  ID.AddInteger(MemVT.getRawBits());
3828  SDValue Ops[] = {Chain, Ptr, Val};
3829  AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
3830  void* IP = 0;
3831  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3832    cast<AtomicSDNode>(E)->refineAlignment(MMO);
3833    return SDValue(E, 0);
3834  }
3835  SDNode *N = new (NodeAllocator) AtomicSDNode(Opcode, dl, VTs, MemVT, Chain,
3836                                               Ptr, Val, MMO);
3837  CSEMap.InsertNode(N, IP);
3838  AllNodes.push_back(N);
3839  return SDValue(N, 0);
3840}
3841
3842/// getMergeValues - Create a MERGE_VALUES node from the given operands.
3843/// Allowed to return something different (and simpler) if Simplify is true.
3844SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
3845                                     DebugLoc dl) {
3846  if (NumOps == 1)
3847    return Ops[0];
3848
3849  SmallVector<EVT, 4> VTs;
3850  VTs.reserve(NumOps);
3851  for (unsigned i = 0; i < NumOps; ++i)
3852    VTs.push_back(Ops[i].getValueType());
3853  return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps),
3854                 Ops, NumOps);
3855}
3856
3857SDValue
3858SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
3859                                  const EVT *VTs, unsigned NumVTs,
3860                                  const SDValue *Ops, unsigned NumOps,
3861                                  EVT MemVT, MachinePointerInfo PtrInfo,
3862                                  unsigned Align, bool Vol,
3863                                  bool ReadMem, bool WriteMem) {
3864  return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
3865                             MemVT, PtrInfo, Align, Vol,
3866                             ReadMem, WriteMem);
3867}
3868
3869SDValue
3870SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3871                                  const SDValue *Ops, unsigned NumOps,
3872                                  EVT MemVT, MachinePointerInfo PtrInfo,
3873                                  unsigned Align, bool Vol,
3874                                  bool ReadMem, bool WriteMem) {
3875  if (Align == 0)  // Ensure that codegen never sees alignment 0
3876    Align = getEVTAlignment(MemVT);
3877
3878  MachineFunction &MF = getMachineFunction();
3879  unsigned Flags = 0;
3880  if (WriteMem)
3881    Flags |= MachineMemOperand::MOStore;
3882  if (ReadMem)
3883    Flags |= MachineMemOperand::MOLoad;
3884  if (Vol)
3885    Flags |= MachineMemOperand::MOVolatile;
3886  MachineMemOperand *MMO =
3887    MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Align);
3888
3889  return getMemIntrinsicNode(Opcode, dl, VTList, Ops, NumOps, MemVT, MMO);
3890}
3891
3892SDValue
3893SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
3894                                  const SDValue *Ops, unsigned NumOps,
3895                                  EVT MemVT, MachineMemOperand *MMO) {
3896  assert((Opcode == ISD::INTRINSIC_VOID ||
3897          Opcode == ISD::INTRINSIC_W_CHAIN ||
3898          Opcode == ISD::PREFETCH ||
3899          (Opcode <= INT_MAX &&
3900           (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
3901         "Opcode is not a memory-accessing opcode!");
3902
3903  // Memoize the node unless it returns a flag.
3904  MemIntrinsicSDNode *N;
3905  if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
3906    FoldingSetNodeID ID;
3907    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
3908    void *IP = 0;
3909    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
3910      cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
3911      return SDValue(E, 0);
3912    }
3913
3914    N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
3915                                               MemVT, MMO);
3916    CSEMap.InsertNode(N, IP);
3917  } else {
3918    N = new (NodeAllocator) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps,
3919                                               MemVT, MMO);
3920  }
3921  AllNodes.push_back(N);
3922  return SDValue(N, 0);
3923}
3924
3925/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
3926/// MachinePointerInfo record from it.  This is particularly useful because the
3927/// code generator has many cases where it doesn't bother passing in a
3928/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
3929static MachinePointerInfo InferPointerInfo(SDValue Ptr, int64_t Offset = 0) {
3930  // If this is FI+Offset, we can model it.
3931  if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
3932    return MachinePointerInfo::getFixedStack(FI->getIndex(), Offset);
3933
3934  // If this is (FI+Offset1)+Offset2, we can model it.
3935  if (Ptr.getOpcode() != ISD::ADD ||
3936      !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
3937      !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
3938    return MachinePointerInfo();
3939
3940  int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
3941  return MachinePointerInfo::getFixedStack(FI, Offset+
3942                       cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
3943}
3944
3945/// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
3946/// MachinePointerInfo record from it.  This is particularly useful because the
3947/// code generator has many cases where it doesn't bother passing in a
3948/// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
3949static MachinePointerInfo InferPointerInfo(SDValue Ptr, SDValue OffsetOp) {
3950  // If the 'Offset' value isn't a constant, we can't handle this.
3951  if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
3952    return InferPointerInfo(Ptr, OffsetNode->getSExtValue());
3953  if (OffsetOp.getOpcode() == ISD::UNDEF)
3954    return InferPointerInfo(Ptr);
3955  return MachinePointerInfo();
3956}
3957
3958
3959SDValue
3960SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3961                      EVT VT, DebugLoc dl, SDValue Chain,
3962                      SDValue Ptr, SDValue Offset,
3963                      MachinePointerInfo PtrInfo, EVT MemVT,
3964                      bool isVolatile, bool isNonTemporal,
3965                      unsigned Alignment, const MDNode *TBAAInfo) {
3966  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
3967    Alignment = getEVTAlignment(VT);
3968
3969  unsigned Flags = MachineMemOperand::MOLoad;
3970  if (isVolatile)
3971    Flags |= MachineMemOperand::MOVolatile;
3972  if (isNonTemporal)
3973    Flags |= MachineMemOperand::MONonTemporal;
3974
3975  // If we don't have a PtrInfo, infer the trivial frame index case to simplify
3976  // clients.
3977  if (PtrInfo.V == 0)
3978    PtrInfo = InferPointerInfo(Ptr, Offset);
3979
3980  MachineFunction &MF = getMachineFunction();
3981  MachineMemOperand *MMO =
3982    MF.getMachineMemOperand(PtrInfo, Flags, MemVT.getStoreSize(), Alignment,
3983                            TBAAInfo);
3984  return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
3985}
3986
3987SDValue
3988SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
3989                      EVT VT, DebugLoc dl, SDValue Chain,
3990                      SDValue Ptr, SDValue Offset, EVT MemVT,
3991                      MachineMemOperand *MMO) {
3992  if (VT == MemVT) {
3993    ExtType = ISD::NON_EXTLOAD;
3994  } else if (ExtType == ISD::NON_EXTLOAD) {
3995    assert(VT == MemVT && "Non-extending load from different memory type!");
3996  } else {
3997    // Extending load.
3998    assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
3999           "Should only be an extending load, not truncating!");
4000    assert(VT.isInteger() == MemVT.isInteger() &&
4001           "Cannot convert from FP to Int or Int -> FP!");
4002    assert(VT.isVector() == MemVT.isVector() &&
4003           "Cannot use trunc store to convert to or from a vector!");
4004    assert((!VT.isVector() ||
4005            VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
4006           "Cannot use trunc store to change the number of vector elements!");
4007  }
4008
4009  bool Indexed = AM != ISD::UNINDEXED;
4010  assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
4011         "Unindexed load with an offset!");
4012
4013  SDVTList VTs = Indexed ?
4014    getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
4015  SDValue Ops[] = { Chain, Ptr, Offset };
4016  FoldingSetNodeID ID;
4017  AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
4018  ID.AddInteger(MemVT.getRawBits());
4019  ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, MMO->isVolatile(),
4020                                     MMO->isNonTemporal()));
4021  void *IP = 0;
4022  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4023    cast<LoadSDNode>(E)->refineAlignment(MMO);
4024    return SDValue(E, 0);
4025  }
4026  SDNode *N = new (NodeAllocator) LoadSDNode(Ops, dl, VTs, AM, ExtType,
4027                                             MemVT, MMO);
4028  CSEMap.InsertNode(N, IP);
4029  AllNodes.push_back(N);
4030  return SDValue(N, 0);
4031}
4032
4033SDValue SelectionDAG::getLoad(EVT VT, DebugLoc dl,
4034                              SDValue Chain, SDValue Ptr,
4035                              MachinePointerInfo PtrInfo,
4036                              bool isVolatile, bool isNonTemporal,
4037                              unsigned Alignment, const MDNode *TBAAInfo) {
4038  SDValue Undef = getUNDEF(Ptr.getValueType());
4039  return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
4040                 PtrInfo, VT, isVolatile, isNonTemporal, Alignment, TBAAInfo);
4041}
4042
4043SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, EVT VT, DebugLoc dl,
4044                                 SDValue Chain, SDValue Ptr,
4045                                 MachinePointerInfo PtrInfo, EVT MemVT,
4046                                 bool isVolatile, bool isNonTemporal,
4047                                 unsigned Alignment, const MDNode *TBAAInfo) {
4048  SDValue Undef = getUNDEF(Ptr.getValueType());
4049  return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
4050                 PtrInfo, MemVT, isVolatile, isNonTemporal, Alignment,
4051                 TBAAInfo);
4052}
4053
4054
4055SDValue
4056SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
4057                             SDValue Offset, ISD::MemIndexedMode AM) {
4058  LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
4059  assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
4060         "Load is already a indexed load!");
4061  return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
4062                 LD->getChain(), Base, Offset, LD->getPointerInfo(),
4063                 LD->getMemoryVT(),
4064                 LD->isVolatile(), LD->isNonTemporal(), LD->getAlignment());
4065}
4066
4067SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4068                               SDValue Ptr, MachinePointerInfo PtrInfo,
4069                               bool isVolatile, bool isNonTemporal,
4070                               unsigned Alignment, const MDNode *TBAAInfo) {
4071  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4072    Alignment = getEVTAlignment(Val.getValueType());
4073
4074  unsigned Flags = MachineMemOperand::MOStore;
4075  if (isVolatile)
4076    Flags |= MachineMemOperand::MOVolatile;
4077  if (isNonTemporal)
4078    Flags |= MachineMemOperand::MONonTemporal;
4079
4080  if (PtrInfo.V == 0)
4081    PtrInfo = InferPointerInfo(Ptr);
4082
4083  MachineFunction &MF = getMachineFunction();
4084  MachineMemOperand *MMO =
4085    MF.getMachineMemOperand(PtrInfo, Flags,
4086                            Val.getValueType().getStoreSize(), Alignment,
4087                            TBAAInfo);
4088
4089  return getStore(Chain, dl, Val, Ptr, MMO);
4090}
4091
4092SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
4093                               SDValue Ptr, MachineMemOperand *MMO) {
4094  EVT VT = Val.getValueType();
4095  SDVTList VTs = getVTList(MVT::Other);
4096  SDValue Undef = getUNDEF(Ptr.getValueType());
4097  SDValue Ops[] = { Chain, Val, Ptr, Undef };
4098  FoldingSetNodeID ID;
4099  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4100  ID.AddInteger(VT.getRawBits());
4101  ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED, MMO->isVolatile(),
4102                                     MMO->isNonTemporal()));
4103  void *IP = 0;
4104  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4105    cast<StoreSDNode>(E)->refineAlignment(MMO);
4106    return SDValue(E, 0);
4107  }
4108  SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4109                                              false, VT, MMO);
4110  CSEMap.InsertNode(N, IP);
4111  AllNodes.push_back(N);
4112  return SDValue(N, 0);
4113}
4114
4115SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4116                                    SDValue Ptr, MachinePointerInfo PtrInfo,
4117                                    EVT SVT,bool isVolatile, bool isNonTemporal,
4118                                    unsigned Alignment,
4119                                    const MDNode *TBAAInfo) {
4120  if (Alignment == 0)  // Ensure that codegen never sees alignment 0
4121    Alignment = getEVTAlignment(SVT);
4122
4123  unsigned Flags = MachineMemOperand::MOStore;
4124  if (isVolatile)
4125    Flags |= MachineMemOperand::MOVolatile;
4126  if (isNonTemporal)
4127    Flags |= MachineMemOperand::MONonTemporal;
4128
4129  if (PtrInfo.V == 0)
4130    PtrInfo = InferPointerInfo(Ptr);
4131
4132  MachineFunction &MF = getMachineFunction();
4133  MachineMemOperand *MMO =
4134    MF.getMachineMemOperand(PtrInfo, Flags, SVT.getStoreSize(), Alignment,
4135                            TBAAInfo);
4136
4137  return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
4138}
4139
4140SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
4141                                    SDValue Ptr, EVT SVT,
4142                                    MachineMemOperand *MMO) {
4143  EVT VT = Val.getValueType();
4144
4145  if (VT == SVT)
4146    return getStore(Chain, dl, Val, Ptr, MMO);
4147
4148  assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
4149         "Should only be a truncating store, not extending!");
4150  assert(VT.isInteger() == SVT.isInteger() &&
4151         "Can't do FP-INT conversion!");
4152  assert(VT.isVector() == SVT.isVector() &&
4153         "Cannot use trunc store to convert to or from a vector!");
4154  assert((!VT.isVector() ||
4155          VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
4156         "Cannot use trunc store to change the number of vector elements!");
4157
4158  SDVTList VTs = getVTList(MVT::Other);
4159  SDValue Undef = getUNDEF(Ptr.getValueType());
4160  SDValue Ops[] = { Chain, Val, Ptr, Undef };
4161  FoldingSetNodeID ID;
4162  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4163  ID.AddInteger(SVT.getRawBits());
4164  ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED, MMO->isVolatile(),
4165                                     MMO->isNonTemporal()));
4166  void *IP = 0;
4167  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
4168    cast<StoreSDNode>(E)->refineAlignment(MMO);
4169    return SDValue(E, 0);
4170  }
4171  SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED,
4172                                              true, SVT, MMO);
4173  CSEMap.InsertNode(N, IP);
4174  AllNodes.push_back(N);
4175  return SDValue(N, 0);
4176}
4177
4178SDValue
4179SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
4180                              SDValue Offset, ISD::MemIndexedMode AM) {
4181  StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
4182  assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
4183         "Store is already a indexed store!");
4184  SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
4185  SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
4186  FoldingSetNodeID ID;
4187  AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
4188  ID.AddInteger(ST->getMemoryVT().getRawBits());
4189  ID.AddInteger(ST->getRawSubclassData());
4190  void *IP = 0;
4191  if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4192    return SDValue(E, 0);
4193
4194  SDNode *N = new (NodeAllocator) StoreSDNode(Ops, dl, VTs, AM,
4195                                              ST->isTruncatingStore(),
4196                                              ST->getMemoryVT(),
4197                                              ST->getMemOperand());
4198  CSEMap.InsertNode(N, IP);
4199  AllNodes.push_back(N);
4200  return SDValue(N, 0);
4201}
4202
4203SDValue SelectionDAG::getVAArg(EVT VT, DebugLoc dl,
4204                               SDValue Chain, SDValue Ptr,
4205                               SDValue SV,
4206                               unsigned Align) {
4207  SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, MVT::i32) };
4208  return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops, 4);
4209}
4210
4211SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4212                              const SDUse *Ops, unsigned NumOps) {
4213  switch (NumOps) {
4214  case 0: return getNode(Opcode, DL, VT);
4215  case 1: return getNode(Opcode, DL, VT, Ops[0]);
4216  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4217  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4218  default: break;
4219  }
4220
4221  // Copy from an SDUse array into an SDValue array for use with
4222  // the regular getNode logic.
4223  SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
4224  return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
4225}
4226
4227SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, EVT VT,
4228                              const SDValue *Ops, unsigned NumOps) {
4229  switch (NumOps) {
4230  case 0: return getNode(Opcode, DL, VT);
4231  case 1: return getNode(Opcode, DL, VT, Ops[0]);
4232  case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
4233  case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
4234  default: break;
4235  }
4236
4237  switch (Opcode) {
4238  default: break;
4239  case ISD::SELECT_CC: {
4240    assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
4241    assert(Ops[0].getValueType() == Ops[1].getValueType() &&
4242           "LHS and RHS of condition must have same type!");
4243    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4244           "True and False arms of SelectCC must have same type!");
4245    assert(Ops[2].getValueType() == VT &&
4246           "select_cc node must be of same type as true and false value!");
4247    break;
4248  }
4249  case ISD::BR_CC: {
4250    assert(NumOps == 5 && "BR_CC takes 5 operands!");
4251    assert(Ops[2].getValueType() == Ops[3].getValueType() &&
4252           "LHS/RHS of comparison should match types!");
4253    break;
4254  }
4255  }
4256
4257  // Memoize nodes.
4258  SDNode *N;
4259  SDVTList VTs = getVTList(VT);
4260
4261  if (VT != MVT::Glue) {
4262    FoldingSetNodeID ID;
4263    AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
4264    void *IP = 0;
4265
4266    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4267      return SDValue(E, 0);
4268
4269    N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4270    CSEMap.InsertNode(N, IP);
4271  } else {
4272    N = new (NodeAllocator) SDNode(Opcode, DL, VTs, Ops, NumOps);
4273  }
4274
4275  AllNodes.push_back(N);
4276#ifndef NDEBUG
4277  VerifySDNode(N);
4278#endif
4279  return SDValue(N, 0);
4280}
4281
4282SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4283                              const std::vector<EVT> &ResultTys,
4284                              const SDValue *Ops, unsigned NumOps) {
4285  return getNode(Opcode, DL, getVTList(&ResultTys[0], ResultTys.size()),
4286                 Ops, NumOps);
4287}
4288
4289SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
4290                              const EVT *VTs, unsigned NumVTs,
4291                              const SDValue *Ops, unsigned NumOps) {
4292  if (NumVTs == 1)
4293    return getNode(Opcode, DL, VTs[0], Ops, NumOps);
4294  return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
4295}
4296
4297SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4298                              const SDValue *Ops, unsigned NumOps) {
4299  if (VTList.NumVTs == 1)
4300    return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
4301
4302#if 0
4303  switch (Opcode) {
4304  // FIXME: figure out how to safely handle things like
4305  // int foo(int x) { return 1 << (x & 255); }
4306  // int bar() { return foo(256); }
4307  case ISD::SRA_PARTS:
4308  case ISD::SRL_PARTS:
4309  case ISD::SHL_PARTS:
4310    if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
4311        cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
4312      return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4313    else if (N3.getOpcode() == ISD::AND)
4314      if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
4315        // If the and is only masking out bits that cannot effect the shift,
4316        // eliminate the and.
4317        unsigned NumBits = VT.getScalarType().getSizeInBits()*2;
4318        if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
4319          return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
4320      }
4321    break;
4322  }
4323#endif
4324
4325  // Memoize the node unless it returns a flag.
4326  SDNode *N;
4327  if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4328    FoldingSetNodeID ID;
4329    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
4330    void *IP = 0;
4331    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4332      return SDValue(E, 0);
4333
4334    if (NumOps == 1) {
4335      N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4336    } else if (NumOps == 2) {
4337      N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4338    } else if (NumOps == 3) {
4339      N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4340                                            Ops[2]);
4341    } else {
4342      N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4343    }
4344    CSEMap.InsertNode(N, IP);
4345  } else {
4346    if (NumOps == 1) {
4347      N = new (NodeAllocator) UnarySDNode(Opcode, DL, VTList, Ops[0]);
4348    } else if (NumOps == 2) {
4349      N = new (NodeAllocator) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
4350    } else if (NumOps == 3) {
4351      N = new (NodeAllocator) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1],
4352                                            Ops[2]);
4353    } else {
4354      N = new (NodeAllocator) SDNode(Opcode, DL, VTList, Ops, NumOps);
4355    }
4356  }
4357  AllNodes.push_back(N);
4358#ifndef NDEBUG
4359  VerifySDNode(N);
4360#endif
4361  return SDValue(N, 0);
4362}
4363
4364SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
4365  return getNode(Opcode, DL, VTList, 0, 0);
4366}
4367
4368SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4369                              SDValue N1) {
4370  SDValue Ops[] = { N1 };
4371  return getNode(Opcode, DL, VTList, Ops, 1);
4372}
4373
4374SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4375                              SDValue N1, SDValue N2) {
4376  SDValue Ops[] = { N1, N2 };
4377  return getNode(Opcode, DL, VTList, Ops, 2);
4378}
4379
4380SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4381                              SDValue N1, SDValue N2, SDValue N3) {
4382  SDValue Ops[] = { N1, N2, N3 };
4383  return getNode(Opcode, DL, VTList, Ops, 3);
4384}
4385
4386SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4387                              SDValue N1, SDValue N2, SDValue N3,
4388                              SDValue N4) {
4389  SDValue Ops[] = { N1, N2, N3, N4 };
4390  return getNode(Opcode, DL, VTList, Ops, 4);
4391}
4392
4393SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
4394                              SDValue N1, SDValue N2, SDValue N3,
4395                              SDValue N4, SDValue N5) {
4396  SDValue Ops[] = { N1, N2, N3, N4, N5 };
4397  return getNode(Opcode, DL, VTList, Ops, 5);
4398}
4399
4400SDVTList SelectionDAG::getVTList(EVT VT) {
4401  return makeVTList(SDNode::getValueTypeList(VT), 1);
4402}
4403
4404SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
4405  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4406       E = VTList.rend(); I != E; ++I)
4407    if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
4408      return *I;
4409
4410  EVT *Array = Allocator.Allocate<EVT>(2);
4411  Array[0] = VT1;
4412  Array[1] = VT2;
4413  SDVTList Result = makeVTList(Array, 2);
4414  VTList.push_back(Result);
4415  return Result;
4416}
4417
4418SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
4419  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4420       E = VTList.rend(); I != E; ++I)
4421    if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4422                          I->VTs[2] == VT3)
4423      return *I;
4424
4425  EVT *Array = Allocator.Allocate<EVT>(3);
4426  Array[0] = VT1;
4427  Array[1] = VT2;
4428  Array[2] = VT3;
4429  SDVTList Result = makeVTList(Array, 3);
4430  VTList.push_back(Result);
4431  return Result;
4432}
4433
4434SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
4435  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4436       E = VTList.rend(); I != E; ++I)
4437    if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
4438                          I->VTs[2] == VT3 && I->VTs[3] == VT4)
4439      return *I;
4440
4441  EVT *Array = Allocator.Allocate<EVT>(4);
4442  Array[0] = VT1;
4443  Array[1] = VT2;
4444  Array[2] = VT3;
4445  Array[3] = VT4;
4446  SDVTList Result = makeVTList(Array, 4);
4447  VTList.push_back(Result);
4448  return Result;
4449}
4450
4451SDVTList SelectionDAG::getVTList(const EVT *VTs, unsigned NumVTs) {
4452  switch (NumVTs) {
4453    case 0: llvm_unreachable("Cannot have nodes without results!");
4454    case 1: return getVTList(VTs[0]);
4455    case 2: return getVTList(VTs[0], VTs[1]);
4456    case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
4457    case 4: return getVTList(VTs[0], VTs[1], VTs[2], VTs[3]);
4458    default: break;
4459  }
4460
4461  for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
4462       E = VTList.rend(); I != E; ++I) {
4463    if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
4464      continue;
4465
4466    bool NoMatch = false;
4467    for (unsigned i = 2; i != NumVTs; ++i)
4468      if (VTs[i] != I->VTs[i]) {
4469        NoMatch = true;
4470        break;
4471      }
4472    if (!NoMatch)
4473      return *I;
4474  }
4475
4476  EVT *Array = Allocator.Allocate<EVT>(NumVTs);
4477  std::copy(VTs, VTs+NumVTs, Array);
4478  SDVTList Result = makeVTList(Array, NumVTs);
4479  VTList.push_back(Result);
4480  return Result;
4481}
4482
4483
4484/// UpdateNodeOperands - *Mutate* the specified node in-place to have the
4485/// specified operands.  If the resultant node already exists in the DAG,
4486/// this does not modify the specified node, instead it returns the node that
4487/// already exists.  If the resultant node does not exist in the DAG, the
4488/// input node is returned.  As a degenerate case, if you specify the same
4489/// input operands as the node already has, the input node is returned.
4490SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
4491  assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
4492
4493  // Check to see if there is no change.
4494  if (Op == N->getOperand(0)) return N;
4495
4496  // See if the modified node already exists.
4497  void *InsertPos = 0;
4498  if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
4499    return Existing;
4500
4501  // Nope it doesn't.  Remove the node from its current place in the maps.
4502  if (InsertPos)
4503    if (!RemoveNodeFromCSEMaps(N))
4504      InsertPos = 0;
4505
4506  // Now we update the operands.
4507  N->OperandList[0].set(Op);
4508
4509  // If this gets put into a CSE map, add it.
4510  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4511  return N;
4512}
4513
4514SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
4515  assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
4516
4517  // Check to see if there is no change.
4518  if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
4519    return N;   // No operands changed, just return the input node.
4520
4521  // See if the modified node already exists.
4522  void *InsertPos = 0;
4523  if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
4524    return Existing;
4525
4526  // Nope it doesn't.  Remove the node from its current place in the maps.
4527  if (InsertPos)
4528    if (!RemoveNodeFromCSEMaps(N))
4529      InsertPos = 0;
4530
4531  // Now we update the operands.
4532  if (N->OperandList[0] != Op1)
4533    N->OperandList[0].set(Op1);
4534  if (N->OperandList[1] != Op2)
4535    N->OperandList[1].set(Op2);
4536
4537  // If this gets put into a CSE map, add it.
4538  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4539  return N;
4540}
4541
4542SDNode *SelectionDAG::
4543UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
4544  SDValue Ops[] = { Op1, Op2, Op3 };
4545  return UpdateNodeOperands(N, Ops, 3);
4546}
4547
4548SDNode *SelectionDAG::
4549UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4550                   SDValue Op3, SDValue Op4) {
4551  SDValue Ops[] = { Op1, Op2, Op3, Op4 };
4552  return UpdateNodeOperands(N, Ops, 4);
4553}
4554
4555SDNode *SelectionDAG::
4556UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
4557                   SDValue Op3, SDValue Op4, SDValue Op5) {
4558  SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
4559  return UpdateNodeOperands(N, Ops, 5);
4560}
4561
4562SDNode *SelectionDAG::
4563UpdateNodeOperands(SDNode *N, const SDValue *Ops, unsigned NumOps) {
4564  assert(N->getNumOperands() == NumOps &&
4565         "Update with wrong number of operands");
4566
4567  // Check to see if there is no change.
4568  bool AnyChange = false;
4569  for (unsigned i = 0; i != NumOps; ++i) {
4570    if (Ops[i] != N->getOperand(i)) {
4571      AnyChange = true;
4572      break;
4573    }
4574  }
4575
4576  // No operands changed, just return the input node.
4577  if (!AnyChange) return N;
4578
4579  // See if the modified node already exists.
4580  void *InsertPos = 0;
4581  if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
4582    return Existing;
4583
4584  // Nope it doesn't.  Remove the node from its current place in the maps.
4585  if (InsertPos)
4586    if (!RemoveNodeFromCSEMaps(N))
4587      InsertPos = 0;
4588
4589  // Now we update the operands.
4590  for (unsigned i = 0; i != NumOps; ++i)
4591    if (N->OperandList[i] != Ops[i])
4592      N->OperandList[i].set(Ops[i]);
4593
4594  // If this gets put into a CSE map, add it.
4595  if (InsertPos) CSEMap.InsertNode(N, InsertPos);
4596  return N;
4597}
4598
4599/// DropOperands - Release the operands and set this node to have
4600/// zero operands.
4601void SDNode::DropOperands() {
4602  // Unlike the code in MorphNodeTo that does this, we don't need to
4603  // watch for dead nodes here.
4604  for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
4605    SDUse &Use = *I++;
4606    Use.set(SDValue());
4607  }
4608}
4609
4610/// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
4611/// machine opcode.
4612///
4613SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4614                                   EVT VT) {
4615  SDVTList VTs = getVTList(VT);
4616  return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
4617}
4618
4619SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4620                                   EVT VT, SDValue Op1) {
4621  SDVTList VTs = getVTList(VT);
4622  SDValue Ops[] = { Op1 };
4623  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4624}
4625
4626SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4627                                   EVT VT, SDValue Op1,
4628                                   SDValue Op2) {
4629  SDVTList VTs = getVTList(VT);
4630  SDValue Ops[] = { Op1, Op2 };
4631  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4632}
4633
4634SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4635                                   EVT VT, SDValue Op1,
4636                                   SDValue Op2, SDValue Op3) {
4637  SDVTList VTs = getVTList(VT);
4638  SDValue Ops[] = { Op1, Op2, Op3 };
4639  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4640}
4641
4642SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4643                                   EVT VT, const SDValue *Ops,
4644                                   unsigned NumOps) {
4645  SDVTList VTs = getVTList(VT);
4646  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4647}
4648
4649SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4650                                   EVT VT1, EVT VT2, const SDValue *Ops,
4651                                   unsigned NumOps) {
4652  SDVTList VTs = getVTList(VT1, VT2);
4653  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4654}
4655
4656SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4657                                   EVT VT1, EVT VT2) {
4658  SDVTList VTs = getVTList(VT1, VT2);
4659  return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
4660}
4661
4662SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4663                                   EVT VT1, EVT VT2, EVT VT3,
4664                                   const SDValue *Ops, unsigned NumOps) {
4665  SDVTList VTs = getVTList(VT1, VT2, VT3);
4666  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4667}
4668
4669SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4670                                   EVT VT1, EVT VT2, EVT VT3, EVT VT4,
4671                                   const SDValue *Ops, unsigned NumOps) {
4672  SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4673  return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
4674}
4675
4676SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4677                                   EVT VT1, EVT VT2,
4678                                   SDValue Op1) {
4679  SDVTList VTs = getVTList(VT1, VT2);
4680  SDValue Ops[] = { Op1 };
4681  return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
4682}
4683
4684SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4685                                   EVT VT1, EVT VT2,
4686                                   SDValue Op1, SDValue Op2) {
4687  SDVTList VTs = getVTList(VT1, VT2);
4688  SDValue Ops[] = { Op1, Op2 };
4689  return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
4690}
4691
4692SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4693                                   EVT VT1, EVT VT2,
4694                                   SDValue Op1, SDValue Op2,
4695                                   SDValue Op3) {
4696  SDVTList VTs = getVTList(VT1, VT2);
4697  SDValue Ops[] = { Op1, Op2, Op3 };
4698  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4699}
4700
4701SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4702                                   EVT VT1, EVT VT2, EVT VT3,
4703                                   SDValue Op1, SDValue Op2,
4704                                   SDValue Op3) {
4705  SDVTList VTs = getVTList(VT1, VT2, VT3);
4706  SDValue Ops[] = { Op1, Op2, Op3 };
4707  return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
4708}
4709
4710SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
4711                                   SDVTList VTs, const SDValue *Ops,
4712                                   unsigned NumOps) {
4713  N = MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
4714  // Reset the NodeID to -1.
4715  N->setNodeId(-1);
4716  return N;
4717}
4718
4719/// MorphNodeTo - This *mutates* the specified node to have the specified
4720/// return type, opcode, and operands.
4721///
4722/// Note that MorphNodeTo returns the resultant node.  If there is already a
4723/// node of the specified opcode and operands, it returns that node instead of
4724/// the current one.  Note that the DebugLoc need not be the same.
4725///
4726/// Using MorphNodeTo is faster than creating a new node and swapping it in
4727/// with ReplaceAllUsesWith both because it often avoids allocating a new
4728/// node, and because it doesn't require CSE recalculation for any of
4729/// the node's users.
4730///
4731SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
4732                                  SDVTList VTs, const SDValue *Ops,
4733                                  unsigned NumOps) {
4734  // If an identical node already exists, use it.
4735  void *IP = 0;
4736  if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
4737    FoldingSetNodeID ID;
4738    AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
4739    if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
4740      return ON;
4741  }
4742
4743  if (!RemoveNodeFromCSEMaps(N))
4744    IP = 0;
4745
4746  // Start the morphing.
4747  N->NodeType = Opc;
4748  N->ValueList = VTs.VTs;
4749  N->NumValues = VTs.NumVTs;
4750
4751  // Clear the operands list, updating used nodes to remove this from their
4752  // use list.  Keep track of any operands that become dead as a result.
4753  SmallPtrSet<SDNode*, 16> DeadNodeSet;
4754  for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
4755    SDUse &Use = *I++;
4756    SDNode *Used = Use.getNode();
4757    Use.set(SDValue());
4758    if (Used->use_empty())
4759      DeadNodeSet.insert(Used);
4760  }
4761
4762  if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N)) {
4763    // Initialize the memory references information.
4764    MN->setMemRefs(0, 0);
4765    // If NumOps is larger than the # of operands we can have in a
4766    // MachineSDNode, reallocate the operand list.
4767    if (NumOps > MN->NumOperands || !MN->OperandsNeedDelete) {
4768      if (MN->OperandsNeedDelete)
4769        delete[] MN->OperandList;
4770      if (NumOps > array_lengthof(MN->LocalOperands))
4771        // We're creating a final node that will live unmorphed for the
4772        // remainder of the current SelectionDAG iteration, so we can allocate
4773        // the operands directly out of a pool with no recycling metadata.
4774        MN->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4775                         Ops, NumOps);
4776      else
4777        MN->InitOperands(MN->LocalOperands, Ops, NumOps);
4778      MN->OperandsNeedDelete = false;
4779    } else
4780      MN->InitOperands(MN->OperandList, Ops, NumOps);
4781  } else {
4782    // If NumOps is larger than the # of operands we currently have, reallocate
4783    // the operand list.
4784    if (NumOps > N->NumOperands) {
4785      if (N->OperandsNeedDelete)
4786        delete[] N->OperandList;
4787      N->InitOperands(new SDUse[NumOps], Ops, NumOps);
4788      N->OperandsNeedDelete = true;
4789    } else
4790      N->InitOperands(N->OperandList, Ops, NumOps);
4791  }
4792
4793  // Delete any nodes that are still dead after adding the uses for the
4794  // new operands.
4795  if (!DeadNodeSet.empty()) {
4796    SmallVector<SDNode *, 16> DeadNodes;
4797    for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
4798         E = DeadNodeSet.end(); I != E; ++I)
4799      if ((*I)->use_empty())
4800        DeadNodes.push_back(*I);
4801    RemoveDeadNodes(DeadNodes);
4802  }
4803
4804  if (IP)
4805    CSEMap.InsertNode(N, IP);   // Memoize the new node.
4806  return N;
4807}
4808
4809
4810/// getMachineNode - These are used for target selectors to create a new node
4811/// with specified return type(s), MachineInstr opcode, and operands.
4812///
4813/// Note that getMachineNode returns the resultant node.  If there is already a
4814/// node of the specified opcode and operands, it returns that node instead of
4815/// the current one.
4816MachineSDNode *
4817SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT) {
4818  SDVTList VTs = getVTList(VT);
4819  return getMachineNode(Opcode, dl, VTs, 0, 0);
4820}
4821
4822MachineSDNode *
4823SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT, SDValue Op1) {
4824  SDVTList VTs = getVTList(VT);
4825  SDValue Ops[] = { Op1 };
4826  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4827}
4828
4829MachineSDNode *
4830SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4831                             SDValue Op1, SDValue Op2) {
4832  SDVTList VTs = getVTList(VT);
4833  SDValue Ops[] = { Op1, Op2 };
4834  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4835}
4836
4837MachineSDNode *
4838SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4839                             SDValue Op1, SDValue Op2, SDValue Op3) {
4840  SDVTList VTs = getVTList(VT);
4841  SDValue Ops[] = { Op1, Op2, Op3 };
4842  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4843}
4844
4845MachineSDNode *
4846SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT,
4847                             const SDValue *Ops, unsigned NumOps) {
4848  SDVTList VTs = getVTList(VT);
4849  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4850}
4851
4852MachineSDNode *
4853SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1, EVT VT2) {
4854  SDVTList VTs = getVTList(VT1, VT2);
4855  return getMachineNode(Opcode, dl, VTs, 0, 0);
4856}
4857
4858MachineSDNode *
4859SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4860                             EVT VT1, EVT VT2, SDValue Op1) {
4861  SDVTList VTs = getVTList(VT1, VT2);
4862  SDValue Ops[] = { Op1 };
4863  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4864}
4865
4866MachineSDNode *
4867SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4868                             EVT VT1, EVT VT2, SDValue Op1, SDValue Op2) {
4869  SDVTList VTs = getVTList(VT1, VT2);
4870  SDValue Ops[] = { Op1, Op2 };
4871  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4872}
4873
4874MachineSDNode *
4875SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4876                             EVT VT1, EVT VT2, SDValue Op1,
4877                             SDValue Op2, SDValue Op3) {
4878  SDVTList VTs = getVTList(VT1, VT2);
4879  SDValue Ops[] = { Op1, Op2, Op3 };
4880  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4881}
4882
4883MachineSDNode *
4884SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4885                             EVT VT1, EVT VT2,
4886                             const SDValue *Ops, unsigned NumOps) {
4887  SDVTList VTs = getVTList(VT1, VT2);
4888  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4889}
4890
4891MachineSDNode *
4892SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4893                             EVT VT1, EVT VT2, EVT VT3,
4894                             SDValue Op1, SDValue Op2) {
4895  SDVTList VTs = getVTList(VT1, VT2, VT3);
4896  SDValue Ops[] = { Op1, Op2 };
4897  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4898}
4899
4900MachineSDNode *
4901SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4902                             EVT VT1, EVT VT2, EVT VT3,
4903                             SDValue Op1, SDValue Op2, SDValue Op3) {
4904  SDVTList VTs = getVTList(VT1, VT2, VT3);
4905  SDValue Ops[] = { Op1, Op2, Op3 };
4906  return getMachineNode(Opcode, dl, VTs, Ops, array_lengthof(Ops));
4907}
4908
4909MachineSDNode *
4910SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4911                             EVT VT1, EVT VT2, EVT VT3,
4912                             const SDValue *Ops, unsigned NumOps) {
4913  SDVTList VTs = getVTList(VT1, VT2, VT3);
4914  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4915}
4916
4917MachineSDNode *
4918SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl, EVT VT1,
4919                             EVT VT2, EVT VT3, EVT VT4,
4920                             const SDValue *Ops, unsigned NumOps) {
4921  SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
4922  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4923}
4924
4925MachineSDNode *
4926SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc dl,
4927                             const std::vector<EVT> &ResultTys,
4928                             const SDValue *Ops, unsigned NumOps) {
4929  SDVTList VTs = getVTList(&ResultTys[0], ResultTys.size());
4930  return getMachineNode(Opcode, dl, VTs, Ops, NumOps);
4931}
4932
4933MachineSDNode *
4934SelectionDAG::getMachineNode(unsigned Opcode, DebugLoc DL, SDVTList VTs,
4935                             const SDValue *Ops, unsigned NumOps) {
4936  bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
4937  MachineSDNode *N;
4938  void *IP;
4939
4940  if (DoCSE) {
4941    FoldingSetNodeID ID;
4942    AddNodeIDNode(ID, ~Opcode, VTs, Ops, NumOps);
4943    IP = 0;
4944    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
4945      return cast<MachineSDNode>(E);
4946  }
4947
4948  // Allocate a new MachineSDNode.
4949  N = new (NodeAllocator) MachineSDNode(~Opcode, DL, VTs);
4950
4951  // Initialize the operands list.
4952  if (NumOps > array_lengthof(N->LocalOperands))
4953    // We're creating a final node that will live unmorphed for the
4954    // remainder of the current SelectionDAG iteration, so we can allocate
4955    // the operands directly out of a pool with no recycling metadata.
4956    N->InitOperands(OperandAllocator.Allocate<SDUse>(NumOps),
4957                    Ops, NumOps);
4958  else
4959    N->InitOperands(N->LocalOperands, Ops, NumOps);
4960  N->OperandsNeedDelete = false;
4961
4962  if (DoCSE)
4963    CSEMap.InsertNode(N, IP);
4964
4965  AllNodes.push_back(N);
4966#ifndef NDEBUG
4967  VerifyMachineNode(N);
4968#endif
4969  return N;
4970}
4971
4972/// getTargetExtractSubreg - A convenience function for creating
4973/// TargetOpcode::EXTRACT_SUBREG nodes.
4974SDValue
4975SelectionDAG::getTargetExtractSubreg(int SRIdx, DebugLoc DL, EVT VT,
4976                                     SDValue Operand) {
4977  SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4978  SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
4979                                  VT, Operand, SRIdxVal);
4980  return SDValue(Subreg, 0);
4981}
4982
4983/// getTargetInsertSubreg - A convenience function for creating
4984/// TargetOpcode::INSERT_SUBREG nodes.
4985SDValue
4986SelectionDAG::getTargetInsertSubreg(int SRIdx, DebugLoc DL, EVT VT,
4987                                    SDValue Operand, SDValue Subreg) {
4988  SDValue SRIdxVal = getTargetConstant(SRIdx, MVT::i32);
4989  SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
4990                                  VT, Operand, Subreg, SRIdxVal);
4991  return SDValue(Result, 0);
4992}
4993
4994/// getNodeIfExists - Get the specified node if it's already available, or
4995/// else return NULL.
4996SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
4997                                      const SDValue *Ops, unsigned NumOps) {
4998  if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
4999    FoldingSetNodeID ID;
5000    AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
5001    void *IP = 0;
5002    if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
5003      return E;
5004  }
5005  return NULL;
5006}
5007
5008/// getDbgValue - Creates a SDDbgValue node.
5009///
5010SDDbgValue *
5011SelectionDAG::getDbgValue(MDNode *MDPtr, SDNode *N, unsigned R, uint64_t Off,
5012                          DebugLoc DL, unsigned O) {
5013  return new (Allocator) SDDbgValue(MDPtr, N, R, Off, DL, O);
5014}
5015
5016SDDbgValue *
5017SelectionDAG::getDbgValue(MDNode *MDPtr, const Value *C, uint64_t Off,
5018                          DebugLoc DL, unsigned O) {
5019  return new (Allocator) SDDbgValue(MDPtr, C, Off, DL, O);
5020}
5021
5022SDDbgValue *
5023SelectionDAG::getDbgValue(MDNode *MDPtr, unsigned FI, uint64_t Off,
5024                          DebugLoc DL, unsigned O) {
5025  return new (Allocator) SDDbgValue(MDPtr, FI, Off, DL, O);
5026}
5027
5028namespace {
5029
5030/// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
5031/// pointed to by a use iterator is deleted, increment the use iterator
5032/// so that it doesn't dangle.
5033///
5034/// This class also manages a "downlink" DAGUpdateListener, to forward
5035/// messages to ReplaceAllUsesWith's callers.
5036///
5037class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
5038  SelectionDAG::DAGUpdateListener *DownLink;
5039  SDNode::use_iterator &UI;
5040  SDNode::use_iterator &UE;
5041
5042  virtual void NodeDeleted(SDNode *N, SDNode *E) {
5043    // Increment the iterator as needed.
5044    while (UI != UE && N == *UI)
5045      ++UI;
5046
5047    // Then forward the message.
5048    if (DownLink) DownLink->NodeDeleted(N, E);
5049  }
5050
5051  virtual void NodeUpdated(SDNode *N) {
5052    // Just forward the message.
5053    if (DownLink) DownLink->NodeUpdated(N);
5054  }
5055
5056public:
5057  RAUWUpdateListener(SelectionDAG::DAGUpdateListener *dl,
5058                     SDNode::use_iterator &ui,
5059                     SDNode::use_iterator &ue)
5060    : DownLink(dl), UI(ui), UE(ue) {}
5061};
5062
5063}
5064
5065/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5066/// This can cause recursive merging of nodes in the DAG.
5067///
5068/// This version assumes From has a single result value.
5069///
5070void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
5071                                      DAGUpdateListener *UpdateListener) {
5072  SDNode *From = FromN.getNode();
5073  assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
5074         "Cannot replace with this method!");
5075  assert(From != To.getNode() && "Cannot replace uses of with self");
5076
5077  // Iterate over all the existing uses of From. New uses will be added
5078  // to the beginning of the use list, which we avoid visiting.
5079  // This specifically avoids visiting uses of From that arise while the
5080  // replacement is happening, because any such uses would be the result
5081  // of CSE: If an existing node looks like From after one of its operands
5082  // is replaced by To, we don't want to replace of all its users with To
5083  // too. See PR3018 for more info.
5084  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5085  RAUWUpdateListener Listener(UpdateListener, UI, UE);
5086  while (UI != UE) {
5087    SDNode *User = *UI;
5088
5089    // This node is about to morph, remove its old self from the CSE maps.
5090    RemoveNodeFromCSEMaps(User);
5091
5092    // A user can appear in a use list multiple times, and when this
5093    // happens the uses are usually next to each other in the list.
5094    // To help reduce the number of CSE recomputations, process all
5095    // the uses of this user that we can find this way.
5096    do {
5097      SDUse &Use = UI.getUse();
5098      ++UI;
5099      Use.set(To);
5100    } while (UI != UE && *UI == User);
5101
5102    // Now that we have modified User, add it back to the CSE maps.  If it
5103    // already exists there, recursively merge the results together.
5104    AddModifiedNodeToCSEMaps(User, &Listener);
5105  }
5106}
5107
5108/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5109/// This can cause recursive merging of nodes in the DAG.
5110///
5111/// This version assumes that for each value of From, there is a
5112/// corresponding value in To in the same position with the same type.
5113///
5114void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
5115                                      DAGUpdateListener *UpdateListener) {
5116#ifndef NDEBUG
5117  for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
5118    assert((!From->hasAnyUseOfValue(i) ||
5119            From->getValueType(i) == To->getValueType(i)) &&
5120           "Cannot use this version of ReplaceAllUsesWith!");
5121#endif
5122
5123  // Handle the trivial case.
5124  if (From == To)
5125    return;
5126
5127  // Iterate over just the existing users of From. See the comments in
5128  // the ReplaceAllUsesWith above.
5129  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5130  RAUWUpdateListener Listener(UpdateListener, UI, UE);
5131  while (UI != UE) {
5132    SDNode *User = *UI;
5133
5134    // This node is about to morph, remove its old self from the CSE maps.
5135    RemoveNodeFromCSEMaps(User);
5136
5137    // A user can appear in a use list multiple times, and when this
5138    // happens the uses are usually next to each other in the list.
5139    // To help reduce the number of CSE recomputations, process all
5140    // the uses of this user that we can find this way.
5141    do {
5142      SDUse &Use = UI.getUse();
5143      ++UI;
5144      Use.setNode(To);
5145    } while (UI != UE && *UI == User);
5146
5147    // Now that we have modified User, add it back to the CSE maps.  If it
5148    // already exists there, recursively merge the results together.
5149    AddModifiedNodeToCSEMaps(User, &Listener);
5150  }
5151}
5152
5153/// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
5154/// This can cause recursive merging of nodes in the DAG.
5155///
5156/// This version can replace From with any result values.  To must match the
5157/// number and types of values returned by From.
5158void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
5159                                      const SDValue *To,
5160                                      DAGUpdateListener *UpdateListener) {
5161  if (From->getNumValues() == 1)  // Handle the simple case efficiently.
5162    return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
5163
5164  // Iterate over just the existing users of From. See the comments in
5165  // the ReplaceAllUsesWith above.
5166  SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
5167  RAUWUpdateListener Listener(UpdateListener, UI, UE);
5168  while (UI != UE) {
5169    SDNode *User = *UI;
5170
5171    // This node is about to morph, remove its old self from the CSE maps.
5172    RemoveNodeFromCSEMaps(User);
5173
5174    // A user can appear in a use list multiple times, and when this
5175    // happens the uses are usually next to each other in the list.
5176    // To help reduce the number of CSE recomputations, process all
5177    // the uses of this user that we can find this way.
5178    do {
5179      SDUse &Use = UI.getUse();
5180      const SDValue &ToOp = To[Use.getResNo()];
5181      ++UI;
5182      Use.set(ToOp);
5183    } while (UI != UE && *UI == User);
5184
5185    // Now that we have modified User, add it back to the CSE maps.  If it
5186    // already exists there, recursively merge the results together.
5187    AddModifiedNodeToCSEMaps(User, &Listener);
5188  }
5189}
5190
5191/// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
5192/// uses of other values produced by From.getNode() alone.  The Deleted
5193/// vector is handled the same way as for ReplaceAllUsesWith.
5194void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
5195                                             DAGUpdateListener *UpdateListener){
5196  // Handle the really simple, really trivial case efficiently.
5197  if (From == To) return;
5198
5199  // Handle the simple, trivial, case efficiently.
5200  if (From.getNode()->getNumValues() == 1) {
5201    ReplaceAllUsesWith(From, To, UpdateListener);
5202    return;
5203  }
5204
5205  // Iterate over just the existing users of From. See the comments in
5206  // the ReplaceAllUsesWith above.
5207  SDNode::use_iterator UI = From.getNode()->use_begin(),
5208                       UE = From.getNode()->use_end();
5209  RAUWUpdateListener Listener(UpdateListener, UI, UE);
5210  while (UI != UE) {
5211    SDNode *User = *UI;
5212    bool UserRemovedFromCSEMaps = false;
5213
5214    // A user can appear in a use list multiple times, and when this
5215    // happens the uses are usually next to each other in the list.
5216    // To help reduce the number of CSE recomputations, process all
5217    // the uses of this user that we can find this way.
5218    do {
5219      SDUse &Use = UI.getUse();
5220
5221      // Skip uses of different values from the same node.
5222      if (Use.getResNo() != From.getResNo()) {
5223        ++UI;
5224        continue;
5225      }
5226
5227      // If this node hasn't been modified yet, it's still in the CSE maps,
5228      // so remove its old self from the CSE maps.
5229      if (!UserRemovedFromCSEMaps) {
5230        RemoveNodeFromCSEMaps(User);
5231        UserRemovedFromCSEMaps = true;
5232      }
5233
5234      ++UI;
5235      Use.set(To);
5236    } while (UI != UE && *UI == User);
5237
5238    // We are iterating over all uses of the From node, so if a use
5239    // doesn't use the specific value, no changes are made.
5240    if (!UserRemovedFromCSEMaps)
5241      continue;
5242
5243    // Now that we have modified User, add it back to the CSE maps.  If it
5244    // already exists there, recursively merge the results together.
5245    AddModifiedNodeToCSEMaps(User, &Listener);
5246  }
5247}
5248
5249namespace {
5250  /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
5251  /// to record information about a use.
5252  struct UseMemo {
5253    SDNode *User;
5254    unsigned Index;
5255    SDUse *Use;
5256  };
5257
5258  /// operator< - Sort Memos by User.
5259  bool operator<(const UseMemo &L, const UseMemo &R) {
5260    return (intptr_t)L.User < (intptr_t)R.User;
5261  }
5262}
5263
5264/// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
5265/// uses of other values produced by From.getNode() alone.  The same value
5266/// may appear in both the From and To list.  The Deleted vector is
5267/// handled the same way as for ReplaceAllUsesWith.
5268void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
5269                                              const SDValue *To,
5270                                              unsigned Num,
5271                                              DAGUpdateListener *UpdateListener){
5272  // Handle the simple, trivial case efficiently.
5273  if (Num == 1)
5274    return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
5275
5276  // Read up all the uses and make records of them. This helps
5277  // processing new uses that are introduced during the
5278  // replacement process.
5279  SmallVector<UseMemo, 4> Uses;
5280  for (unsigned i = 0; i != Num; ++i) {
5281    unsigned FromResNo = From[i].getResNo();
5282    SDNode *FromNode = From[i].getNode();
5283    for (SDNode::use_iterator UI = FromNode->use_begin(),
5284         E = FromNode->use_end(); UI != E; ++UI) {
5285      SDUse &Use = UI.getUse();
5286      if (Use.getResNo() == FromResNo) {
5287        UseMemo Memo = { *UI, i, &Use };
5288        Uses.push_back(Memo);
5289      }
5290    }
5291  }
5292
5293  // Sort the uses, so that all the uses from a given User are together.
5294  std::sort(Uses.begin(), Uses.end());
5295
5296  for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
5297       UseIndex != UseIndexEnd; ) {
5298    // We know that this user uses some value of From.  If it is the right
5299    // value, update it.
5300    SDNode *User = Uses[UseIndex].User;
5301
5302    // This node is about to morph, remove its old self from the CSE maps.
5303    RemoveNodeFromCSEMaps(User);
5304
5305    // The Uses array is sorted, so all the uses for a given User
5306    // are next to each other in the list.
5307    // To help reduce the number of CSE recomputations, process all
5308    // the uses of this user that we can find this way.
5309    do {
5310      unsigned i = Uses[UseIndex].Index;
5311      SDUse &Use = *Uses[UseIndex].Use;
5312      ++UseIndex;
5313
5314      Use.set(To[i]);
5315    } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
5316
5317    // Now that we have modified User, add it back to the CSE maps.  If it
5318    // already exists there, recursively merge the results together.
5319    AddModifiedNodeToCSEMaps(User, UpdateListener);
5320  }
5321}
5322
5323/// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
5324/// based on their topological order. It returns the maximum id and a vector
5325/// of the SDNodes* in assigned order by reference.
5326unsigned SelectionDAG::AssignTopologicalOrder() {
5327
5328  unsigned DAGSize = 0;
5329
5330  // SortedPos tracks the progress of the algorithm. Nodes before it are
5331  // sorted, nodes after it are unsorted. When the algorithm completes
5332  // it is at the end of the list.
5333  allnodes_iterator SortedPos = allnodes_begin();
5334
5335  // Visit all the nodes. Move nodes with no operands to the front of
5336  // the list immediately. Annotate nodes that do have operands with their
5337  // operand count. Before we do this, the Node Id fields of the nodes
5338  // may contain arbitrary values. After, the Node Id fields for nodes
5339  // before SortedPos will contain the topological sort index, and the
5340  // Node Id fields for nodes At SortedPos and after will contain the
5341  // count of outstanding operands.
5342  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
5343    SDNode *N = I++;
5344    checkForCycles(N);
5345    unsigned Degree = N->getNumOperands();
5346    if (Degree == 0) {
5347      // A node with no uses, add it to the result array immediately.
5348      N->setNodeId(DAGSize++);
5349      allnodes_iterator Q = N;
5350      if (Q != SortedPos)
5351        SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
5352      assert(SortedPos != AllNodes.end() && "Overran node list");
5353      ++SortedPos;
5354    } else {
5355      // Temporarily use the Node Id as scratch space for the degree count.
5356      N->setNodeId(Degree);
5357    }
5358  }
5359
5360  // Visit all the nodes. As we iterate, moves nodes into sorted order,
5361  // such that by the time the end is reached all nodes will be sorted.
5362  for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
5363    SDNode *N = I;
5364    checkForCycles(N);
5365    // N is in sorted position, so all its uses have one less operand
5366    // that needs to be sorted.
5367    for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5368         UI != UE; ++UI) {
5369      SDNode *P = *UI;
5370      unsigned Degree = P->getNodeId();
5371      assert(Degree != 0 && "Invalid node degree");
5372      --Degree;
5373      if (Degree == 0) {
5374        // All of P's operands are sorted, so P may sorted now.
5375        P->setNodeId(DAGSize++);
5376        if (P != SortedPos)
5377          SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
5378        assert(SortedPos != AllNodes.end() && "Overran node list");
5379        ++SortedPos;
5380      } else {
5381        // Update P's outstanding operand count.
5382        P->setNodeId(Degree);
5383      }
5384    }
5385    if (I == SortedPos) {
5386#ifndef NDEBUG
5387      SDNode *S = ++I;
5388      dbgs() << "Overran sorted position:\n";
5389      S->dumprFull();
5390#endif
5391      llvm_unreachable(0);
5392    }
5393  }
5394
5395  assert(SortedPos == AllNodes.end() &&
5396         "Topological sort incomplete!");
5397  assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
5398         "First node in topological sort is not the entry token!");
5399  assert(AllNodes.front().getNodeId() == 0 &&
5400         "First node in topological sort has non-zero id!");
5401  assert(AllNodes.front().getNumOperands() == 0 &&
5402         "First node in topological sort has operands!");
5403  assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
5404         "Last node in topologic sort has unexpected id!");
5405  assert(AllNodes.back().use_empty() &&
5406         "Last node in topologic sort has users!");
5407  assert(DAGSize == allnodes_size() && "Node count mismatch!");
5408  return DAGSize;
5409}
5410
5411/// AssignOrdering - Assign an order to the SDNode.
5412void SelectionDAG::AssignOrdering(const SDNode *SD, unsigned Order) {
5413  assert(SD && "Trying to assign an order to a null node!");
5414  Ordering->add(SD, Order);
5415}
5416
5417/// GetOrdering - Get the order for the SDNode.
5418unsigned SelectionDAG::GetOrdering(const SDNode *SD) const {
5419  assert(SD && "Trying to get the order of a null node!");
5420  return Ordering->getOrder(SD);
5421}
5422
5423/// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
5424/// value is produced by SD.
5425void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
5426  DbgInfo->add(DB, SD, isParameter);
5427  if (SD)
5428    SD->setHasDebugValue(true);
5429}
5430
5431//===----------------------------------------------------------------------===//
5432//                              SDNode Class
5433//===----------------------------------------------------------------------===//
5434
5435HandleSDNode::~HandleSDNode() {
5436  DropOperands();
5437}
5438
5439GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, DebugLoc DL,
5440                                         const GlobalValue *GA,
5441                                         EVT VT, int64_t o, unsigned char TF)
5442  : SDNode(Opc, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
5443  TheGlobal = GA;
5444}
5445
5446MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, EVT memvt,
5447                     MachineMemOperand *mmo)
5448 : SDNode(Opc, dl, VTs), MemoryVT(memvt), MMO(mmo) {
5449  SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5450                                      MMO->isNonTemporal());
5451  assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5452  assert(isNonTemporal() == MMO->isNonTemporal() &&
5453         "Non-temporal encoding error!");
5454  assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5455}
5456
5457MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs,
5458                     const SDValue *Ops, unsigned NumOps, EVT memvt,
5459                     MachineMemOperand *mmo)
5460   : SDNode(Opc, dl, VTs, Ops, NumOps),
5461     MemoryVT(memvt), MMO(mmo) {
5462  SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, MMO->isVolatile(),
5463                                      MMO->isNonTemporal());
5464  assert(isVolatile() == MMO->isVolatile() && "Volatile encoding error!");
5465  assert(memvt.getStoreSize() == MMO->getSize() && "Size mismatch!");
5466}
5467
5468/// Profile - Gather unique data for the node.
5469///
5470void SDNode::Profile(FoldingSetNodeID &ID) const {
5471  AddNodeIDNode(ID, this);
5472}
5473
5474namespace {
5475  struct EVTArray {
5476    std::vector<EVT> VTs;
5477
5478    EVTArray() {
5479      VTs.reserve(MVT::LAST_VALUETYPE);
5480      for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
5481        VTs.push_back(MVT((MVT::SimpleValueType)i));
5482    }
5483  };
5484}
5485
5486static ManagedStatic<std::set<EVT, EVT::compareRawBits> > EVTs;
5487static ManagedStatic<EVTArray> SimpleVTArray;
5488static ManagedStatic<sys::SmartMutex<true> > VTMutex;
5489
5490/// getValueTypeList - Return a pointer to the specified value type.
5491///
5492const EVT *SDNode::getValueTypeList(EVT VT) {
5493  if (VT.isExtended()) {
5494    sys::SmartScopedLock<true> Lock(*VTMutex);
5495    return &(*EVTs->insert(VT).first);
5496  } else {
5497    assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
5498           "Value type out of range!");
5499    return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
5500  }
5501}
5502
5503/// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
5504/// indicated value.  This method ignores uses of other values defined by this
5505/// operation.
5506bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
5507  assert(Value < getNumValues() && "Bad value!");
5508
5509  // TODO: Only iterate over uses of a given value of the node
5510  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
5511    if (UI.getUse().getResNo() == Value) {
5512      if (NUses == 0)
5513        return false;
5514      --NUses;
5515    }
5516  }
5517
5518  // Found exactly the right number of uses?
5519  return NUses == 0;
5520}
5521
5522
5523/// hasAnyUseOfValue - Return true if there are any use of the indicated
5524/// value. This method ignores uses of other values defined by this operation.
5525bool SDNode::hasAnyUseOfValue(unsigned Value) const {
5526  assert(Value < getNumValues() && "Bad value!");
5527
5528  for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
5529    if (UI.getUse().getResNo() == Value)
5530      return true;
5531
5532  return false;
5533}
5534
5535
5536/// isOnlyUserOf - Return true if this node is the only use of N.
5537///
5538bool SDNode::isOnlyUserOf(SDNode *N) const {
5539  bool Seen = false;
5540  for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
5541    SDNode *User = *I;
5542    if (User == this)
5543      Seen = true;
5544    else
5545      return false;
5546  }
5547
5548  return Seen;
5549}
5550
5551/// isOperand - Return true if this node is an operand of N.
5552///
5553bool SDValue::isOperandOf(SDNode *N) const {
5554  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
5555    if (*this == N->getOperand(i))
5556      return true;
5557  return false;
5558}
5559
5560bool SDNode::isOperandOf(SDNode *N) const {
5561  for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
5562    if (this == N->OperandList[i].getNode())
5563      return true;
5564  return false;
5565}
5566
5567/// reachesChainWithoutSideEffects - Return true if this operand (which must
5568/// be a chain) reaches the specified operand without crossing any
5569/// side-effecting instructions on any chain path.  In practice, this looks
5570/// through token factors and non-volatile loads.  In order to remain efficient,
5571/// this only looks a couple of nodes in, it does not do an exhaustive search.
5572bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
5573                                               unsigned Depth) const {
5574  if (*this == Dest) return true;
5575
5576  // Don't search too deeply, we just want to be able to see through
5577  // TokenFactor's etc.
5578  if (Depth == 0) return false;
5579
5580  // If this is a token factor, all inputs to the TF happen in parallel.  If any
5581  // of the operands of the TF does not reach dest, then we cannot do the xform.
5582  if (getOpcode() == ISD::TokenFactor) {
5583    for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
5584      if (!getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
5585        return false;
5586    return true;
5587  }
5588
5589  // Loads don't have side effects, look through them.
5590  if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
5591    if (!Ld->isVolatile())
5592      return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
5593  }
5594  return false;
5595}
5596
5597/// isPredecessorOf - Return true if this node is a predecessor of N. This node
5598/// is either an operand of N or it can be reached by traversing up the operands.
5599/// NOTE: this is an expensive method. Use it carefully.
5600bool SDNode::isPredecessorOf(SDNode *N) const {
5601  SmallPtrSet<SDNode *, 32> Visited;
5602  SmallVector<SDNode *, 16> Worklist;
5603  Worklist.push_back(N);
5604
5605  do {
5606    N = Worklist.pop_back_val();
5607    for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
5608      SDNode *Op = N->getOperand(i).getNode();
5609      if (Op == this)
5610        return true;
5611      if (Visited.insert(Op))
5612        Worklist.push_back(Op);
5613    }
5614  } while (!Worklist.empty());
5615
5616  return false;
5617}
5618
5619uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
5620  assert(Num < NumOperands && "Invalid child # of SDNode!");
5621  return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
5622}
5623
5624std::string SDNode::getOperationName(const SelectionDAG *G) const {
5625  switch (getOpcode()) {
5626  default:
5627    if (getOpcode() < ISD::BUILTIN_OP_END)
5628      return "<<Unknown DAG Node>>";
5629    if (isMachineOpcode()) {
5630      if (G)
5631        if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
5632          if (getMachineOpcode() < TII->getNumOpcodes())
5633            return TII->get(getMachineOpcode()).getName();
5634      return "<<Unknown Machine Node #" + utostr(getOpcode()) + ">>";
5635    }
5636    if (G) {
5637      const TargetLowering &TLI = G->getTargetLoweringInfo();
5638      const char *Name = TLI.getTargetNodeName(getOpcode());
5639      if (Name) return Name;
5640      return "<<Unknown Target Node #" + utostr(getOpcode()) + ">>";
5641    }
5642    return "<<Unknown Node #" + utostr(getOpcode()) + ">>";
5643
5644#ifndef NDEBUG
5645  case ISD::DELETED_NODE:
5646    return "<<Deleted Node!>>";
5647#endif
5648  case ISD::PREFETCH:      return "Prefetch";
5649  case ISD::MEMBARRIER:    return "MemBarrier";
5650  case ISD::ATOMIC_CMP_SWAP:    return "AtomicCmpSwap";
5651  case ISD::ATOMIC_SWAP:        return "AtomicSwap";
5652  case ISD::ATOMIC_LOAD_ADD:    return "AtomicLoadAdd";
5653  case ISD::ATOMIC_LOAD_SUB:    return "AtomicLoadSub";
5654  case ISD::ATOMIC_LOAD_AND:    return "AtomicLoadAnd";
5655  case ISD::ATOMIC_LOAD_OR:     return "AtomicLoadOr";
5656  case ISD::ATOMIC_LOAD_XOR:    return "AtomicLoadXor";
5657  case ISD::ATOMIC_LOAD_NAND:   return "AtomicLoadNand";
5658  case ISD::ATOMIC_LOAD_MIN:    return "AtomicLoadMin";
5659  case ISD::ATOMIC_LOAD_MAX:    return "AtomicLoadMax";
5660  case ISD::ATOMIC_LOAD_UMIN:   return "AtomicLoadUMin";
5661  case ISD::ATOMIC_LOAD_UMAX:   return "AtomicLoadUMax";
5662  case ISD::PCMARKER:      return "PCMarker";
5663  case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
5664  case ISD::SRCVALUE:      return "SrcValue";
5665  case ISD::MDNODE_SDNODE: return "MDNode";
5666  case ISD::EntryToken:    return "EntryToken";
5667  case ISD::TokenFactor:   return "TokenFactor";
5668  case ISD::AssertSext:    return "AssertSext";
5669  case ISD::AssertZext:    return "AssertZext";
5670
5671  case ISD::BasicBlock:    return "BasicBlock";
5672  case ISD::VALUETYPE:     return "ValueType";
5673  case ISD::Register:      return "Register";
5674
5675  case ISD::Constant:      return "Constant";
5676  case ISD::ConstantFP:    return "ConstantFP";
5677  case ISD::GlobalAddress: return "GlobalAddress";
5678  case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
5679  case ISD::FrameIndex:    return "FrameIndex";
5680  case ISD::JumpTable:     return "JumpTable";
5681  case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
5682  case ISD::RETURNADDR: return "RETURNADDR";
5683  case ISD::FRAMEADDR: return "FRAMEADDR";
5684  case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
5685  case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
5686  case ISD::LSDAADDR: return "LSDAADDR";
5687  case ISD::EHSELECTION: return "EHSELECTION";
5688  case ISD::EH_RETURN: return "EH_RETURN";
5689  case ISD::EH_SJLJ_SETJMP: return "EH_SJLJ_SETJMP";
5690  case ISD::EH_SJLJ_LONGJMP: return "EH_SJLJ_LONGJMP";
5691  case ISD::EH_SJLJ_DISPATCHSETUP: return "EH_SJLJ_DISPATCHSETUP";
5692  case ISD::ConstantPool:  return "ConstantPool";
5693  case ISD::ExternalSymbol: return "ExternalSymbol";
5694  case ISD::BlockAddress:  return "BlockAddress";
5695  case ISD::INTRINSIC_WO_CHAIN:
5696  case ISD::INTRINSIC_VOID:
5697  case ISD::INTRINSIC_W_CHAIN: {
5698    unsigned OpNo = getOpcode() == ISD::INTRINSIC_WO_CHAIN ? 0 : 1;
5699    unsigned IID = cast<ConstantSDNode>(getOperand(OpNo))->getZExtValue();
5700    if (IID < Intrinsic::num_intrinsics)
5701      return Intrinsic::getName((Intrinsic::ID)IID);
5702    else if (const TargetIntrinsicInfo *TII = G->getTarget().getIntrinsicInfo())
5703      return TII->getName(IID);
5704    llvm_unreachable("Invalid intrinsic ID");
5705  }
5706
5707  case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
5708  case ISD::TargetConstant: return "TargetConstant";
5709  case ISD::TargetConstantFP:return "TargetConstantFP";
5710  case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
5711  case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
5712  case ISD::TargetFrameIndex: return "TargetFrameIndex";
5713  case ISD::TargetJumpTable:  return "TargetJumpTable";
5714  case ISD::TargetConstantPool:  return "TargetConstantPool";
5715  case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
5716  case ISD::TargetBlockAddress: return "TargetBlockAddress";
5717
5718  case ISD::CopyToReg:     return "CopyToReg";
5719  case ISD::CopyFromReg:   return "CopyFromReg";
5720  case ISD::UNDEF:         return "undef";
5721  case ISD::MERGE_VALUES:  return "merge_values";
5722  case ISD::INLINEASM:     return "inlineasm";
5723  case ISD::EH_LABEL:      return "eh_label";
5724  case ISD::HANDLENODE:    return "handlenode";
5725
5726  // Unary operators
5727  case ISD::FABS:   return "fabs";
5728  case ISD::FNEG:   return "fneg";
5729  case ISD::FSQRT:  return "fsqrt";
5730  case ISD::FSIN:   return "fsin";
5731  case ISD::FCOS:   return "fcos";
5732  case ISD::FTRUNC: return "ftrunc";
5733  case ISD::FFLOOR: return "ffloor";
5734  case ISD::FCEIL:  return "fceil";
5735  case ISD::FRINT:  return "frint";
5736  case ISD::FNEARBYINT: return "fnearbyint";
5737  case ISD::FEXP:   return "fexp";
5738  case ISD::FEXP2:  return "fexp2";
5739  case ISD::FLOG:   return "flog";
5740  case ISD::FLOG2:  return "flog2";
5741  case ISD::FLOG10: return "flog10";
5742
5743  // Binary operators
5744  case ISD::ADD:    return "add";
5745  case ISD::SUB:    return "sub";
5746  case ISD::MUL:    return "mul";
5747  case ISD::MULHU:  return "mulhu";
5748  case ISD::MULHS:  return "mulhs";
5749  case ISD::SDIV:   return "sdiv";
5750  case ISD::UDIV:   return "udiv";
5751  case ISD::SREM:   return "srem";
5752  case ISD::UREM:   return "urem";
5753  case ISD::SMUL_LOHI:  return "smul_lohi";
5754  case ISD::UMUL_LOHI:  return "umul_lohi";
5755  case ISD::SDIVREM:    return "sdivrem";
5756  case ISD::UDIVREM:    return "udivrem";
5757  case ISD::AND:    return "and";
5758  case ISD::OR:     return "or";
5759  case ISD::XOR:    return "xor";
5760  case ISD::SHL:    return "shl";
5761  case ISD::SRA:    return "sra";
5762  case ISD::SRL:    return "srl";
5763  case ISD::ROTL:   return "rotl";
5764  case ISD::ROTR:   return "rotr";
5765  case ISD::FADD:   return "fadd";
5766  case ISD::FSUB:   return "fsub";
5767  case ISD::FMUL:   return "fmul";
5768  case ISD::FDIV:   return "fdiv";
5769  case ISD::FREM:   return "frem";
5770  case ISD::FCOPYSIGN: return "fcopysign";
5771  case ISD::FGETSIGN:  return "fgetsign";
5772  case ISD::FPOW:   return "fpow";
5773
5774  case ISD::FPOWI:  return "fpowi";
5775  case ISD::SETCC:       return "setcc";
5776  case ISD::VSETCC:      return "vsetcc";
5777  case ISD::SELECT:      return "select";
5778  case ISD::SELECT_CC:   return "select_cc";
5779  case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
5780  case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
5781  case ISD::CONCAT_VECTORS:      return "concat_vectors";
5782  case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
5783  case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
5784  case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
5785  case ISD::CARRY_FALSE:         return "carry_false";
5786  case ISD::ADDC:        return "addc";
5787  case ISD::ADDE:        return "adde";
5788  case ISD::SADDO:       return "saddo";
5789  case ISD::UADDO:       return "uaddo";
5790  case ISD::SSUBO:       return "ssubo";
5791  case ISD::USUBO:       return "usubo";
5792  case ISD::SMULO:       return "smulo";
5793  case ISD::UMULO:       return "umulo";
5794  case ISD::SUBC:        return "subc";
5795  case ISD::SUBE:        return "sube";
5796  case ISD::SHL_PARTS:   return "shl_parts";
5797  case ISD::SRA_PARTS:   return "sra_parts";
5798  case ISD::SRL_PARTS:   return "srl_parts";
5799
5800  // Conversion operators.
5801  case ISD::SIGN_EXTEND: return "sign_extend";
5802  case ISD::ZERO_EXTEND: return "zero_extend";
5803  case ISD::ANY_EXTEND:  return "any_extend";
5804  case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
5805  case ISD::TRUNCATE:    return "truncate";
5806  case ISD::FP_ROUND:    return "fp_round";
5807  case ISD::FLT_ROUNDS_: return "flt_rounds";
5808  case ISD::FP_ROUND_INREG: return "fp_round_inreg";
5809  case ISD::FP_EXTEND:   return "fp_extend";
5810
5811  case ISD::SINT_TO_FP:  return "sint_to_fp";
5812  case ISD::UINT_TO_FP:  return "uint_to_fp";
5813  case ISD::FP_TO_SINT:  return "fp_to_sint";
5814  case ISD::FP_TO_UINT:  return "fp_to_uint";
5815  case ISD::BITCAST:     return "bit_convert";
5816  case ISD::FP16_TO_FP32: return "fp16_to_fp32";
5817  case ISD::FP32_TO_FP16: return "fp32_to_fp16";
5818
5819  case ISD::CONVERT_RNDSAT: {
5820    switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
5821    default: llvm_unreachable("Unknown cvt code!");
5822    case ISD::CVT_FF:  return "cvt_ff";
5823    case ISD::CVT_FS:  return "cvt_fs";
5824    case ISD::CVT_FU:  return "cvt_fu";
5825    case ISD::CVT_SF:  return "cvt_sf";
5826    case ISD::CVT_UF:  return "cvt_uf";
5827    case ISD::CVT_SS:  return "cvt_ss";
5828    case ISD::CVT_SU:  return "cvt_su";
5829    case ISD::CVT_US:  return "cvt_us";
5830    case ISD::CVT_UU:  return "cvt_uu";
5831    }
5832  }
5833
5834    // Control flow instructions
5835  case ISD::BR:      return "br";
5836  case ISD::BRIND:   return "brind";
5837  case ISD::BR_JT:   return "br_jt";
5838  case ISD::BRCOND:  return "brcond";
5839  case ISD::BR_CC:   return "br_cc";
5840  case ISD::CALLSEQ_START:  return "callseq_start";
5841  case ISD::CALLSEQ_END:    return "callseq_end";
5842
5843    // Other operators
5844  case ISD::LOAD:               return "load";
5845  case ISD::STORE:              return "store";
5846  case ISD::VAARG:              return "vaarg";
5847  case ISD::VACOPY:             return "vacopy";
5848  case ISD::VAEND:              return "vaend";
5849  case ISD::VASTART:            return "vastart";
5850  case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
5851  case ISD::EXTRACT_ELEMENT:    return "extract_element";
5852  case ISD::BUILD_PAIR:         return "build_pair";
5853  case ISD::STACKSAVE:          return "stacksave";
5854  case ISD::STACKRESTORE:       return "stackrestore";
5855  case ISD::TRAP:               return "trap";
5856
5857  // Bit manipulation
5858  case ISD::BSWAP:   return "bswap";
5859  case ISD::CTPOP:   return "ctpop";
5860  case ISD::CTTZ:    return "cttz";
5861  case ISD::CTLZ:    return "ctlz";
5862
5863  // Trampolines
5864  case ISD::TRAMPOLINE: return "trampoline";
5865
5866  case ISD::CONDCODE:
5867    switch (cast<CondCodeSDNode>(this)->get()) {
5868    default: llvm_unreachable("Unknown setcc condition!");
5869    case ISD::SETOEQ:  return "setoeq";
5870    case ISD::SETOGT:  return "setogt";
5871    case ISD::SETOGE:  return "setoge";
5872    case ISD::SETOLT:  return "setolt";
5873    case ISD::SETOLE:  return "setole";
5874    case ISD::SETONE:  return "setone";
5875
5876    case ISD::SETO:    return "seto";
5877    case ISD::SETUO:   return "setuo";
5878    case ISD::SETUEQ:  return "setue";
5879    case ISD::SETUGT:  return "setugt";
5880    case ISD::SETUGE:  return "setuge";
5881    case ISD::SETULT:  return "setult";
5882    case ISD::SETULE:  return "setule";
5883    case ISD::SETUNE:  return "setune";
5884
5885    case ISD::SETEQ:   return "seteq";
5886    case ISD::SETGT:   return "setgt";
5887    case ISD::SETGE:   return "setge";
5888    case ISD::SETLT:   return "setlt";
5889    case ISD::SETLE:   return "setle";
5890    case ISD::SETNE:   return "setne";
5891    }
5892  }
5893}
5894
5895const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
5896  switch (AM) {
5897  default:
5898    return "";
5899  case ISD::PRE_INC:
5900    return "<pre-inc>";
5901  case ISD::PRE_DEC:
5902    return "<pre-dec>";
5903  case ISD::POST_INC:
5904    return "<post-inc>";
5905  case ISD::POST_DEC:
5906    return "<post-dec>";
5907  }
5908}
5909
5910std::string ISD::ArgFlagsTy::getArgFlagsString() {
5911  std::string S = "< ";
5912
5913  if (isZExt())
5914    S += "zext ";
5915  if (isSExt())
5916    S += "sext ";
5917  if (isInReg())
5918    S += "inreg ";
5919  if (isSRet())
5920    S += "sret ";
5921  if (isByVal())
5922    S += "byval ";
5923  if (isNest())
5924    S += "nest ";
5925  if (getByValAlign())
5926    S += "byval-align:" + utostr(getByValAlign()) + " ";
5927  if (getOrigAlign())
5928    S += "orig-align:" + utostr(getOrigAlign()) + " ";
5929  if (getByValSize())
5930    S += "byval-size:" + utostr(getByValSize()) + " ";
5931  return S + ">";
5932}
5933
5934void SDNode::dump() const { dump(0); }
5935void SDNode::dump(const SelectionDAG *G) const {
5936  print(dbgs(), G);
5937  dbgs() << '\n';
5938}
5939
5940void SDNode::print_types(raw_ostream &OS, const SelectionDAG *G) const {
5941  OS << (void*)this << ": ";
5942
5943  for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
5944    if (i) OS << ",";
5945    if (getValueType(i) == MVT::Other)
5946      OS << "ch";
5947    else
5948      OS << getValueType(i).getEVTString();
5949  }
5950  OS << " = " << getOperationName(G);
5951}
5952
5953void SDNode::print_details(raw_ostream &OS, const SelectionDAG *G) const {
5954  if (const MachineSDNode *MN = dyn_cast<MachineSDNode>(this)) {
5955    if (!MN->memoperands_empty()) {
5956      OS << "<";
5957      OS << "Mem:";
5958      for (MachineSDNode::mmo_iterator i = MN->memoperands_begin(),
5959           e = MN->memoperands_end(); i != e; ++i) {
5960        OS << **i;
5961        if (llvm::next(i) != e)
5962          OS << " ";
5963      }
5964      OS << ">";
5965    }
5966  } else if (const ShuffleVectorSDNode *SVN =
5967               dyn_cast<ShuffleVectorSDNode>(this)) {
5968    OS << "<";
5969    for (unsigned i = 0, e = ValueList[0].getVectorNumElements(); i != e; ++i) {
5970      int Idx = SVN->getMaskElt(i);
5971      if (i) OS << ",";
5972      if (Idx < 0)
5973        OS << "u";
5974      else
5975        OS << Idx;
5976    }
5977    OS << ">";
5978  } else if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
5979    OS << '<' << CSDN->getAPIntValue() << '>';
5980  } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
5981    if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
5982      OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
5983    else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
5984      OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
5985    else {
5986      OS << "<APFloat(";
5987      CSDN->getValueAPF().bitcastToAPInt().dump();
5988      OS << ")>";
5989    }
5990  } else if (const GlobalAddressSDNode *GADN =
5991             dyn_cast<GlobalAddressSDNode>(this)) {
5992    int64_t offset = GADN->getOffset();
5993    OS << '<';
5994    WriteAsOperand(OS, GADN->getGlobal());
5995    OS << '>';
5996    if (offset > 0)
5997      OS << " + " << offset;
5998    else
5999      OS << " " << offset;
6000    if (unsigned int TF = GADN->getTargetFlags())
6001      OS << " [TF=" << TF << ']';
6002  } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
6003    OS << "<" << FIDN->getIndex() << ">";
6004  } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
6005    OS << "<" << JTDN->getIndex() << ">";
6006    if (unsigned int TF = JTDN->getTargetFlags())
6007      OS << " [TF=" << TF << ']';
6008  } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
6009    int offset = CP->getOffset();
6010    if (CP->isMachineConstantPoolEntry())
6011      OS << "<" << *CP->getMachineCPVal() << ">";
6012    else
6013      OS << "<" << *CP->getConstVal() << ">";
6014    if (offset > 0)
6015      OS << " + " << offset;
6016    else
6017      OS << " " << offset;
6018    if (unsigned int TF = CP->getTargetFlags())
6019      OS << " [TF=" << TF << ']';
6020  } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
6021    OS << "<";
6022    const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
6023    if (LBB)
6024      OS << LBB->getName() << " ";
6025    OS << (const void*)BBDN->getBasicBlock() << ">";
6026  } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
6027    if (G && R->getReg() &&
6028        TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
6029      OS << " %" << G->getTarget().getRegisterInfo()->getName(R->getReg());
6030    } else {
6031      OS << " %reg" << R->getReg();
6032    }
6033  } else if (const ExternalSymbolSDNode *ES =
6034             dyn_cast<ExternalSymbolSDNode>(this)) {
6035    OS << "'" << ES->getSymbol() << "'";
6036    if (unsigned int TF = ES->getTargetFlags())
6037      OS << " [TF=" << TF << ']';
6038  } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
6039    if (M->getValue())
6040      OS << "<" << M->getValue() << ">";
6041    else
6042      OS << "<null>";
6043  } else if (const MDNodeSDNode *MD = dyn_cast<MDNodeSDNode>(this)) {
6044    if (MD->getMD())
6045      OS << "<" << MD->getMD() << ">";
6046    else
6047      OS << "<null>";
6048  } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
6049    OS << ":" << N->getVT().getEVTString();
6050  }
6051  else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
6052    OS << "<" << *LD->getMemOperand();
6053
6054    bool doExt = true;
6055    switch (LD->getExtensionType()) {
6056    default: doExt = false; break;
6057    case ISD::EXTLOAD: OS << ", anyext"; break;
6058    case ISD::SEXTLOAD: OS << ", sext"; break;
6059    case ISD::ZEXTLOAD: OS << ", zext"; break;
6060    }
6061    if (doExt)
6062      OS << " from " << LD->getMemoryVT().getEVTString();
6063
6064    const char *AM = getIndexedModeName(LD->getAddressingMode());
6065    if (*AM)
6066      OS << ", " << AM;
6067
6068    OS << ">";
6069  } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
6070    OS << "<" << *ST->getMemOperand();
6071
6072    if (ST->isTruncatingStore())
6073      OS << ", trunc to " << ST->getMemoryVT().getEVTString();
6074
6075    const char *AM = getIndexedModeName(ST->getAddressingMode());
6076    if (*AM)
6077      OS << ", " << AM;
6078
6079    OS << ">";
6080  } else if (const MemSDNode* M = dyn_cast<MemSDNode>(this)) {
6081    OS << "<" << *M->getMemOperand() << ">";
6082  } else if (const BlockAddressSDNode *BA =
6083               dyn_cast<BlockAddressSDNode>(this)) {
6084    OS << "<";
6085    WriteAsOperand(OS, BA->getBlockAddress()->getFunction(), false);
6086    OS << ", ";
6087    WriteAsOperand(OS, BA->getBlockAddress()->getBasicBlock(), false);
6088    OS << ">";
6089    if (unsigned int TF = BA->getTargetFlags())
6090      OS << " [TF=" << TF << ']';
6091  }
6092
6093  if (G)
6094    if (unsigned Order = G->GetOrdering(this))
6095      OS << " [ORD=" << Order << ']';
6096
6097  if (getNodeId() != -1)
6098    OS << " [ID=" << getNodeId() << ']';
6099
6100  DebugLoc dl = getDebugLoc();
6101  if (G && !dl.isUnknown()) {
6102    DIScope
6103      Scope(dl.getScope(G->getMachineFunction().getFunction()->getContext()));
6104    OS << " dbg:";
6105    // Omit the directory, since it's usually long and uninteresting.
6106    if (Scope.Verify())
6107      OS << Scope.getFilename();
6108    else
6109      OS << "<unknown>";
6110    OS << ':' << dl.getLine();
6111    if (dl.getCol() != 0)
6112      OS << ':' << dl.getCol();
6113  }
6114}
6115
6116void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
6117  print_types(OS, G);
6118  for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
6119    if (i) OS << ", "; else OS << " ";
6120    OS << (void*)getOperand(i).getNode();
6121    if (unsigned RN = getOperand(i).getResNo())
6122      OS << ":" << RN;
6123  }
6124  print_details(OS, G);
6125}
6126
6127static void printrWithDepthHelper(raw_ostream &OS, const SDNode *N,
6128                                  const SelectionDAG *G, unsigned depth,
6129                                  unsigned indent)
6130{
6131  if (depth == 0)
6132    return;
6133
6134  OS.indent(indent);
6135
6136  N->print(OS, G);
6137
6138  if (depth < 1)
6139    return;
6140
6141  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6142    OS << '\n';
6143    printrWithDepthHelper(OS, N->getOperand(i).getNode(), G, depth-1, indent+2);
6144  }
6145}
6146
6147void SDNode::printrWithDepth(raw_ostream &OS, const SelectionDAG *G,
6148                            unsigned depth) const {
6149  printrWithDepthHelper(OS, this, G, depth, 0);
6150}
6151
6152void SDNode::printrFull(raw_ostream &OS, const SelectionDAG *G) const {
6153  // Don't print impossibly deep things.
6154  printrWithDepth(OS, G, 100);
6155}
6156
6157void SDNode::dumprWithDepth(const SelectionDAG *G, unsigned depth) const {
6158  printrWithDepth(dbgs(), G, depth);
6159}
6160
6161void SDNode::dumprFull(const SelectionDAG *G) const {
6162  // Don't print impossibly deep things.
6163  dumprWithDepth(G, 100);
6164}
6165
6166static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
6167  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6168    if (N->getOperand(i).getNode()->hasOneUse())
6169      DumpNodes(N->getOperand(i).getNode(), indent+2, G);
6170    else
6171      dbgs() << "\n" << std::string(indent+2, ' ')
6172           << (void*)N->getOperand(i).getNode() << ": <multiple use>";
6173
6174
6175  dbgs() << "\n";
6176  dbgs().indent(indent);
6177  N->dump(G);
6178}
6179
6180SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
6181  assert(N->getNumValues() == 1 &&
6182         "Can't unroll a vector with multiple results!");
6183
6184  EVT VT = N->getValueType(0);
6185  unsigned NE = VT.getVectorNumElements();
6186  EVT EltVT = VT.getVectorElementType();
6187  DebugLoc dl = N->getDebugLoc();
6188
6189  SmallVector<SDValue, 8> Scalars;
6190  SmallVector<SDValue, 4> Operands(N->getNumOperands());
6191
6192  // If ResNE is 0, fully unroll the vector op.
6193  if (ResNE == 0)
6194    ResNE = NE;
6195  else if (NE > ResNE)
6196    NE = ResNE;
6197
6198  unsigned i;
6199  for (i= 0; i != NE; ++i) {
6200    for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
6201      SDValue Operand = N->getOperand(j);
6202      EVT OperandVT = Operand.getValueType();
6203      if (OperandVT.isVector()) {
6204        // A vector operand; extract a single element.
6205        EVT OperandEltVT = OperandVT.getVectorElementType();
6206        Operands[j] = getNode(ISD::EXTRACT_VECTOR_ELT, dl,
6207                              OperandEltVT,
6208                              Operand,
6209                              getConstant(i, MVT::i32));
6210      } else {
6211        // A scalar operand; just use it as is.
6212        Operands[j] = Operand;
6213      }
6214    }
6215
6216    switch (N->getOpcode()) {
6217    default:
6218      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6219                                &Operands[0], Operands.size()));
6220      break;
6221    case ISD::SHL:
6222    case ISD::SRA:
6223    case ISD::SRL:
6224    case ISD::ROTL:
6225    case ISD::ROTR:
6226      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
6227                                getShiftAmountOperand(Operands[1])));
6228      break;
6229    case ISD::SIGN_EXTEND_INREG:
6230    case ISD::FP_ROUND_INREG: {
6231      EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
6232      Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
6233                                Operands[0],
6234                                getValueType(ExtVT)));
6235    }
6236    }
6237  }
6238
6239  for (; i < ResNE; ++i)
6240    Scalars.push_back(getUNDEF(EltVT));
6241
6242  return getNode(ISD::BUILD_VECTOR, dl,
6243                 EVT::getVectorVT(*getContext(), EltVT, ResNE),
6244                 &Scalars[0], Scalars.size());
6245}
6246
6247
6248/// isConsecutiveLoad - Return true if LD is loading 'Bytes' bytes from a
6249/// location that is 'Dist' units away from the location that the 'Base' load
6250/// is loading from.
6251bool SelectionDAG::isConsecutiveLoad(LoadSDNode *LD, LoadSDNode *Base,
6252                                     unsigned Bytes, int Dist) const {
6253  if (LD->getChain() != Base->getChain())
6254    return false;
6255  EVT VT = LD->getValueType(0);
6256  if (VT.getSizeInBits() / 8 != Bytes)
6257    return false;
6258
6259  SDValue Loc = LD->getOperand(1);
6260  SDValue BaseLoc = Base->getOperand(1);
6261  if (Loc.getOpcode() == ISD::FrameIndex) {
6262    if (BaseLoc.getOpcode() != ISD::FrameIndex)
6263      return false;
6264    const MachineFrameInfo *MFI = getMachineFunction().getFrameInfo();
6265    int FI  = cast<FrameIndexSDNode>(Loc)->getIndex();
6266    int BFI = cast<FrameIndexSDNode>(BaseLoc)->getIndex();
6267    int FS  = MFI->getObjectSize(FI);
6268    int BFS = MFI->getObjectSize(BFI);
6269    if (FS != BFS || FS != (int)Bytes) return false;
6270    return MFI->getObjectOffset(FI) == (MFI->getObjectOffset(BFI) + Dist*Bytes);
6271  }
6272  if (Loc.getOpcode() == ISD::ADD && Loc.getOperand(0) == BaseLoc) {
6273    ConstantSDNode *V = dyn_cast<ConstantSDNode>(Loc.getOperand(1));
6274    if (V && (V->getSExtValue() == Dist*Bytes))
6275      return true;
6276  }
6277
6278  const GlobalValue *GV1 = NULL;
6279  const GlobalValue *GV2 = NULL;
6280  int64_t Offset1 = 0;
6281  int64_t Offset2 = 0;
6282  bool isGA1 = TLI.isGAPlusOffset(Loc.getNode(), GV1, Offset1);
6283  bool isGA2 = TLI.isGAPlusOffset(BaseLoc.getNode(), GV2, Offset2);
6284  if (isGA1 && isGA2 && GV1 == GV2)
6285    return Offset1 == (Offset2 + Dist*Bytes);
6286  return false;
6287}
6288
6289
6290/// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
6291/// it cannot be inferred.
6292unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
6293  // If this is a GlobalAddress + cst, return the alignment.
6294  const GlobalValue *GV;
6295  int64_t GVOffset = 0;
6296  if (TLI.isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
6297    // If GV has specified alignment, then use it. Otherwise, use the preferred
6298    // alignment.
6299    unsigned Align = GV->getAlignment();
6300    if (!Align) {
6301      if (const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV)) {
6302        if (GVar->hasInitializer()) {
6303          const TargetData *TD = TLI.getTargetData();
6304          Align = TD->getPreferredAlignment(GVar);
6305        }
6306      }
6307    }
6308    return MinAlign(Align, GVOffset);
6309  }
6310
6311  // If this is a direct reference to a stack slot, use information about the
6312  // stack slot's alignment.
6313  int FrameIdx = 1 << 31;
6314  int64_t FrameOffset = 0;
6315  if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
6316    FrameIdx = FI->getIndex();
6317  } else if (Ptr.getOpcode() == ISD::ADD &&
6318             isa<ConstantSDNode>(Ptr.getOperand(1)) &&
6319             isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
6320    FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
6321    FrameOffset = Ptr.getConstantOperandVal(1);
6322  }
6323
6324  if (FrameIdx != (1 << 31)) {
6325    // FIXME: Handle FI+CST.
6326    const MachineFrameInfo &MFI = *getMachineFunction().getFrameInfo();
6327    unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
6328                                    FrameOffset);
6329    return FIInfoAlign;
6330  }
6331
6332  return 0;
6333}
6334
6335void SelectionDAG::dump() const {
6336  dbgs() << "SelectionDAG has " << AllNodes.size() << " nodes:";
6337
6338  for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
6339       I != E; ++I) {
6340    const SDNode *N = I;
6341    if (!N->hasOneUse() && N != getRoot().getNode())
6342      DumpNodes(N, 2, this);
6343  }
6344
6345  if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
6346
6347  dbgs() << "\n\n";
6348}
6349
6350void SDNode::printr(raw_ostream &OS, const SelectionDAG *G) const {
6351  print_types(OS, G);
6352  print_details(OS, G);
6353}
6354
6355typedef SmallPtrSet<const SDNode *, 128> VisitedSDNodeSet;
6356static void DumpNodesr(raw_ostream &OS, const SDNode *N, unsigned indent,
6357                       const SelectionDAG *G, VisitedSDNodeSet &once) {
6358  if (!once.insert(N))          // If we've been here before, return now.
6359    return;
6360
6361  // Dump the current SDNode, but don't end the line yet.
6362  OS << std::string(indent, ' ');
6363  N->printr(OS, G);
6364
6365  // Having printed this SDNode, walk the children:
6366  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6367    const SDNode *child = N->getOperand(i).getNode();
6368
6369    if (i) OS << ",";
6370    OS << " ";
6371
6372    if (child->getNumOperands() == 0) {
6373      // This child has no grandchildren; print it inline right here.
6374      child->printr(OS, G);
6375      once.insert(child);
6376    } else {         // Just the address. FIXME: also print the child's opcode.
6377      OS << (void*)child;
6378      if (unsigned RN = N->getOperand(i).getResNo())
6379        OS << ":" << RN;
6380    }
6381  }
6382
6383  OS << "\n";
6384
6385  // Dump children that have grandchildren on their own line(s).
6386  for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
6387    const SDNode *child = N->getOperand(i).getNode();
6388    DumpNodesr(OS, child, indent+2, G, once);
6389  }
6390}
6391
6392void SDNode::dumpr() const {
6393  VisitedSDNodeSet once;
6394  DumpNodesr(dbgs(), this, 0, 0, once);
6395}
6396
6397void SDNode::dumpr(const SelectionDAG *G) const {
6398  VisitedSDNodeSet once;
6399  DumpNodesr(dbgs(), this, 0, G, once);
6400}
6401
6402
6403// getAddressSpace - Return the address space this GlobalAddress belongs to.
6404unsigned GlobalAddressSDNode::getAddressSpace() const {
6405  return getGlobal()->getType()->getAddressSpace();
6406}
6407
6408
6409const Type *ConstantPoolSDNode::getType() const {
6410  if (isMachineConstantPoolEntry())
6411    return Val.MachineCPVal->getType();
6412  return Val.ConstVal->getType();
6413}
6414
6415bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue,
6416                                        APInt &SplatUndef,
6417                                        unsigned &SplatBitSize,
6418                                        bool &HasAnyUndefs,
6419                                        unsigned MinSplatBits,
6420                                        bool isBigEndian) {
6421  EVT VT = getValueType(0);
6422  assert(VT.isVector() && "Expected a vector type");
6423  unsigned sz = VT.getSizeInBits();
6424  if (MinSplatBits > sz)
6425    return false;
6426
6427  SplatValue = APInt(sz, 0);
6428  SplatUndef = APInt(sz, 0);
6429
6430  // Get the bits.  Bits with undefined values (when the corresponding element
6431  // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
6432  // in SplatValue.  If any of the values are not constant, give up and return
6433  // false.
6434  unsigned int nOps = getNumOperands();
6435  assert(nOps > 0 && "isConstantSplat has 0-size build vector");
6436  unsigned EltBitSize = VT.getVectorElementType().getSizeInBits();
6437
6438  for (unsigned j = 0; j < nOps; ++j) {
6439    unsigned i = isBigEndian ? nOps-1-j : j;
6440    SDValue OpVal = getOperand(i);
6441    unsigned BitPos = j * EltBitSize;
6442
6443    if (OpVal.getOpcode() == ISD::UNDEF)
6444      SplatUndef |= APInt::getBitsSet(sz, BitPos, BitPos + EltBitSize);
6445    else if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(OpVal))
6446      SplatValue |= CN->getAPIntValue().zextOrTrunc(EltBitSize).
6447                    zextOrTrunc(sz) << BitPos;
6448    else if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(OpVal))
6449      SplatValue |= CN->getValueAPF().bitcastToAPInt().zextOrTrunc(sz) <<BitPos;
6450     else
6451      return false;
6452  }
6453
6454  // The build_vector is all constants or undefs.  Find the smallest element
6455  // size that splats the vector.
6456
6457  HasAnyUndefs = (SplatUndef != 0);
6458  while (sz > 8) {
6459
6460    unsigned HalfSize = sz / 2;
6461    APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
6462    APInt LowValue = SplatValue.trunc(HalfSize);
6463    APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
6464    APInt LowUndef = SplatUndef.trunc(HalfSize);
6465
6466    // If the two halves do not match (ignoring undef bits), stop here.
6467    if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
6468        MinSplatBits > HalfSize)
6469      break;
6470
6471    SplatValue = HighValue | LowValue;
6472    SplatUndef = HighUndef & LowUndef;
6473
6474    sz = HalfSize;
6475  }
6476
6477  SplatBitSize = sz;
6478  return true;
6479}
6480
6481bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
6482  // Find the first non-undef value in the shuffle mask.
6483  unsigned i, e;
6484  for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
6485    /* search */;
6486
6487  assert(i != e && "VECTOR_SHUFFLE node with all undef indices!");
6488
6489  // Make sure all remaining elements are either undef or the same as the first
6490  // non-undef value.
6491  for (int Idx = Mask[i]; i != e; ++i)
6492    if (Mask[i] >= 0 && Mask[i] != Idx)
6493      return false;
6494  return true;
6495}
6496
6497#ifdef XDEBUG
6498static void checkForCyclesHelper(const SDNode *N,
6499                                 SmallPtrSet<const SDNode*, 32> &Visited,
6500                                 SmallPtrSet<const SDNode*, 32> &Checked) {
6501  // If this node has already been checked, don't check it again.
6502  if (Checked.count(N))
6503    return;
6504
6505  // If a node has already been visited on this depth-first walk, reject it as
6506  // a cycle.
6507  if (!Visited.insert(N)) {
6508    dbgs() << "Offending node:\n";
6509    N->dumprFull();
6510    errs() << "Detected cycle in SelectionDAG\n";
6511    abort();
6512  }
6513
6514  for(unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
6515    checkForCyclesHelper(N->getOperand(i).getNode(), Visited, Checked);
6516
6517  Checked.insert(N);
6518  Visited.erase(N);
6519}
6520#endif
6521
6522void llvm::checkForCycles(const llvm::SDNode *N) {
6523#ifdef XDEBUG
6524  assert(N && "Checking nonexistant SDNode");
6525  SmallPtrSet<const SDNode*, 32> visited;
6526  SmallPtrSet<const SDNode*, 32> checked;
6527  checkForCyclesHelper(N, visited, checked);
6528#endif
6529}
6530
6531void llvm::checkForCycles(const llvm::SelectionDAG *DAG) {
6532  checkForCycles(DAG->getRoot().getNode());
6533}
6534