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