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