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