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