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