LLVM API Documentation

SelectionDAG.cpp

Go to the documentation of this file.
00001 //===-- SelectionDAG.cpp - Implement the SelectionDAG data structures -----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This implements the SelectionDAG class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 #include "llvm/CodeGen/SelectionDAG.h"
00014 #include "llvm/Constants.h"
00015 #include "llvm/Analysis/ValueTracking.h"
00016 #include "llvm/GlobalAlias.h"
00017 #include "llvm/GlobalVariable.h"
00018 #include "llvm/Intrinsics.h"
00019 #include "llvm/DerivedTypes.h"
00020 #include "llvm/Assembly/Writer.h"
00021 #include "llvm/CallingConv.h"
00022 #include "llvm/CodeGen/MachineBasicBlock.h"
00023 #include "llvm/CodeGen/MachineConstantPool.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineModuleInfo.h"
00026 #include "llvm/CodeGen/PseudoSourceValue.h"
00027 #include "llvm/Target/TargetRegisterInfo.h"
00028 #include "llvm/Target/TargetData.h"
00029 #include "llvm/Target/TargetLowering.h"
00030 #include "llvm/Target/TargetOptions.h"
00031 #include "llvm/Target/TargetInstrInfo.h"
00032 #include "llvm/Target/TargetMachine.h"
00033 #include "llvm/Support/CommandLine.h"
00034 #include "llvm/Support/MathExtras.h"
00035 #include "llvm/Support/raw_ostream.h"
00036 #include "llvm/ADT/SetVector.h"
00037 #include "llvm/ADT/SmallPtrSet.h"
00038 #include "llvm/ADT/SmallSet.h"
00039 #include "llvm/ADT/SmallVector.h"
00040 #include "llvm/ADT/StringExtras.h"
00041 #include <algorithm>
00042 #include <cmath>
00043 using namespace llvm;
00044 
00045 /// makeVTList - Return an instance of the SDVTList struct initialized with the
00046 /// specified members.
00047 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
00048   SDVTList Res = {VTs, NumVTs};
00049   return Res;
00050 }
00051 
00052 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
00053   switch (VT.getSimpleVT()) {
00054   default: assert(0 && "Unknown FP format");
00055   case MVT::f32:     return &APFloat::IEEEsingle;
00056   case MVT::f64:     return &APFloat::IEEEdouble;
00057   case MVT::f80:     return &APFloat::x87DoubleExtended;
00058   case MVT::f128:    return &APFloat::IEEEquad;
00059   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
00060   }
00061 }
00062 
00063 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
00064 
00065 //===----------------------------------------------------------------------===//
00066 //                              ConstantFPSDNode Class
00067 //===----------------------------------------------------------------------===//
00068 
00069 /// isExactlyValue - We don't rely on operator== working on double values, as
00070 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
00071 /// As such, this method can be used to do an exact bit-for-bit comparison of
00072 /// two floating point values.
00073 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
00074   return getValueAPF().bitwiseIsEqual(V);
00075 }
00076 
00077 bool ConstantFPSDNode::isValueValidForType(MVT VT,
00078                                            const APFloat& Val) {
00079   assert(VT.isFloatingPoint() && "Can only convert between FP types");
00080   
00081   // PPC long double cannot be converted to any other type.
00082   if (VT == MVT::ppcf128 ||
00083       &Val.getSemantics() == &APFloat::PPCDoubleDouble)
00084     return false;
00085   
00086   // convert modifies in place, so make a copy.
00087   APFloat Val2 = APFloat(Val);
00088   bool losesInfo;
00089   (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
00090                       &losesInfo);
00091   return !losesInfo;
00092 }
00093 
00094 //===----------------------------------------------------------------------===//
00095 //                              ISD Namespace
00096 //===----------------------------------------------------------------------===//
00097 
00098 /// isBuildVectorAllOnes - Return true if the specified node is a
00099 /// BUILD_VECTOR where all of the elements are ~0 or undef.
00100 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
00101   // Look through a bit convert.
00102   if (N->getOpcode() == ISD::BIT_CONVERT)
00103     N = N->getOperand(0).getNode();
00104   
00105   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00106   
00107   unsigned i = 0, e = N->getNumOperands();
00108   
00109   // Skip over all of the undef values.
00110   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00111     ++i;
00112   
00113   // Do not accept an all-undef vector.
00114   if (i == e) return false;
00115   
00116   // Do not accept build_vectors that aren't all constants or which have non-~0
00117   // elements.
00118   SDValue NotZero = N->getOperand(i);
00119   if (isa<ConstantSDNode>(NotZero)) {
00120     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
00121       return false;
00122   } else if (isa<ConstantFPSDNode>(NotZero)) {
00123     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
00124                 bitcastToAPInt().isAllOnesValue())
00125       return false;
00126   } else
00127     return false;
00128   
00129   // Okay, we have at least one ~0 value, check to see if the rest match or are
00130   // undefs.
00131   for (++i; i != e; ++i)
00132     if (N->getOperand(i) != NotZero &&
00133         N->getOperand(i).getOpcode() != ISD::UNDEF)
00134       return false;
00135   return true;
00136 }
00137 
00138 
00139 /// isBuildVectorAllZeros - Return true if the specified node is a
00140 /// BUILD_VECTOR where all of the elements are 0 or undef.
00141 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
00142   // Look through a bit convert.
00143   if (N->getOpcode() == ISD::BIT_CONVERT)
00144     N = N->getOperand(0).getNode();
00145   
00146   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00147   
00148   unsigned i = 0, e = N->getNumOperands();
00149   
00150   // Skip over all of the undef values.
00151   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00152     ++i;
00153   
00154   // Do not accept an all-undef vector.
00155   if (i == e) return false;
00156   
00157   // Do not accept build_vectors that aren't all constants or which have non-~0
00158   // elements.
00159   SDValue Zero = N->getOperand(i);
00160   if (isa<ConstantSDNode>(Zero)) {
00161     if (!cast<ConstantSDNode>(Zero)->isNullValue())
00162       return false;
00163   } else if (isa<ConstantFPSDNode>(Zero)) {
00164     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
00165       return false;
00166   } else
00167     return false;
00168   
00169   // Okay, we have at least one ~0 value, check to see if the rest match or are
00170   // undefs.
00171   for (++i; i != e; ++i)
00172     if (N->getOperand(i) != Zero &&
00173         N->getOperand(i).getOpcode() != ISD::UNDEF)
00174       return false;
00175   return true;
00176 }
00177 
00178 /// isScalarToVector - Return true if the specified node is a
00179 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
00180 /// element is not an undef.
00181 bool ISD::isScalarToVector(const SDNode *N) {
00182   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
00183     return true;
00184 
00185   if (N->getOpcode() != ISD::BUILD_VECTOR)
00186     return false;
00187   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
00188     return false;
00189   unsigned NumElems = N->getNumOperands();
00190   for (unsigned i = 1; i < NumElems; ++i) {
00191     SDValue V = N->getOperand(i);
00192     if (V.getOpcode() != ISD::UNDEF)
00193       return false;
00194   }
00195   return true;
00196 }
00197 
00198 
00199 /// isDebugLabel - Return true if the specified node represents a debug
00200 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
00201 bool ISD::isDebugLabel(const SDNode *N) {
00202   SDValue Zero;
00203   if (N->getOpcode() == ISD::DBG_LABEL)
00204     return true;
00205   if (N->isMachineOpcode() &&
00206       N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
00207     return true;
00208   return false;
00209 }
00210 
00211 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
00212 /// when given the operation for (X op Y).
00213 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
00214   // To perform this operation, we just need to swap the L and G bits of the
00215   // operation.
00216   unsigned OldL = (Operation >> 2) & 1;
00217   unsigned OldG = (Operation >> 1) & 1;
00218   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
00219                        (OldL << 1) |       // New G bit
00220                        (OldG << 2));       // New L bit.
00221 }
00222 
00223 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
00224 /// 'op' is a valid SetCC operation.
00225 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
00226   unsigned Operation = Op;
00227   if (isInteger)
00228     Operation ^= 7;   // Flip L, G, E bits, but not U.
00229   else
00230     Operation ^= 15;  // Flip all of the condition bits.
00231 
00232   if (Operation > ISD::SETTRUE2)
00233     Operation &= ~8;  // Don't let N and U bits get set.
00234 
00235   return ISD::CondCode(Operation);
00236 }
00237 
00238 
00239 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
00240 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
00241 /// if the operation does not depend on the sign of the input (setne and seteq).
00242 static int isSignedOp(ISD::CondCode Opcode) {
00243   switch (Opcode) {
00244   default: assert(0 && "Illegal integer setcc operation!");
00245   case ISD::SETEQ:
00246   case ISD::SETNE: return 0;
00247   case ISD::SETLT:
00248   case ISD::SETLE:
00249   case ISD::SETGT:
00250   case ISD::SETGE: return 1;
00251   case ISD::SETULT:
00252   case ISD::SETULE:
00253   case ISD::SETUGT:
00254   case ISD::SETUGE: return 2;
00255   }
00256 }
00257 
00258 /// getSetCCOrOperation - Return the result of a logical OR between different
00259 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
00260 /// returns SETCC_INVALID if it is not possible to represent the resultant
00261 /// comparison.
00262 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00263                                        bool isInteger) {
00264   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00265     // Cannot fold a signed integer setcc with an unsigned integer setcc.
00266     return ISD::SETCC_INVALID;
00267 
00268   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
00269 
00270   // If the N and U bits get set then the resultant comparison DOES suddenly
00271   // care about orderedness, and is true when ordered.
00272   if (Op > ISD::SETTRUE2)
00273     Op &= ~16;     // Clear the U bit if the N bit is set.
00274   
00275   // Canonicalize illegal integer setcc's.
00276   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
00277     Op = ISD::SETNE;
00278   
00279   return ISD::CondCode(Op);
00280 }
00281 
00282 /// getSetCCAndOperation - Return the result of a logical AND between different
00283 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
00284 /// function returns zero if it is not possible to represent the resultant
00285 /// comparison.
00286 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00287                                         bool isInteger) {
00288   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00289     // Cannot fold a signed setcc with an unsigned setcc.
00290     return ISD::SETCC_INVALID;
00291 
00292   // Combine all of the condition bits.
00293   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
00294   
00295   // Canonicalize illegal integer setcc's.
00296   if (isInteger) {
00297     switch (Result) {
00298     default: break;
00299     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
00300     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
00301     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
00302     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
00303     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
00304     }
00305   }
00306   
00307   return Result;
00308 }
00309 
00310 const TargetMachine &SelectionDAG::getTarget() const {
00311   return MF->getTarget();
00312 }
00313 
00314 //===----------------------------------------------------------------------===//
00315 //                           SDNode Profile Support
00316 //===----------------------------------------------------------------------===//
00317 
00318 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
00319 ///
00320 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
00321   ID.AddInteger(OpC);
00322 }
00323 
00324 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
00325 /// solely with their pointer.
00326 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
00327   ID.AddPointer(VTList.VTs);  
00328 }
00329 
00330 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
00331 ///
00332 static void AddNodeIDOperands(FoldingSetNodeID &ID,
00333                               const SDValue *Ops, unsigned NumOps) {
00334   for (; NumOps; --NumOps, ++Ops) {
00335     ID.AddPointer(Ops->getNode());
00336     ID.AddInteger(Ops->getResNo());
00337   }
00338 }
00339 
00340 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
00341 ///
00342 static void AddNodeIDOperands(FoldingSetNodeID &ID,
00343                               const SDUse *Ops, unsigned NumOps) {
00344   for (; NumOps; --NumOps, ++Ops) {
00345     ID.AddPointer(Ops->getNode());
00346     ID.AddInteger(Ops->getResNo());
00347   }
00348 }
00349 
00350 static void AddNodeIDNode(FoldingSetNodeID &ID,
00351                           unsigned short OpC, SDVTList VTList, 
00352                           const SDValue *OpList, unsigned N) {
00353   AddNodeIDOpcode(ID, OpC);
00354   AddNodeIDValueTypes(ID, VTList);
00355   AddNodeIDOperands(ID, OpList, N);
00356 }
00357 
00358 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
00359 /// the NodeID data.
00360 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
00361   switch (N->getOpcode()) {
00362   default: break;  // Normal nodes don't need extra info.
00363   case ISD::ARG_FLAGS:
00364     ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
00365     break;
00366   case ISD::TargetConstant:
00367   case ISD::Constant:
00368     ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
00369     break;
00370   case ISD::TargetConstantFP:
00371   case ISD::ConstantFP: {
00372     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
00373     break;
00374   }
00375   case ISD::TargetGlobalAddress:
00376   case ISD::GlobalAddress:
00377   case ISD::TargetGlobalTLSAddress:
00378   case ISD::GlobalTLSAddress: {
00379     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
00380     ID.AddPointer(GA->getGlobal());
00381     ID.AddInteger(GA->getOffset());
00382     break;
00383   }
00384   case ISD::BasicBlock:
00385     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
00386     break;
00387   case ISD::Register:
00388     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
00389     break;
00390   case ISD::DBG_STOPPOINT: {
00391     const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
00392     ID.AddInteger(DSP->getLine());
00393     ID.AddInteger(DSP->getColumn());
00394     ID.AddPointer(DSP->getCompileUnit());
00395     break;
00396   }
00397   case ISD::SRCVALUE:
00398     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
00399     break;
00400   case ISD::MEMOPERAND: {
00401     const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
00402     MO.Profile(ID);
00403     break;
00404   }
00405   case ISD::FrameIndex:
00406   case ISD::TargetFrameIndex:
00407     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
00408     break;
00409   case ISD::JumpTable:
00410   case ISD::TargetJumpTable:
00411     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
00412     break;
00413   case ISD::ConstantPool:
00414   case ISD::TargetConstantPool: {
00415     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
00416     ID.AddInteger(CP->getAlignment());
00417     ID.AddInteger(CP->getOffset());
00418     if (CP->isMachineConstantPoolEntry())
00419       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
00420     else
00421       ID.AddPointer(CP->getConstVal());
00422     break;
00423   }
00424   case ISD::CALL: {
00425     const CallSDNode *Call = cast<CallSDNode>(N);
00426     ID.AddInteger(Call->getCallingConv());
00427     ID.AddInteger(Call->isVarArg());
00428     break;
00429   }
00430   case ISD::LOAD: {
00431     const LoadSDNode *LD = cast<LoadSDNode>(N);
00432     ID.AddInteger(LD->getMemoryVT().getRawBits());
00433     ID.AddInteger(LD->getRawSubclassData());
00434     break;
00435   }
00436   case ISD::STORE: {
00437     const StoreSDNode *ST = cast<StoreSDNode>(N);
00438     ID.AddInteger(ST->getMemoryVT().getRawBits());
00439     ID.AddInteger(ST->getRawSubclassData());
00440     break;
00441   }
00442   case ISD::ATOMIC_CMP_SWAP:
00443   case ISD::ATOMIC_SWAP:
00444   case ISD::ATOMIC_LOAD_ADD:
00445   case ISD::ATOMIC_LOAD_SUB:
00446   case ISD::ATOMIC_LOAD_AND:
00447   case ISD::ATOMIC_LOAD_OR:
00448   case ISD::ATOMIC_LOAD_XOR:
00449   case ISD::ATOMIC_LOAD_NAND:
00450   case ISD::ATOMIC_LOAD_MIN:
00451   case ISD::ATOMIC_LOAD_MAX:
00452   case ISD::ATOMIC_LOAD_UMIN:
00453   case ISD::ATOMIC_LOAD_UMAX: {
00454     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
00455     ID.AddInteger(AT->getMemoryVT().getRawBits());
00456     ID.AddInteger(AT->getRawSubclassData());
00457     break;
00458   }
00459   } // end switch (N->getOpcode())
00460 }
00461 
00462 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
00463 /// data.
00464 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
00465   AddNodeIDOpcode(ID, N->getOpcode());
00466   // Add the return value info.
00467   AddNodeIDValueTypes(ID, N->getVTList());
00468   // Add the operand info.
00469   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
00470 
00471   // Handle SDNode leafs with special info.
00472   AddNodeIDCustom(ID, N);
00473 }
00474 
00475 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
00476 /// the CSE map that carries alignment, volatility, indexing mode, and
00477 /// extension/truncation information.
00478 ///
00479 static inline unsigned
00480 encodeMemSDNodeFlags(int ConvType, ISD::MemIndexedMode AM,
00481                      bool isVolatile, unsigned Alignment) {
00482   assert((ConvType & 3) == ConvType &&
00483          "ConvType may not require more than 2 bits!");
00484   assert((AM & 7) == AM &&
00485          "AM may not require more than 3 bits!");
00486   return ConvType |
00487          (AM << 2) |
00488          (isVolatile << 5) |
00489          ((Log2_32(Alignment) + 1) << 6);
00490 }
00491 
00492 //===----------------------------------------------------------------------===//
00493 //                              SelectionDAG Class
00494 //===----------------------------------------------------------------------===//
00495 
00496 /// doNotCSE - Return true if CSE should not be performed for this node.
00497 static bool doNotCSE(SDNode *N) {
00498   if (N->getValueType(0) == MVT::Flag)
00499     return true; // Never CSE anything that produces a flag.
00500 
00501   switch (N->getOpcode()) {
00502   default: break;
00503   case ISD::HANDLENODE:
00504   case ISD::DBG_LABEL:
00505   case ISD::DBG_STOPPOINT:
00506   case ISD::EH_LABEL:
00507   case ISD::DECLARE:
00508     return true;   // Never CSE these nodes.
00509   }
00510 
00511   // Check that remaining values produced are not flags.
00512   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00513     if (N->getValueType(i) == MVT::Flag)
00514       return true; // Never CSE anything that produces a flag.
00515 
00516   return false;
00517 }
00518 
00519 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
00520 /// SelectionDAG.
00521 void SelectionDAG::RemoveDeadNodes() {
00522   // Create a dummy node (which is not added to allnodes), that adds a reference
00523   // to the root node, preventing it from being deleted.
00524   HandleSDNode Dummy(getRoot());
00525 
00526   SmallVector<SDNode*, 128> DeadNodes;
00527   
00528   // Add all obviously-dead nodes to the DeadNodes worklist.
00529   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
00530     if (I->use_empty())
00531       DeadNodes.push_back(I);
00532 
00533   RemoveDeadNodes(DeadNodes);
00534   
00535   // If the root changed (e.g. it was a dead load, update the root).
00536   setRoot(Dummy.getValue());
00537 }
00538 
00539 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
00540 /// given list, and any nodes that become unreachable as a result.
00541 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
00542                                    DAGUpdateListener *UpdateListener) {
00543 
00544   // Process the worklist, deleting the nodes and adding their uses to the
00545   // worklist.
00546   while (!DeadNodes.empty()) {
00547     SDNode *N = DeadNodes.pop_back_val();
00548     
00549     if (UpdateListener)
00550       UpdateListener->NodeDeleted(N, 0);
00551     
00552     // Take the node out of the appropriate CSE map.
00553     RemoveNodeFromCSEMaps(N);
00554 
00555     // Next, brutally remove the operand list.  This is safe to do, as there are
00556     // no cycles in the graph.
00557     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
00558       SDUse &Use = *I++;
00559       SDNode *Operand = Use.getNode();
00560       Use.set(SDValue());
00561 
00562       // Now that we removed this operand, see if there are no uses of it left.
00563       if (Operand->use_empty())
00564         DeadNodes.push_back(Operand);
00565     }
00566 
00567     DeallocateNode(N);
00568   }
00569 }
00570 
00571 void SelectionDAG::RemoveDeadNode(SDNode *N, DAGUpdateListener *UpdateListener){
00572   SmallVector<SDNode*, 16> DeadNodes(1, N);
00573   RemoveDeadNodes(DeadNodes, UpdateListener);
00574 }
00575 
00576 void SelectionDAG::DeleteNode(SDNode *N) {
00577   // First take this out of the appropriate CSE map.
00578   RemoveNodeFromCSEMaps(N);
00579 
00580   // Finally, remove uses due to operands of this node, remove from the 
00581   // AllNodes list, and delete the node.
00582   DeleteNodeNotInCSEMaps(N);
00583 }
00584 
00585 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
00586   assert(N != AllNodes.begin() && "Cannot delete the entry node!");
00587   assert(N->use_empty() && "Cannot delete a node that is not dead!");
00588 
00589   // Drop all of the operands and decrement used node's use counts.
00590   N->DropOperands();
00591 
00592   DeallocateNode(N);
00593 }
00594 
00595 void SelectionDAG::DeallocateNode(SDNode *N) {
00596   if (N->OperandsNeedDelete)
00597     delete[] N->OperandList;
00598   
00599   // Set the opcode to DELETED_NODE to help catch bugs when node
00600   // memory is reallocated.
00601   N->NodeType = ISD::DELETED_NODE;
00602 
00603   NodeAllocator.Deallocate(AllNodes.remove(N));
00604 }
00605 
00606 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
00607 /// correspond to it.  This is useful when we're about to delete or repurpose
00608 /// the node.  We don't want future request for structurally identical nodes
00609 /// to return N anymore.
00610 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
00611   bool Erased = false;
00612   switch (N->getOpcode()) {
00613   case ISD::EntryToken:
00614     assert(0 && "EntryToken should not be in CSEMaps!");
00615     return false;
00616   case ISD::HANDLENODE: return false;  // noop.
00617   case ISD::CONDCODE:
00618     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
00619            "Cond code doesn't exist!");
00620     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
00621     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
00622     break;
00623   case ISD::ExternalSymbol:
00624     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00625     break;
00626   case ISD::TargetExternalSymbol:
00627     Erased =
00628       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00629     break;
00630   case ISD::VALUETYPE: {
00631     MVT VT = cast<VTSDNode>(N)->getVT();
00632     if (VT.isExtended()) {
00633       Erased = ExtendedValueTypeNodes.erase(VT);
00634     } else {
00635       Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
00636       ValueTypeNodes[VT.getSimpleVT()] = 0;
00637     }
00638     break;
00639   }
00640   default:
00641     // Remove it from the CSE Map.
00642     Erased = CSEMap.RemoveNode(N);
00643     break;
00644   }
00645 #ifndef NDEBUG
00646   // Verify that the node was actually in one of the CSE maps, unless it has a 
00647   // flag result (which cannot be CSE'd) or is one of the special cases that are
00648   // not subject to CSE.
00649   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
00650       !N->isMachineOpcode() && !doNotCSE(N)) {
00651     N->dump(this);
00652     cerr << "\n";
00653     assert(0 && "Node is not in map!");
00654   }
00655 #endif
00656   return Erased;
00657 }
00658 
00659 /// AddModifiedNodeToCSEMaps - The specified node has been removed from the CSE
00660 /// maps and modified in place. Add it back to the CSE maps, unless an identical
00661 /// node already exists, in which case transfer all its users to the existing
00662 /// node. This transfer can potentially trigger recursive merging.
00663 ///
00664 void
00665 SelectionDAG::AddModifiedNodeToCSEMaps(SDNode *N,
00666                                        DAGUpdateListener *UpdateListener) {
00667   // For node types that aren't CSE'd, just act as if no identical node
00668   // already exists.
00669   if (!doNotCSE(N)) {
00670     SDNode *Existing = CSEMap.GetOrInsertNode(N);
00671     if (Existing != N) {
00672       // If there was already an existing matching node, use ReplaceAllUsesWith
00673       // to replace the dead one with the existing one.  This can cause
00674       // recursive merging of other unrelated nodes down the line.
00675       ReplaceAllUsesWith(N, Existing, UpdateListener);
00676 
00677       // N is now dead.  Inform the listener if it exists and delete it.
00678       if (UpdateListener) 
00679         UpdateListener->NodeDeleted(N, Existing);
00680       DeleteNodeNotInCSEMaps(N);
00681       return;
00682     }
00683   }
00684 
00685   // If the node doesn't already exist, we updated it.  Inform a listener if
00686   // it exists.
00687   if (UpdateListener) 
00688     UpdateListener->NodeUpdated(N);
00689 }
00690 
00691 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00692 /// were replaced with those specified.  If this node is never memoized, 
00693 /// return null, otherwise return a pointer to the slot it would take.  If a
00694 /// node already exists with these operands, the slot will be non-null.
00695 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
00696                                            void *&InsertPos) {
00697   if (doNotCSE(N))
00698     return 0;
00699 
00700   SDValue Ops[] = { Op };
00701   FoldingSetNodeID ID;
00702   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
00703   AddNodeIDCustom(ID, N);
00704   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00705 }
00706 
00707 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00708 /// were replaced with those specified.  If this node is never memoized, 
00709 /// return null, otherwise return a pointer to the slot it would take.  If a
00710 /// node already exists with these operands, the slot will be non-null.
00711 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00712                                            SDValue Op1, SDValue Op2,
00713                                            void *&InsertPos) {
00714   if (doNotCSE(N))
00715     return 0;
00716 
00717   SDValue Ops[] = { Op1, Op2 };
00718   FoldingSetNodeID ID;
00719   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
00720   AddNodeIDCustom(ID, N);
00721   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00722 }
00723 
00724 
00725 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00726 /// were replaced with those specified.  If this node is never memoized, 
00727 /// return null, otherwise return a pointer to the slot it would take.  If a
00728 /// node already exists with these operands, the slot will be non-null.
00729 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00730                                            const SDValue *Ops,unsigned NumOps,
00731                                            void *&InsertPos) {
00732   if (doNotCSE(N))
00733     return 0;
00734 
00735   FoldingSetNodeID ID;
00736   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
00737   AddNodeIDCustom(ID, N);
00738   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00739 }
00740 
00741 /// VerifyNode - Sanity check the given node.  Aborts if it is invalid.
00742 void SelectionDAG::VerifyNode(SDNode *N) {
00743   switch (N->getOpcode()) {
00744   default:
00745     break;
00746   case ISD::BUILD_PAIR: {
00747     MVT VT = N->getValueType(0);
00748     assert(N->getNumValues() == 1 && "Too many results!");
00749     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
00750            "Wrong return type!");
00751     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
00752     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
00753            "Mismatched operand types!");
00754     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
00755            "Wrong operand type!");
00756     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
00757            "Wrong return type size");
00758     break;
00759   }
00760   case ISD::BUILD_VECTOR: {
00761     assert(N->getNumValues() == 1 && "Too many results!");
00762     assert(N->getValueType(0).isVector() && "Wrong return type!");
00763     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
00764            "Wrong number of operands!");
00765     // FIXME: Change vector_shuffle to a variadic node with mask elements being
00766     // operands of the node.  Currently the mask is a BUILD_VECTOR passed as an
00767     // operand, and it is not always possible to legalize it.  Turning off the
00768     // following checks at least makes it possible to legalize most of the time.
00769 //    MVT EltVT = N->getValueType(0).getVectorElementType();
00770 //    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
00771 //      assert(I->getValueType() == EltVT &&
00772 //             "Wrong operand type!");
00773     break;
00774   }
00775   }
00776 }
00777 
00778 /// getMVTAlignment - Compute the default alignment value for the
00779 /// given type.
00780 ///
00781 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
00782   const Type *Ty = VT == MVT::iPTR ?
00783                    PointerType::get(Type::Int8Ty, 0) :
00784                    VT.getTypeForMVT();
00785 
00786   return TLI.getTargetData()->getABITypeAlignment(Ty);
00787 }
00788 
00789 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
00790   : TLI(tli), FLI(fli), DW(0),
00791     EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
00792     Root(getEntryNode()) {
00793   AllNodes.push_back(&EntryNode);
00794 }
00795 
00796 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi,
00797                         DwarfWriter *dw) {
00798   MF = &mf;
00799   MMI = mmi;
00800   DW = dw;
00801 }
00802 
00803 SelectionDAG::~SelectionDAG() {
00804   allnodes_clear();
00805 }
00806 
00807 void SelectionDAG::allnodes_clear() {
00808   assert(&*AllNodes.begin() == &EntryNode);
00809   AllNodes.remove(AllNodes.begin());
00810   while (!AllNodes.empty())
00811     DeallocateNode(AllNodes.begin());
00812 }
00813 
00814 void SelectionDAG::clear() {
00815   allnodes_clear();
00816   OperandAllocator.Reset();
00817   CSEMap.clear();
00818 
00819   ExtendedValueTypeNodes.clear();
00820   ExternalSymbols.clear();
00821   TargetExternalSymbols.clear();
00822   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
00823             static_cast<CondCodeSDNode*>(0));
00824   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
00825             static_cast<SDNode*>(0));
00826 
00827   EntryNode.UseList = 0;
00828   AllNodes.push_back(&EntryNode);
00829   Root = getEntryNode();
00830 }
00831 
00832 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
00833   if (Op.getValueType() == VT) return Op;
00834   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
00835                                    VT.getSizeInBits());
00836   return getNode(ISD::AND, Op.getValueType(), Op,
00837                  getConstant(Imm, Op.getValueType()));
00838 }
00839 
00840 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, DebugLoc DL, MVT VT) {
00841   if (Op.getValueType() == VT) return Op;
00842   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
00843                                    VT.getSizeInBits());
00844   return getNode(ISD::AND, DL, Op.getValueType(), Op,
00845                  getConstant(Imm, Op.getValueType()));
00846 }
00847 
00848 /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
00849 ///
00850 SDValue SelectionDAG::getNOT(DebugLoc DL, SDValue Val, MVT VT) {
00851   SDValue NegOne;
00852   if (VT.isVector()) {
00853     MVT EltVT = VT.getVectorElementType();
00854     SDValue NegOneElt =
00855       getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), EltVT);
00856     std::vector<SDValue> NegOnes(VT.getVectorNumElements(), NegOneElt);
00857     NegOne = getNode(ISD::BUILD_VECTOR, DL, VT, &NegOnes[0], NegOnes.size());
00858   } else {
00859     NegOne = getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
00860   }
00861   return getNode(ISD::XOR, DL, VT, Val, NegOne);
00862 }
00863 
00864 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
00865   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
00866   assert((EltVT.getSizeInBits() >= 64 ||
00867          (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
00868          "getConstant with a uint64_t value that doesn't fit in the type!");
00869   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
00870 }
00871 
00872 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
00873   return getConstant(*ConstantInt::get(Val), VT, isT);
00874 }
00875 
00876 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
00877   assert(VT.isInteger() && "Cannot create FP integer constant!");
00878 
00879   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
00880   assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
00881          "APInt size does not match type size!");
00882 
00883   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
00884   FoldingSetNodeID ID;
00885   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
00886   ID.AddPointer(&Val);
00887   void *IP = 0;
00888   SDNode *N = NULL;
00889   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
00890     if (!VT.isVector())
00891       return SDValue(N, 0);
00892   if (!N) {
00893     N = NodeAllocator.Allocate<ConstantSDNode>();
00894     new (N) ConstantSDNode(isT, &Val, EltVT);
00895     CSEMap.InsertNode(N, IP);
00896     AllNodes.push_back(N);
00897   }
00898 
00899   SDValue Result(N, 0);
00900   if (VT.isVector()) {
00901     SmallVector<SDValue, 8> Ops;
00902     Ops.assign(VT.getVectorNumElements(), Result);
00903     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
00904   }
00905   return Result;
00906 }
00907 
00908 SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, bool isTarget) {
00909   return getConstant(Val, TLI.getPointerTy(), isTarget);
00910 }
00911 
00912 
00913 SDValue SelectionDAG::getConstantFP(const APFloat& V, MVT VT, bool isTarget) {
00914   return getConstantFP(*ConstantFP::get(V), VT, isTarget);
00915 }
00916 
00917 SDValue SelectionDAG::getConstantFP(const ConstantFP& V, MVT VT, bool isTarget){
00918   assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
00919                                 
00920   MVT EltVT =
00921     VT.isVector() ? VT.getVectorElementType() : VT;
00922 
00923   // Do the map lookup using the actual bit pattern for the floating point
00924   // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
00925   // we don't have issues with SNANs.
00926   unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
00927   FoldingSetNodeID ID;
00928   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
00929   ID.AddPointer(&V);
00930   void *IP = 0;
00931   SDNode *N = NULL;
00932   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
00933     if (!VT.isVector())
00934       return SDValue(N, 0);
00935   if (!N) {
00936     N = NodeAllocator.Allocate<ConstantFPSDNode>();
00937     new (N) ConstantFPSDNode(isTarget, &V, EltVT);
00938     CSEMap.InsertNode(N, IP);
00939     AllNodes.push_back(N);
00940   }
00941 
00942   SDValue Result(N, 0);
00943   if (VT.isVector()) {
00944     SmallVector<SDValue, 8> Ops;
00945     Ops.assign(VT.getVectorNumElements(), Result);
00946     Result = getNode(ISD::BUILD_VECTOR, VT, &Ops[0], Ops.size());
00947   }
00948   return Result;
00949 }
00950 
00951 SDValue SelectionDAG::getConstantFP(double Val, MVT VT, bool isTarget) {
00952   MVT EltVT =
00953     VT.isVector() ? VT.getVectorElementType() : VT;
00954   if (EltVT==MVT::f32)
00955     return getConstantFP(APFloat((float)Val), VT, isTarget);
00956   else
00957     return getConstantFP(APFloat(Val), VT, isTarget);
00958 }
00959 
00960 SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV,
00961                                        MVT VT, int64_t Offset,
00962                                        bool isTargetGA) {
00963   unsigned Opc;
00964 
00965   // Truncate (with sign-extension) the offset value to the pointer size.
00966   unsigned BitWidth = TLI.getPointerTy().getSizeInBits();
00967   if (BitWidth < 64)
00968     Offset = (Offset << (64 - BitWidth) >> (64 - BitWidth));
00969 
00970   const GlobalVariable *GVar = dyn_cast<GlobalVariable>(GV);
00971   if (!GVar) {
00972     // If GV is an alias then use the aliasee for determining thread-localness.
00973     if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
00974       GVar = dyn_cast_or_null<GlobalVariable>(GA->resolveAliasedGlobal(false));
00975   }
00976 
00977   if (GVar && GVar->isThreadLocal())
00978     Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
00979   else
00980     Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
00981 
00982   FoldingSetNodeID ID;
00983   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
00984   ID.AddPointer(GV);
00985   ID.AddInteger(Offset);
00986   void *IP = 0;
00987   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
00988     return SDValue(E, 0);
00989   SDNode *N = NodeAllocator.Allocate<GlobalAddressSDNode>();
00990   new (N) GlobalAddressSDNode(isTargetGA, GV, VT, Offset);
00991   CSEMap.InsertNode(N, IP);
00992   AllNodes.push_back(N);
00993   return SDValue(N, 0);
00994 }
00995 
00996 SDValue SelectionDAG::getFrameIndex(int FI, MVT VT, bool isTarget) {
00997   unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
00998   FoldingSetNodeID ID;
00999   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
01000   ID.AddInteger(FI);
01001   void *IP = 0;
01002   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01003     return SDValue(E, 0);
01004   SDNode *N = NodeAllocator.Allocate<FrameIndexSDNode>();
01005   new (N) FrameIndexSDNode(FI, VT, isTarget);
01006   CSEMap.InsertNode(N, IP);
01007   AllNodes.push_back(N);
01008   return SDValue(N, 0);
01009 }
01010 
01011 SDValue SelectionDAG::getJumpTable(int JTI, MVT VT, bool isTarget){
01012   unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
01013   FoldingSetNodeID ID;
01014   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
01015   ID.AddInteger(JTI);
01016   void *IP = 0;
01017   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01018     return SDValue(E, 0);
01019   SDNode *N = NodeAllocator.Allocate<JumpTableSDNode>();
01020   new (N) JumpTableSDNode(JTI, VT, isTarget);
01021   CSEMap.InsertNode(N, IP);
01022   AllNodes.push_back(N);
01023   return SDValue(N, 0);
01024 }
01025 
01026 SDValue SelectionDAG::getConstantPool(Constant *C, MVT VT,
01027                                       unsigned Alignment, int Offset,
01028                                       bool isTarget) {
01029   if (Alignment == 0)
01030     Alignment =
01031       TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
01032   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
01033   FoldingSetNodeID ID;
01034   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
01035   ID.AddInteger(Alignment);
01036   ID.AddInteger(Offset);
01037   ID.AddPointer(C);
01038   void *IP = 0;
01039   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01040     return SDValue(E, 0);
01041   SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
01042   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
01043   CSEMap.InsertNode(N, IP);
01044   AllNodes.push_back(N);
01045   return SDValue(N, 0);
01046 }
01047 
01048 
01049 SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, MVT VT,
01050                                       unsigned Alignment, int Offset,
01051                                       bool isTarget) {
01052   if (Alignment == 0)
01053     Alignment =
01054       TLI.getTargetData()->getPreferredTypeAlignmentShift(C->getType());
01055   unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
01056   FoldingSetNodeID ID;
01057   AddNodeIDNode(ID, Opc, getVTList(VT), 0, 0);
01058   ID.AddInteger(Alignment);
01059   ID.AddInteger(Offset);
01060   C->AddSelectionDAGCSEId(ID);
01061   void *IP = 0;
01062   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01063     return SDValue(E, 0);
01064   SDNode *N = NodeAllocator.Allocate<ConstantPoolSDNode>();
01065   new (N) ConstantPoolSDNode(isTarget, C, VT, Offset, Alignment);
01066   CSEMap.InsertNode(N, IP);
01067   AllNodes.push_back(N);
01068   return SDValue(N, 0);
01069 }
01070 
01071 
01072 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
01073   FoldingSetNodeID ID;
01074   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
01075   ID.AddPointer(MBB);
01076   void *IP = 0;
01077   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01078     return SDValue(E, 0);
01079   SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
01080   new (N) BasicBlockSDNode(MBB);
01081   CSEMap.InsertNode(N, IP);
01082   AllNodes.push_back(N);
01083   return SDValue(N, 0);
01084 }
01085 
01086 SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB, DebugLoc dl) {
01087   FoldingSetNodeID ID;
01088   AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), 0, 0);
01089   ID.AddPointer(MBB);
01090   void *IP = 0;
01091   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01092     return SDValue(E, 0);
01093   SDNode *N = NodeAllocator.Allocate<BasicBlockSDNode>();
01094   new (N) BasicBlockSDNode(MBB, dl);
01095   CSEMap.InsertNode(N, IP);
01096   AllNodes.push_back(N);
01097   return SDValue(N, 0);
01098 }
01099 
01100 SDValue SelectionDAG::getArgFlags(ISD::ArgFlagsTy Flags) {
01101   FoldingSetNodeID ID;
01102   AddNodeIDNode(ID, ISD::ARG_FLAGS, getVTList(MVT::Other), 0, 0);
01103   ID.AddInteger(Flags.getRawBits());
01104   void *IP = 0;
01105   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01106     return SDValue(E, 0);
01107   SDNode *N = NodeAllocator.Allocate<ARG_FLAGSSDNode>();
01108   new (N) ARG_FLAGSSDNode(Flags);
01109   CSEMap.InsertNode(N, IP);
01110   AllNodes.push_back(N);
01111   return SDValue(N, 0);
01112 }
01113 
01114 SDValue SelectionDAG::getValueType(MVT VT) {
01115   if (VT.isSimple() && (unsigned)VT.getSimpleVT() >= ValueTypeNodes.size())
01116     ValueTypeNodes.resize(VT.getSimpleVT()+1);
01117 
01118   SDNode *&N = VT.isExtended() ?
01119     ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT()];
01120 
01121   if (N) return SDValue(N, 0);
01122   N = NodeAllocator.Allocate<VTSDNode>();
01123   new (N) VTSDNode(VT);
01124   AllNodes.push_back(N);
01125   return SDValue(N, 0);
01126 }
01127 
01128 SDValue SelectionDAG::getExternalSymbol(const char *Sym, MVT VT) {
01129   SDNode *&N = ExternalSymbols[Sym];
01130   if (N) return SDValue(N, 0);
01131   N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
01132   new (N) ExternalSymbolSDNode(false, Sym, VT);
01133   AllNodes.push_back(N);
01134   return SDValue(N, 0);
01135 }
01136 
01137 SDValue SelectionDAG::getExternalSymbol(const char *Sym, DebugLoc dl, MVT VT) {
01138   SDNode *&N = ExternalSymbols[Sym];
01139   if (N) return SDValue(N, 0);
01140   N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
01141   new (N) ExternalSymbolSDNode(false, dl, Sym, VT);
01142   AllNodes.push_back(N);
01143   return SDValue(N, 0);
01144 }
01145 
01146 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, MVT VT) {
01147   SDNode *&N = TargetExternalSymbols[Sym];
01148   if (N) return SDValue(N, 0);
01149   N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
01150   new (N) ExternalSymbolSDNode(true, Sym, VT);
01151   AllNodes.push_back(N);
01152   return SDValue(N, 0);
01153 }
01154 
01155 SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, DebugLoc dl, 
01156                                               MVT VT) {
01157   SDNode *&N = TargetExternalSymbols[Sym];
01158   if (N) return SDValue(N, 0);
01159   N = NodeAllocator.Allocate<ExternalSymbolSDNode>();
01160   new (N) ExternalSymbolSDNode(true, dl, Sym, VT);
01161   AllNodes.push_back(N);
01162   return SDValue(N, 0);
01163 }
01164 
01165 SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
01166   if ((unsigned)Cond >= CondCodeNodes.size())
01167     CondCodeNodes.resize(Cond+1);
01168 
01169   if (CondCodeNodes[Cond] == 0) {
01170     CondCodeSDNode *N = NodeAllocator.Allocate<CondCodeSDNode>();
01171     new (N) CondCodeSDNode(Cond);
01172     CondCodeNodes[Cond] = N;
01173     AllNodes.push_back(N);
01174   }
01175   return SDValue(CondCodeNodes[Cond], 0);
01176 }
01177 
01178 SDValue SelectionDAG::getConvertRndSat(MVT VT, SDValue Val, SDValue DTy,
01179                                        SDValue STy, SDValue Rnd, SDValue Sat,
01180                                        ISD::CvtCode Code) {
01181   // If the src and dest types are the same, no conversion is necessary.
01182   if (DTy == STy)
01183     return Val;
01184 
01185   FoldingSetNodeID ID;
01186   void* IP = 0;
01187   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01188     return SDValue(E, 0);
01189   CvtRndSatSDNode *N = NodeAllocator.Allocate<CvtRndSatSDNode>();
01190   SDValue Ops[] = { Val, DTy, STy, Rnd, Sat };
01191   new (N) CvtRndSatSDNode(VT, Ops, 5, Code);
01192   CSEMap.InsertNode(N, IP);
01193   AllNodes.push_back(N);
01194   return SDValue(N, 0);
01195 }
01196 
01197 SDValue SelectionDAG::getRegister(unsigned RegNo, MVT VT) {
01198   FoldingSetNodeID ID;
01199   AddNodeIDNode(ID, ISD::Register, getVTList(VT), 0, 0);
01200   ID.AddInteger(RegNo);
01201   void *IP = 0;
01202   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01203     return SDValue(E, 0);
01204   SDNode *N = NodeAllocator.Allocate<RegisterSDNode>();
01205   new (N) RegisterSDNode(RegNo, VT);
01206   CSEMap.InsertNode(N, IP);
01207   AllNodes.push_back(N);
01208   return SDValue(N, 0);
01209 }
01210 
01211 SDValue SelectionDAG::getDbgStopPoint(SDValue Root,
01212                                       unsigned Line, unsigned Col,
01213                                       Value *CU) {
01214   SDNode *N = NodeAllocator.Allocate<DbgStopPointSDNode>();
01215   new (N) DbgStopPointSDNode(Root, Line, Col, CU);
01216   AllNodes.push_back(N);
01217   return SDValue(N, 0);
01218 }
01219 
01220 SDValue SelectionDAG::getLabel(unsigned Opcode,
01221                                SDValue Root,
01222                                unsigned LabelID) {
01223   FoldingSetNodeID ID;
01224   SDValue Ops[] = { Root };
01225   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
01226   ID.AddInteger(LabelID);
01227   void *IP = 0;
01228   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01229     return SDValue(E, 0);
01230   SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
01231   new (N) LabelSDNode(Opcode, Root, LabelID);
01232   CSEMap.InsertNode(N, IP);
01233   AllNodes.push_back(N);
01234   return SDValue(N, 0);
01235 }
01236 
01237 SDValue SelectionDAG::getLabel(unsigned Opcode, DebugLoc dl,
01238                                SDValue Root,
01239                                unsigned LabelID) {
01240   FoldingSetNodeID ID;
01241   SDValue Ops[] = { Root };
01242   AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), &Ops[0], 1);
01243   ID.AddInteger(LabelID);
01244   void *IP = 0;
01245   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01246     return SDValue(E, 0);
01247   SDNode *N = NodeAllocator.Allocate<LabelSDNode>();
01248   new (N) LabelSDNode(Opcode, dl, Root, LabelID);
01249   CSEMap.InsertNode(N, IP);
01250   AllNodes.push_back(N);
01251   return SDValue(N, 0);
01252 }
01253 
01254 SDValue SelectionDAG::getSrcValue(const Value *V) {
01255   assert((!V || isa<PointerType>(V->getType())) &&
01256          "SrcValue is not a pointer?");
01257 
01258   FoldingSetNodeID ID;
01259   AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), 0, 0);
01260   ID.AddPointer(V);
01261 
01262   void *IP = 0;
01263   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01264     return SDValue(E, 0);
01265 
01266   SDNode *N = NodeAllocator.Allocate<SrcValueSDNode>();
01267   new (N) SrcValueSDNode(V);
01268   CSEMap.InsertNode(N, IP);
01269   AllNodes.push_back(N);
01270   return SDValue(N, 0);
01271 }
01272 
01273 SDValue SelectionDAG::getMemOperand(const MachineMemOperand &MO) {
01274 #ifndef NDEBUG
01275   const Value *v = MO.getValue();
01276   assert((!v || isa<PointerType>(v->getType())) &&
01277          "SrcValue is not a pointer?");
01278 #endif
01279 
01280   FoldingSetNodeID ID;
01281   AddNodeIDNode(ID, ISD::MEMOPERAND, getVTList(MVT::Other), 0, 0);
01282   MO.Profile(ID);
01283 
01284   void *IP = 0;
01285   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
01286     return SDValue(E, 0);
01287 
01288   SDNode *N = NodeAllocator.Allocate<MemOperandSDNode>();
01289   new (N) MemOperandSDNode(MO);
01290   CSEMap.InsertNode(N, IP);
01291   AllNodes.push_back(N);
01292   return SDValue(N, 0);
01293 }
01294 
01295 /// getShiftAmountOperand - Return the specified value casted to
01296 /// the target's desired shift amount type.
01297 SDValue SelectionDAG::getShiftAmountOperand(SDValue Op) {
01298   MVT OpTy = Op.getValueType();
01299   MVT ShTy = TLI.getShiftAmountTy();
01300   if (OpTy == ShTy || OpTy.isVector()) return Op;
01301 
01302   ISD::NodeType Opcode = OpTy.bitsGT(ShTy) ?  ISD::TRUNCATE : ISD::ZERO_EXTEND;
01303   return getNode(Opcode, ShTy, Op);
01304 }
01305 
01306 /// CreateStackTemporary - Create a stack temporary, suitable for holding the
01307 /// specified value type.
01308 SDValue SelectionDAG::CreateStackTemporary(MVT VT, unsigned minAlign) {
01309   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
01310   unsigned ByteSize = VT.getStoreSizeInBits()/8;
01311   const Type *Ty = VT.getTypeForMVT();
01312   unsigned StackAlign =
01313   std::max((unsigned)TLI.getTargetData()->getPrefTypeAlignment(Ty), minAlign);
01314   
01315   int FrameIdx = FrameInfo->CreateStackObject(ByteSize, StackAlign);
01316   return getFrameIndex(FrameIdx, TLI.getPointerTy());
01317 }
01318 
01319 /// CreateStackTemporary - Create a stack temporary suitable for holding
01320 /// either of the specified value types.
01321 SDValue SelectionDAG::CreateStackTemporary(MVT VT1, MVT VT2) {
01322   unsigned Bytes = std::max(VT1.getStoreSizeInBits(),
01323                             VT2.getStoreSizeInBits())/8;
01324   const Type *Ty1 = VT1.getTypeForMVT();
01325   const Type *Ty2 = VT2.getTypeForMVT();
01326   const TargetData *TD = TLI.getTargetData();
01327   unsigned Align = std::max(TD->getPrefTypeAlignment(Ty1),
01328                             TD->getPrefTypeAlignment(Ty2));
01329 
01330   MachineFrameInfo *FrameInfo = getMachineFunction().getFrameInfo();
01331   int FrameIdx = FrameInfo->CreateStackObject(Bytes, Align);
01332   return getFrameIndex(FrameIdx, TLI.getPointerTy());
01333 }
01334 
01335 SDValue SelectionDAG::FoldSetCC(MVT VT, SDValue N1,
01336                                 SDValue N2, ISD::CondCode Cond, DebugLoc dl) {
01337   // These setcc operations always fold.
01338   switch (Cond) {
01339   default: break;
01340   case ISD::SETFALSE:
01341   case ISD::SETFALSE2: return getConstant(0, VT);
01342   case ISD::SETTRUE:
01343   case ISD::SETTRUE2:  return getConstant(1, VT);
01344     
01345   case ISD::SETOEQ:
01346   case ISD::SETOGT:
01347   case ISD::SETOGE:
01348   case ISD::SETOLT:
01349   case ISD::SETOLE:
01350   case ISD::SETONE:
01351   case ISD::SETO:
01352   case ISD::SETUO:
01353   case ISD::SETUEQ:
01354   case ISD::SETUNE:
01355     assert(!N1.getValueType().isInteger() && "Illegal setcc for integer!");
01356     break;
01357   }
01358   
01359   if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode())) {
01360     const APInt &C2 = N2C->getAPIntValue();
01361     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode())) {
01362       const APInt &C1 = N1C->getAPIntValue();
01363       
01364       switch (Cond) {
01365       default: assert(0 && "Unknown integer setcc!");
01366       case ISD::SETEQ:  return getConstant(C1 == C2, VT);
01367       case ISD::SETNE:  return getConstant(C1 != C2, VT);
01368       case ISD::SETULT: return getConstant(C1.ult(C2), VT);
01369       case ISD::SETUGT: return getConstant(C1.ugt(C2), VT);
01370       case ISD::SETULE: return getConstant(C1.ule(C2), VT);
01371       case ISD::SETUGE: return getConstant(C1.uge(C2), VT);
01372       case ISD::SETLT:  return getConstant(C1.slt(C2), VT);
01373       case ISD::SETGT:  return getConstant(C1.sgt(C2), VT);
01374       case ISD::SETLE:  return getConstant(C1.sle(C2), VT);
01375       case ISD::SETGE:  return getConstant(C1.sge(C2), VT);
01376       }
01377     }
01378   }
01379   if (ConstantFPSDNode *N1C = dyn_cast<ConstantFPSDNode>(N1.getNode())) {
01380     if (ConstantFPSDNode *N2C = dyn_cast<ConstantFPSDNode>(N2.getNode())) {
01381       // No compile time operations on this type yet.
01382       if (N1C->getValueType(0) == MVT::ppcf128)
01383         return SDValue();
01384 
01385       APFloat::cmpResult R = N1C->getValueAPF().compare(N2C->getValueAPF());
01386       switch (Cond) {
01387       default: break;
01388       case ISD::SETEQ:  if (R==APFloat::cmpUnordered) 
01389                           return getNode(ISD::UNDEF, dl, VT);
01390                         // fall through
01391       case ISD::SETOEQ: return getConstant(R==APFloat::cmpEqual, VT);
01392       case ISD::SETNE:  if (R==APFloat::cmpUnordered) 
01393                           return getNode(ISD::UNDEF, dl, VT);
01394                         // fall through
01395       case ISD::SETONE: return getConstant(R==APFloat::cmpGreaterThan ||
01396                                            R==APFloat::cmpLessThan, VT);
01397       case ISD::SETLT:  if (R==APFloat::cmpUnordered) 
01398                           return getNode(ISD::UNDEF, dl, VT);
01399                         // fall through
01400       case ISD::SETOLT: return getConstant(R==APFloat::cmpLessThan, VT);
01401       case ISD::SETGT:  if (R==APFloat::cmpUnordered) 
01402                           return getNode(ISD::UNDEF, dl, VT);
01403                         // fall through
01404       case ISD::SETOGT: return getConstant(R==APFloat::cmpGreaterThan, VT);
01405       case ISD::SETLE:  if (R==APFloat::cmpUnordered) 
01406                           return getNode(ISD::UNDEF, dl, VT);
01407                         // fall through
01408       case ISD::SETOLE: return getConstant(R==APFloat::cmpLessThan ||
01409                                            R==APFloat::cmpEqual, VT);
01410       case ISD::SETGE:  if (R==APFloat::cmpUnordered) 
01411                           return getNode(ISD::UNDEF, dl, VT);
01412                         // fall through
01413       case ISD::SETOGE: return getConstant(R==APFloat::cmpGreaterThan ||
01414                                            R==APFloat::cmpEqual, VT);
01415       case ISD::SETO:   return getConstant(R!=APFloat::cmpUnordered, VT);
01416       case ISD::SETUO:  return getConstant(R==APFloat::cmpUnordered, VT);
01417       case ISD::SETUEQ: return getConstant(R==APFloat::cmpUnordered ||
01418                                            R==APFloat::cmpEqual, VT);
01419       case ISD::SETUNE: return getConstant(R!=APFloat::cmpEqual, VT);
01420       case ISD::SETULT: return getConstant(R==APFloat::cmpUnordered ||
01421                                            R==APFloat::cmpLessThan, VT);
01422       case ISD::SETUGT: return getConstant(R==APFloat::cmpGreaterThan ||
01423                                            R==APFloat::cmpUnordered, VT);
01424       case ISD::SETULE: return getConstant(R!=APFloat::cmpGreaterThan, VT);
01425       case ISD::SETUGE: return getConstant(R!=APFloat::cmpLessThan, VT);
01426       }
01427     } else {
01428       // Ensure that the constant occurs on the RHS.
01429       return getSetCC(dl, VT, N2, N1, ISD::getSetCCSwappedOperands(Cond));
01430     }
01431   }
01432 
01433   // Could not fold it.
01434   return SDValue();
01435 }
01436 
01437 /// SignBitIsZero - Return true if the sign bit of Op is known to be zero.  We
01438 /// use this predicate to simplify operations downstream.
01439 bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
01440   unsigned BitWidth = Op.getValueSizeInBits();
01441   return MaskedValueIsZero(Op, APInt::getSignBit(BitWidth), Depth);
01442 }
01443 
01444 /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero.  We use
01445 /// this predicate to simplify operations downstream.  Mask is known to be zero
01446 /// for bits that V cannot have.
01447 bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask, 
01448                                      unsigned Depth) const {
01449   APInt KnownZero, KnownOne;
01450   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
01451   assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01452   return (KnownZero & Mask) == Mask;
01453 }
01454 
01455 /// ComputeMaskedBits - Determine which of the bits specified in Mask are
01456 /// known to be either zero or one and return them in the KnownZero/KnownOne
01457 /// bitsets.  This code only analyzes bits in Mask, in order to short-circuit
01458 /// processing.
01459 void SelectionDAG::ComputeMaskedBits(SDValue Op, const APInt &Mask, 
01460                                      APInt &KnownZero, APInt &KnownOne,
01461                                      unsigned Depth) const {
01462   unsigned BitWidth = Mask.getBitWidth();
01463   assert(BitWidth == Op.getValueType().getSizeInBits() &&
01464          "Mask size mismatches value type size!");
01465 
01466   KnownZero = KnownOne = APInt(BitWidth, 0);   // Don't know anything.
01467   if (Depth == 6 || Mask == 0)
01468     return;  // Limit search depth.
01469   
01470   APInt KnownZero2, KnownOne2;
01471 
01472   switch (Op.getOpcode()) {
01473   case ISD::Constant:
01474     // We know all of the bits for a constant!
01475     KnownOne = cast<ConstantSDNode>(Op)->getAPIntValue() & Mask;
01476     KnownZero = ~KnownOne & Mask;
01477     return;
01478   case ISD::AND:
01479     // If either the LHS or the RHS are Zero, the result is zero.
01480     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
01481     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownZero,
01482                       KnownZero2, KnownOne2, Depth+1);
01483     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01484     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01485 
01486     // Output known-1 bits are only known if set in both the LHS & RHS.
01487     KnownOne &= KnownOne2;
01488     // Output known-0 are known to be clear if zero in either the LHS | RHS.
01489     KnownZero |= KnownZero2;
01490     return;
01491   case ISD::OR:
01492     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
01493     ComputeMaskedBits(Op.getOperand(0), Mask & ~KnownOne,
01494                       KnownZero2, KnownOne2, Depth+1);
01495     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01496     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01497     
01498     // Output known-0 bits are only known if clear in both the LHS & RHS.
01499     KnownZero &= KnownZero2;
01500     // Output known-1 are known to be set if set in either the LHS | RHS.
01501     KnownOne |= KnownOne2;
01502     return;
01503   case ISD::XOR: {
01504     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
01505     ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2, Depth+1);
01506     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01507     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01508     
01509     // Output known-0 bits are known if clear or set in both the LHS & RHS.
01510     APInt KnownZeroOut = (KnownZero & KnownZero2) | (KnownOne & KnownOne2);
01511     // Output known-1 are known to be set if set in only one of the LHS, RHS.
01512     KnownOne = (KnownZero & KnownOne2) | (KnownOne & KnownZero2);
01513     KnownZero = KnownZeroOut;
01514     return;
01515   }
01516   case ISD::MUL: {
01517     APInt Mask2 = APInt::getAllOnesValue(BitWidth);
01518     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero, KnownOne, Depth+1);
01519     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
01520     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
01521     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
01522 
01523     // If low bits are zero in either operand, output low known-0 bits.
01524     // Also compute a conserative estimate for high known-0 bits.
01525     // More trickiness is possible, but this is sufficient for the
01526     // interesting case of alignment computation.
01527     KnownOne.clear();
01528     unsigned TrailZ = KnownZero.countTrailingOnes() +
01529                       KnownZero2.countTrailingOnes();
01530     unsigned LeadZ =  std::max(KnownZero.countLeadingOnes() +
01531                                KnownZero2.countLeadingOnes(),
01532                                BitWidth) - BitWidth;
01533 
01534     TrailZ = std::min(TrailZ, BitWidth);
01535     LeadZ = std::min(LeadZ, BitWidth);
01536     KnownZero = APInt::getLowBitsSet(BitWidth, TrailZ) |
01537                 APInt::getHighBitsSet(BitWidth, LeadZ);
01538     KnownZero &= Mask;
01539     return;
01540   }
01541   case ISD::UDIV: {
01542     // For the purposes of computing leading zeros we can conservatively
01543     // treat a udiv as a logical right shift by the power of 2 known to
01544     // be less than the denominator.
01545     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
01546     ComputeMaskedBits(Op.getOperand(0),
01547                       AllOnes, KnownZero2, KnownOne2, Depth+1);
01548     unsigned LeadZ = KnownZero2.countLeadingOnes();
01549 
01550     KnownOne2.clear();
01551     KnownZero2.clear();
01552     ComputeMaskedBits(Op.getOperand(1),
01553                       AllOnes, KnownZero2, KnownOne2, Depth+1);
01554     unsigned RHSUnknownLeadingOnes = KnownOne2.countLeadingZeros();
01555     if (RHSUnknownLeadingOnes != BitWidth)
01556       LeadZ = std::min(BitWidth,
01557                        LeadZ + BitWidth - RHSUnknownLeadingOnes - 1);
01558 
01559     KnownZero = APInt::getHighBitsSet(BitWidth, LeadZ) & Mask;
01560     return;
01561   }
01562   case ISD::SELECT:
01563     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero, KnownOne, Depth+1);
01564     ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero2, KnownOne2, Depth+1);
01565     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01566     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01567     
01568     // Only known if known in both the LHS and RHS.
01569     KnownOne &= KnownOne2;
01570     KnownZero &= KnownZero2;
01571     return;
01572   case ISD::SELECT_CC:
01573     ComputeMaskedBits(Op.getOperand(3), Mask, KnownZero, KnownOne, Depth+1);
01574     ComputeMaskedBits(Op.getOperand(2), Mask, KnownZero2, KnownOne2, Depth+1);
01575     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01576     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01577     
01578     // Only known if known in both the LHS and RHS.
01579     KnownOne &= KnownOne2;
01580     KnownZero &= KnownZero2;
01581     return;
01582   case ISD::SADDO:
01583   case ISD::UADDO:
01584   case ISD::SSUBO:
01585   case ISD::USUBO:
01586   case ISD::SMULO:
01587   case ISD::UMULO:
01588     if (Op.getResNo() != 1)
01589       return;
01590     // The boolean result conforms to getBooleanContents.  Fall through.
01591   case ISD::SETCC:
01592     // If we know the result of a setcc has the top bits zero, use this info.
01593     if (TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent &&
01594         BitWidth > 1)
01595       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - 1);
01596     return;
01597   case ISD::SHL:
01598     // (shl X, C1) & C2 == 0   iff   (X & C2 >>u C1) == 0
01599     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01600       unsigned ShAmt = SA->getZExtValue();
01601 
01602       // If the shift count is an invalid immediate, don't do anything.
01603       if (ShAmt >= BitWidth)
01604         return;
01605 
01606       ComputeMaskedBits(Op.getOperand(0), Mask.lshr(ShAmt),
01607                         KnownZero, KnownOne, Depth+1);
01608       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01609       KnownZero <<= ShAmt;
01610       KnownOne  <<= ShAmt;
01611       // low bits known zero.
01612       KnownZero |= APInt::getLowBitsSet(BitWidth, ShAmt);
01613     }
01614     return;
01615   case ISD::SRL:
01616     // (ushr X, C1) & C2 == 0   iff  (-1 >> C1) & C2 == 0
01617     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01618       unsigned ShAmt = SA->getZExtValue();
01619 
01620       // If the shift count is an invalid immediate, don't do anything.
01621       if (ShAmt >= BitWidth)
01622         return;
01623 
01624       ComputeMaskedBits(Op.getOperand(0), (Mask << ShAmt),
01625                         KnownZero, KnownOne, Depth+1);
01626       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01627       KnownZero = KnownZero.lshr(ShAmt);
01628       KnownOne  = KnownOne.lshr(ShAmt);
01629 
01630       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
01631       KnownZero |= HighBits;  // High bits known zero.
01632     }
01633     return;
01634   case ISD::SRA:
01635     if (ConstantSDNode *SA = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01636       unsigned ShAmt = SA->getZExtValue();
01637 
01638       // If the shift count is an invalid immediate, don't do anything.
01639       if (ShAmt >= BitWidth)
01640         return;
01641 
01642       APInt InDemandedMask = (Mask << ShAmt);
01643       // If any of the demanded bits are produced by the sign extension, we also
01644       // demand the input sign bit.
01645       APInt HighBits = APInt::getHighBitsSet(BitWidth, ShAmt) & Mask;
01646       if (HighBits.getBoolValue())
01647         InDemandedMask |= APInt::getSignBit(BitWidth);
01648       
01649       ComputeMaskedBits(Op.getOperand(0), InDemandedMask, KnownZero, KnownOne,
01650                         Depth+1);
01651       assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01652       KnownZero = KnownZero.lshr(ShAmt);
01653       KnownOne  = KnownOne.lshr(ShAmt);
01654       
01655       // Handle the sign bits.
01656       APInt SignBit = APInt::getSignBit(BitWidth);
01657       SignBit = SignBit.lshr(ShAmt);  // Adjust to where it is now in the mask.
01658       
01659       if (KnownZero.intersects(SignBit)) {
01660         KnownZero |= HighBits;  // New bits are known zero.
01661       } else if (KnownOne.intersects(SignBit)) {
01662         KnownOne  |= HighBits;  // New bits are known one.
01663       }
01664     }
01665     return;
01666   case ISD::SIGN_EXTEND_INREG: {
01667     MVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
01668     unsigned EBits = EVT.getSizeInBits();
01669     
01670     // Sign extension.  Compute the demanded bits in the result that are not 
01671     // present in the input.
01672     APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits) & Mask;
01673 
01674     APInt InSignBit = APInt::getSignBit(EBits);
01675     APInt InputDemandedBits = Mask & APInt::getLowBitsSet(BitWidth, EBits);
01676     
01677     // If the sign extended bits are demanded, we know that the sign
01678     // bit is demanded.
01679     InSignBit.zext(BitWidth);
01680     if (NewBits.getBoolValue())
01681       InputDemandedBits |= InSignBit;
01682     
01683     ComputeMaskedBits(Op.getOperand(0), InputDemandedBits,
01684                       KnownZero, KnownOne, Depth+1);
01685     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01686     
01687     // If the sign bit of the input is known set or clear, then we know the
01688     // top bits of the result.
01689     if (KnownZero.intersects(InSignBit)) {         // Input sign bit known clear
01690       KnownZero |= NewBits;
01691       KnownOne  &= ~NewBits;
01692     } else if (KnownOne.intersects(InSignBit)) {   // Input sign bit known set
01693       KnownOne  |= NewBits;
01694       KnownZero &= ~NewBits;
01695     } else {                              // Input sign bit unknown
01696       KnownZero &= ~NewBits;
01697       KnownOne  &= ~NewBits;
01698     }
01699     return;
01700   }
01701   case ISD::CTTZ:
01702   case ISD::CTLZ:
01703   case ISD::CTPOP: {
01704     unsigned LowBits = Log2_32(BitWidth)+1;
01705     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - LowBits);
01706     KnownOne.clear();
01707     return;
01708   }
01709   case ISD::LOAD: {
01710     if (ISD::isZEXTLoad(Op.getNode())) {
01711       LoadSDNode *LD = cast<LoadSDNode>(Op);
01712       MVT VT = LD->getMemoryVT();
01713       unsigned MemBits = VT.getSizeInBits();
01714       KnownZero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits) & Mask;
01715     }
01716     return;
01717   }
01718   case ISD::ZERO_EXTEND: {
01719     MVT InVT = Op.getOperand(0).getValueType();
01720     unsigned InBits = InVT.getSizeInBits();
01721     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
01722     APInt InMask    = Mask;
01723     InMask.trunc(InBits);
01724     KnownZero.trunc(InBits);
01725     KnownOne.trunc(InBits);
01726     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
01727     KnownZero.zext(BitWidth);
01728     KnownOne.zext(BitWidth);
01729     KnownZero |= NewBits;
01730     return;
01731   }
01732   case ISD::SIGN_EXTEND: {
01733     MVT InVT = Op.getOperand(0).getValueType();
01734     unsigned InBits = InVT.getSizeInBits();
01735     APInt InSignBit = APInt::getSignBit(InBits);
01736     APInt NewBits   = APInt::getHighBitsSet(BitWidth, BitWidth - InBits) & Mask;
01737     APInt InMask = Mask;
01738     InMask.trunc(InBits);
01739 
01740     // If any of the sign extended bits are demanded, we know that the sign
01741     // bit is demanded. Temporarily set this bit in the mask for our callee.
01742     if (NewBits.getBoolValue())
01743       InMask |= InSignBit;
01744 
01745     KnownZero.trunc(InBits);
01746     KnownOne.trunc(InBits);
01747     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
01748 
01749     // Note if the sign bit is known to be zero or one.
01750     bool SignBitKnownZero = KnownZero.isNegative();
01751     bool SignBitKnownOne  = KnownOne.isNegative();
01752     assert(!(SignBitKnownZero && SignBitKnownOne) &&
01753            "Sign bit can't be known to be both zero and one!");
01754 
01755     // If the sign bit wasn't actually demanded by our caller, we don't
01756     // want it set in the KnownZero and KnownOne result values. Reset the
01757     // mask and reapply it to the result values.
01758     InMask = Mask;
01759     InMask.trunc(InBits);
01760     KnownZero &= InMask;
01761     KnownOne  &= InMask;
01762 
01763     KnownZero.zext(BitWidth);
01764     KnownOne.zext(BitWidth);
01765 
01766     // If the sign bit is known zero or one, the top bits match.
01767     if (SignBitKnownZero)
01768       KnownZero |= NewBits;
01769     else if (SignBitKnownOne)
01770       KnownOne  |= NewBits;
01771     return;
01772   }
01773   case ISD::ANY_EXTEND: {
01774     MVT InVT = Op.getOperand(0).getValueType();
01775     unsigned InBits = InVT.getSizeInBits();
01776     APInt InMask = Mask;
01777     InMask.trunc(InBits);
01778     KnownZero.trunc(InBits);
01779     KnownOne.trunc(InBits);
01780     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
01781     KnownZero.zext(BitWidth);
01782     KnownOne.zext(BitWidth);
01783     return;
01784   }
01785   case ISD::TRUNCATE: {
01786     MVT InVT = Op.getOperand(0).getValueType();
01787     unsigned InBits = InVT.getSizeInBits();
01788     APInt InMask = Mask;
01789     InMask.zext(InBits);
01790     KnownZero.zext(InBits);
01791     KnownOne.zext(InBits);
01792     ComputeMaskedBits(Op.getOperand(0), InMask, KnownZero, KnownOne, Depth+1);
01793     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?"); 
01794     KnownZero.trunc(BitWidth);
01795     KnownOne.trunc(BitWidth);
01796     break;
01797   }
01798   case ISD::AssertZext: {
01799     MVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
01800     APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
01801     ComputeMaskedBits(Op.getOperand(0), Mask & InMask, KnownZero, 
01802                       KnownOne, Depth+1);
01803     KnownZero |= (~InMask) & Mask;
01804     return;
01805   }
01806   case ISD::FGETSIGN:
01807     // All bits are zero except the low bit.
01808     KnownZero = APInt::getHighBitsSet(BitWidth, BitWidth - 1);
01809     return;
01810   
01811   case ISD::SUB: {
01812     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0))) {
01813       // We know that the top bits of C-X are clear if X contains less bits
01814       // than C (i.e. no wrap-around can happen).  For example, 20-X is
01815       // positive if we can prove that X is >= 0 and < 16.
01816       if (CLHS->getAPIntValue().isNonNegative()) {
01817         unsigned NLZ = (CLHS->getAPIntValue()+1).countLeadingZeros();
01818         // NLZ can't be BitWidth with no sign bit
01819         APInt MaskV = APInt::getHighBitsSet(BitWidth, NLZ+1);
01820         ComputeMaskedBits(Op.getOperand(1), MaskV, KnownZero2, KnownOne2,
01821                           Depth+1);
01822 
01823         // If all of the MaskV bits are known to be zero, then we know the
01824         // output top bits are zero, because we now know that the output is
01825         // from [0-C].
01826         if ((KnownZero2 & MaskV) == MaskV) {
01827           unsigned NLZ2 = CLHS->getAPIntValue().countLeadingZeros();
01828           // Top bits known zero.
01829           KnownZero = APInt::getHighBitsSet(BitWidth, NLZ2) & Mask;
01830         }
01831       }
01832     }
01833   }
01834   // fall through
01835   case ISD::ADD: {
01836     // Output known-0 bits are known if clear or set in both the low clear bits
01837     // common to both LHS & RHS.  For example, 8+(X<<3) is known to have the
01838     // low 3 bits clear.
01839     APInt Mask2 = APInt::getLowBitsSet(BitWidth, Mask.countTrailingOnes());
01840     ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero2, KnownOne2, Depth+1);
01841     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01842     unsigned KnownZeroOut = KnownZero2.countTrailingOnes();
01843 
01844     ComputeMaskedBits(Op.getOperand(1), Mask2, KnownZero2, KnownOne2, Depth+1);
01845     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?"); 
01846     KnownZeroOut = std::min(KnownZeroOut,
01847                             KnownZero2.countTrailingOnes());
01848 
01849     KnownZero |= APInt::getLowBitsSet(BitWidth, KnownZeroOut);
01850     return;
01851   }
01852   case ISD::SREM:
01853     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01854       const APInt &RA = Rem->getAPIntValue();
01855       if (RA.isPowerOf2() || (-RA).isPowerOf2()) {
01856         APInt LowBits = RA.isStrictlyPositive() ? (RA - 1) : ~RA;
01857         APInt Mask2 = LowBits | APInt::getSignBit(BitWidth);
01858         ComputeMaskedBits(Op.getOperand(0), Mask2,KnownZero2,KnownOne2,Depth+1);
01859 
01860         // If the sign bit of the first operand is zero, the sign bit of
01861         // the result is zero. If the first operand has no one bits below
01862         // the second operand's single 1 bit, its sign will be zero.
01863         if (KnownZero2[BitWidth-1] || ((KnownZero2 & LowBits) == LowBits))
01864           KnownZero2 |= ~LowBits;
01865 
01866         KnownZero |= KnownZero2 & Mask;
01867 
01868         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
01869       }
01870     }
01871     return;
01872   case ISD::UREM: {
01873     if (ConstantSDNode *Rem = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01874       const APInt &RA = Rem->getAPIntValue();
01875       if (RA.isPowerOf2()) {
01876         APInt LowBits = (RA - 1);
01877         APInt Mask2 = LowBits & Mask;
01878         KnownZero |= ~LowBits & Mask;
01879         ComputeMaskedBits(Op.getOperand(0), Mask2, KnownZero, KnownOne,Depth+1);
01880         assert((KnownZero & KnownOne) == 0&&"Bits known to be one AND zero?");
01881         break;
01882       }
01883     }
01884 
01885     // Since the result is less than or equal to either operand, any leading
01886     // zero bits in either operand must also exist in the result.
01887     APInt AllOnes = APInt::getAllOnesValue(BitWidth);
01888     ComputeMaskedBits(Op.getOperand(0), AllOnes, KnownZero, KnownOne,
01889                       Depth+1);
01890     ComputeMaskedBits(Op.getOperand(1), AllOnes, KnownZero2, KnownOne2,
01891                       Depth+1);
01892 
01893     uint32_t Leaders = std::max(KnownZero.countLeadingOnes(),
01894                                 KnownZero2.countLeadingOnes());
01895     KnownOne.clear();
01896     KnownZero = APInt::getHighBitsSet(BitWidth, Leaders) & Mask;
01897     return;
01898   }
01899   default:
01900     // Allow the target to implement this method for its nodes.
01901     if (Op.getOpcode() >= ISD::BUILTIN_OP_END) {
01902   case ISD::INTRINSIC_WO_CHAIN:
01903   case ISD::INTRINSIC_W_CHAIN:
01904   case ISD::INTRINSIC_VOID:
01905       TLI.computeMaskedBitsForTargetNode(Op, Mask, KnownZero, KnownOne, *this);
01906     }
01907     return;
01908   }
01909 }
01910 
01911 /// ComputeNumSignBits - Return the number of times the sign bit of the
01912 /// register is replicated into the other bits.  We know that at least 1 bit
01913 /// is always equal to the sign bit (itself), but other cases can give us
01914 /// information.  For example, immediately after an "SRA X, 2", we know that
01915 /// the top 3 bits are all equal to each other, so we return 3.
01916 unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const{
01917   MVT VT = Op.getValueType();
01918   assert(VT.isInteger() && "Invalid VT!");
01919   unsigned VTBits = VT.getSizeInBits();
01920   unsigned Tmp, Tmp2;
01921   unsigned FirstAnswer = 1;
01922   
01923   if (Depth == 6)
01924     return 1;  // Limit search depth.
01925 
01926   switch (Op.getOpcode()) {
01927   default: break;
01928   case ISD::AssertSext:
01929     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
01930     return VTBits-Tmp+1;
01931   case ISD::AssertZext:
01932     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
01933     return VTBits-Tmp;
01934     
01935   case ISD::Constant: {
01936     const APInt &Val = cast<ConstantSDNode>(Op)->getAPIntValue();
01937     // If negative, return # leading ones.
01938     if (Val.isNegative())
01939       return Val.countLeadingOnes();
01940     
01941     // Return # leading zeros.
01942     return Val.countLeadingZeros();
01943   }
01944     
01945   case ISD::SIGN_EXTEND:
01946     Tmp = VTBits-Op.getOperand(0).getValueType().getSizeInBits();
01947     return ComputeNumSignBits(Op.getOperand(0), Depth+1) + Tmp;
01948     
01949   case ISD::SIGN_EXTEND_INREG:
01950     // Max of the input and what this extends.
01951     Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
01952     Tmp = VTBits-Tmp+1;
01953     
01954     Tmp2 = ComputeNumSignBits(Op.getOperand(0), Depth+1);
01955     return std::max(Tmp, Tmp2);
01956 
01957   case ISD::SRA:
01958     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
01959     // SRA X, C   -> adds C sign bits.
01960     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01961       Tmp += C->getZExtValue();
01962       if (Tmp > VTBits) Tmp = VTBits;
01963     }
01964     return Tmp;
01965   case ISD::SHL:
01966     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
01967       // shl destroys sign bits.
01968       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
01969       if (C->getZExtValue() >= VTBits ||      // Bad shift.
01970           C->getZExtValue() >= Tmp) break;    // Shifted all sign bits out.
01971       return Tmp - C->getZExtValue();
01972     }
01973     break;
01974   case ISD::AND:
01975   case ISD::OR:
01976   case ISD::XOR:    // NOT is handled here.
01977     // Logical binary ops preserve the number of sign bits at the worst.
01978     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
01979     if (Tmp != 1) {
01980       Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
01981       FirstAnswer = std::min(Tmp, Tmp2);
01982       // We computed what we know about the sign bits as our first
01983       // answer. Now proceed to the generic code that uses
01984       // ComputeMaskedBits, and pick whichever answer is better.
01985     }
01986     break;
01987 
01988   case ISD::SELECT:
01989     Tmp = ComputeNumSignBits(Op.getOperand(1), Depth+1);
01990     if (Tmp == 1) return 1;  // Early out.
01991     Tmp2 = ComputeNumSignBits(Op.getOperand(2), Depth+1);
01992     return std::min(Tmp, Tmp2);
01993 
01994   case ISD::SADDO:
01995   case ISD::UADDO:
01996   case ISD::SSUBO:
01997   case ISD::USUBO:
01998   case ISD::SMULO:
01999   case ISD::UMULO:
02000     if (Op.getResNo() != 1)
02001       break;
02002     // The boolean result conforms to getBooleanContents.  Fall through.
02003   case ISD::SETCC:
02004     // If setcc returns 0/-1, all bits are sign bits.
02005     if (TLI.getBooleanContents() ==
02006         TargetLowering::ZeroOrNegativeOneBooleanContent)
02007       return VTBits;
02008     break;
02009   case ISD::ROTL:
02010   case ISD::ROTR:
02011     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
02012       unsigned RotAmt = C->getZExtValue() & (VTBits-1);
02013       
02014       // Handle rotate right by N like a rotate left by 32-N.
02015       if (Op.getOpcode() == ISD::ROTR)
02016         RotAmt = (VTBits-RotAmt) & (VTBits-1);
02017 
02018       // If we aren't rotating out all of the known-in sign bits, return the
02019       // number that are left.  This handles rotl(sext(x), 1) for example.
02020       Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
02021       if (Tmp > RotAmt+1) return Tmp-RotAmt;
02022     }
02023     break;
02024   case ISD::ADD:
02025     // Add can have at most one carry bit.  Thus we know that the output
02026     // is, at worst, one more bit than the inputs.
02027     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
02028     if (Tmp == 1) return 1;  // Early out.
02029       
02030     // Special case decrementing a value (ADD X, -1):
02031     if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
02032       if (CRHS->isAllOnesValue()) {
02033         APInt KnownZero, KnownOne;
02034         APInt Mask = APInt::getAllOnesValue(VTBits);
02035         ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero, KnownOne, Depth+1);
02036         
02037         // If the input is known to be 0 or 1, the output is 0/-1, which is all
02038         // sign bits set.
02039         if ((KnownZero | APInt(VTBits, 1)) == Mask)
02040           return VTBits;
02041         
02042         // If we are subtracting one from a positive number, there is no carry
02043         // out of the result.
02044         if (KnownZero.isNegative())
02045           return Tmp;
02046       }
02047       
02048     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
02049     if (Tmp2 == 1) return 1;
02050       return std::min(Tmp, Tmp2)-1;
02051     break;
02052     
02053   case ISD::SUB:
02054     Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
02055     if (Tmp2 == 1) return 1;
02056       
02057     // Handle NEG.
02058     if (ConstantSDNode *CLHS = dyn_cast<ConstantSDNode>(Op.getOperand(0)))
02059       if (CLHS->isNullValue()) {
02060         APInt KnownZero, KnownOne;
02061         APInt Mask = APInt::getAllOnesValue(VTBits);
02062         ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne, Depth+1);
02063         // If the input is known to be 0 or 1, the output is 0/-1, which is all
02064         // sign bits set.
02065         if ((KnownZero | APInt(VTBits, 1)) == Mask)
02066           return VTBits;
02067         
02068         // If the input is known to be positive (the sign bit is known clear),
02069         // the output of the NEG has the same number of sign bits as the input.
02070         if (KnownZero.isNegative())
02071           return Tmp2;
02072         
02073         // Otherwise, we treat this like a SUB.
02074       }
02075     
02076     // Sub can have at most one carry bit.  Thus we know that the output
02077     // is, at worst, one more bit than the inputs.
02078     Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
02079     if (Tmp == 1) return 1;  // Early out.
02080       return std::min(Tmp, Tmp2)-1;
02081     break;
02082   case ISD::TRUNCATE:
02083     // FIXME: it's tricky to do anything useful for this, but it is an important
02084     // case for targets like X86.
02085     break;
02086   }
02087   
02088   // Handle LOADX separately here. EXTLOAD case will fallthrough.
02089   if (Op.getOpcode() == ISD::LOAD) {
02090     LoadSDNode *LD = cast<LoadSDNode>(Op);
02091     unsigned ExtType = LD->getExtensionType();
02092     switch (ExtType) {
02093     default: break;
02094     case ISD::SEXTLOAD:    // '17' bits known
02095       Tmp = LD->getMemoryVT().getSizeInBits();
02096       return VTBits-Tmp+1;
02097     case ISD::ZEXTLOAD:    // '16' bits known
02098       Tmp = LD->getMemoryVT().getSizeInBits();
02099       return VTBits-Tmp;
02100     }
02101   }
02102 
02103   // Allow the target to implement this method for its nodes.
02104   if (Op.getOpcode() >= ISD::BUILTIN_OP_END ||
02105       Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN || 
02106       Op.getOpcode() == ISD::INTRINSIC_W_CHAIN ||
02107       Op.getOpcode() == ISD::INTRINSIC_VOID) {
02108     unsigned NumBits = TLI.ComputeNumSignBitsForTargetNode(Op, Depth);
02109     if (NumBits > 1) FirstAnswer = std::max(FirstAnswer, NumBits);
02110   }
02111   
02112   // Finally, if we can prove that the top bits of the result are 0's or 1's,
02113   // use this information.
02114   APInt KnownZero, KnownOne;
02115   APInt Mask = APInt::getAllOnesValue(VTBits);
02116   ComputeMaskedBits(Op, Mask, KnownZero, KnownOne, Depth);
02117   
02118   if (KnownZero.isNegative()) {        // sign bit is 0
02119     Mask = KnownZero;
02120   } else if (KnownOne.isNegative()) {  // sign bit is 1;
02121     Mask = KnownOne;
02122   } else {
02123     // Nothing known.
02124     return FirstAnswer;
02125   }
02126   
02127   // Okay, we know that the sign bit in Mask is set.  Use CLZ to determine
02128   // the number of identical bits in the top of the input value.
02129   Mask = ~Mask;
02130   Mask <<= Mask.getBitWidth()-VTBits;
02131   // Return # leading zeros.  We use 'min' here in case Val was zero before
02132   // shifting.  We don't want to return '64' as for an i32 "0".
02133   return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
02134 }
02135 
02136 
02137 bool SelectionDAG::isVerifiedDebugInfoDesc(SDValue Op) const {
02138   GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op);
02139   if (!GA) return false;
02140   if (GA->getOffset() != 0) return false;
02141   GlobalVariable *GV = dyn_cast<GlobalVariable>(GA->getGlobal());
02142   if (!GV) return false;
02143   MachineModuleInfo *MMI = getMachineModuleInfo();
02144   return MMI && MMI->hasDebugInfo();
02145 }
02146 
02147 
02148 /// getShuffleScalarElt - Returns the scalar element that will make up the ith
02149 /// element of the result of the vector shuffle.
02150 SDValue SelectionDAG::getShuffleScalarElt(const SDNode *N, unsigned i) {
02151   MVT VT = N->getValueType(0);
02152   DebugLoc dl = N->getDebugLoc();
02153   SDValue PermMask = N->getOperand(2);
02154   SDValue Idx = PermMask.getOperand(i);
02155   if (Idx.getOpcode() == ISD::UNDEF)
02156     return getNode(ISD::UNDEF, dl, VT.getVectorElementType());
02157   unsigned Index = cast<ConstantSDNode>(Idx)->getZExtValue();
02158   unsigned NumElems = PermMask.getNumOperands();
02159   SDValue V = (Index < NumElems) ? N->getOperand(0) : N->getOperand(1);
02160   Index %= NumElems;
02161 
02162   if (V.getOpcode() == ISD::BIT_CONVERT) {
02163     V = V.getOperand(0);
02164     MVT VVT = V.getValueType();
02165     if (!VVT.isVector() || VVT.getVectorNumElements() != NumElems)
02166       return SDValue();
02167   }
02168   if (V.getOpcode() == ISD::SCALAR_TO_VECTOR)
02169     return (Index == 0) ? V.getOperand(0)
02170                       : getNode(ISD::UNDEF, dl, VT.getVectorElementType());
02171   if (V.getOpcode() == ISD::BUILD_VECTOR)
02172     return V.getOperand(Index);
02173   if (V.getOpcode() == ISD::VECTOR_SHUFFLE)
02174     return getShuffleScalarElt(V.getNode(), Index);
02175   return SDValue();
02176 }
02177 
02178 
02179 /// getNode - Gets or creates the specified node.
02180 ///
02181 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT) {
02182   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT);
02183 }
02184 
02185 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT) {
02186   FoldingSetNodeID ID;
02187   AddNodeIDNode(ID, Opcode, getVTList(VT), 0, 0);
02188   void *IP = 0;
02189   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
02190     return SDValue(E, 0);
02191   SDNode *N = NodeAllocator.Allocate<SDNode>();
02192   new (N) SDNode(Opcode, DL, SDNode::getSDVTList(VT));
02193   CSEMap.InsertNode(N, IP);
02194   
02195   AllNodes.push_back(N);
02196 #ifndef NDEBUG
02197   VerifyNode(N);
02198 #endif
02199   return SDValue(N, 0);
02200 }
02201 
02202 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT, SDValue Operand) {
02203   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Operand);
02204 }
02205 
02206 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
02207                               MVT VT, SDValue Operand) {
02208   // Constant fold unary operations with an integer constant operand.
02209   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand.getNode())) {
02210     const APInt &Val = C->getAPIntValue();
02211     unsigned BitWidth = VT.getSizeInBits();
02212     switch (Opcode) {
02213     default: break;
02214     case ISD::SIGN_EXTEND:
02215       return getConstant(APInt(Val).sextOrTrunc(BitWidth), VT);
02216     case ISD::ANY_EXTEND:
02217     case ISD::ZERO_EXTEND:
02218     case ISD::TRUNCATE:
02219       return getConstant(APInt(Val).zextOrTrunc(BitWidth), VT);
02220     case ISD::UINT_TO_FP:
02221     case ISD::SINT_TO_FP: {
02222       const uint64_t zero[] = {0, 0};
02223       // No compile time operations on this type.
02224       if (VT==MVT::ppcf128)
02225         break;
02226       APFloat apf = APFloat(APInt(BitWidth, 2, zero));
02227       (void)apf.convertFromAPInt(Val, 
02228                                  Opcode==ISD::SINT_TO_FP,
02229                                  APFloat::rmNearestTiesToEven);
02230       return getConstantFP(apf, VT);
02231     }
02232     case ISD::BIT_CONVERT:
02233       if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
02234         return getConstantFP(Val.bitsToFloat(), VT);
02235       else if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
02236         return getConstantFP(Val.bitsToDouble(), VT);
02237       break;
02238     case ISD::BSWAP:
02239       return getConstant(Val.byteSwap(), VT);
02240     case ISD::CTPOP:
02241       return getConstant(Val.countPopulation(), VT);
02242     case ISD::CTLZ:
02243       return getConstant(Val.countLeadingZeros(), VT);
02244     case ISD::CTTZ:
02245       return getConstant(Val.countTrailingZeros(), VT);
02246     }
02247   }
02248 
02249   // Constant fold unary operations with a floating point constant operand.
02250   if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand.getNode())) {
02251     APFloat V = C->getValueAPF();    // make copy
02252     if (VT != MVT::ppcf128 && Operand.getValueType() != MVT::ppcf128) {
02253       switch (Opcode) {
02254       case ISD::FNEG:
02255         V.changeSign();
02256         return getConstantFP(V, VT);
02257       case ISD::FABS:
02258         V.clearSign();
02259         return getConstantFP(V, VT);
02260       case ISD::FP_ROUND:
02261       case ISD::FP_EXTEND: {
02262         bool ignored;
02263         // This can return overflow, underflow, or inexact; we don't care.
02264         // FIXME need to be more flexible about rounding mode.
02265         (void)V.convert(*MVTToAPFloatSemantics(VT),
02266                         APFloat::rmNearestTiesToEven, &ignored);
02267         return getConstantFP(V, VT);
02268       }
02269       case ISD::FP_TO_SINT:
02270       case ISD::FP_TO_UINT: {
02271         integerPart x;
02272         bool ignored;
02273         assert(integerPartWidth >= 64);
02274         // FIXME need to be more flexible about rounding mode.
02275         APFloat::opStatus s = V.convertToInteger(&x, 64U,
02276                               Opcode==ISD::FP_TO_SINT,
02277                               APFloat::rmTowardZero, &ignored);
02278         if (s==APFloat::opInvalidOp)     // inexact is OK, in fact usual
02279           break;
02280         return getConstant(x, VT);
02281       }
02282       case ISD::BIT_CONVERT:
02283         if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
02284           return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), VT);
02285         else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
02286           return getConstant(V.bitcastToAPInt().getZExtValue(), VT);
02287         break;
02288       }
02289     }
02290   }
02291 
02292   unsigned OpOpcode = Operand.getNode()->getOpcode();
02293   switch (Opcode) {
02294   case ISD::TokenFactor:
02295   case ISD::MERGE_VALUES:
02296   case ISD::CONCAT_VECTORS:
02297     return Operand;         // Factor, merge or concat of one node?  No need.
02298   case ISD::FP_ROUND: assert(0 && "Invalid method to make FP_ROUND node");
02299   case ISD::FP_EXTEND:
02300     assert(VT.isFloatingPoint() &&
02301            Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
02302     if (Operand.getValueType() == VT) return Operand;  // noop conversion.
02303     if (Operand.getOpcode() == ISD::UNDEF)
02304       return getNode(ISD::UNDEF, DL, VT);
02305     break;
02306   case ISD::SIGN_EXTEND:
02307     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
02308            "Invalid SIGN_EXTEND!");
02309     if (Operand.getValueType() == VT) return Operand;   // noop extension
02310     assert(Operand.getValueType().bitsLT(VT)
02311            && "Invalid sext node, dst < src!");
02312     if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
02313       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
02314     break;
02315   case ISD::ZERO_EXTEND:
02316     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
02317            "Invalid ZERO_EXTEND!");
02318     if (Operand.getValueType() == VT) return Operand;   // noop extension
02319     assert(Operand.getValueType().bitsLT(VT)
02320            && "Invalid zext node, dst < src!");
02321     if (OpOpcode == ISD::ZERO_EXTEND)   // (zext (zext x)) -> (zext x)
02322       return getNode(ISD::ZERO_EXTEND, DL, VT, 
02323                      Operand.getNode()->getOperand(0));
02324     break;
02325   case ISD::ANY_EXTEND:
02326     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
02327            "Invalid ANY_EXTEND!");
02328     if (Operand.getValueType() == VT) return Operand;   // noop extension
02329     assert(Operand.getValueType().bitsLT(VT)
02330            && "Invalid anyext node, dst < src!");
02331     if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND)
02332       // (ext (zext x)) -> (zext x)  and  (ext (sext x)) -> (sext x)
02333       return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
02334     break;
02335   case ISD::TRUNCATE:
02336     assert(VT.isInteger() && Operand.getValueType().isInteger() &&
02337            "Invalid TRUNCATE!");
02338     if (Operand.getValueType() == VT) return Operand;   // noop truncate
02339     assert(Operand.getValueType().bitsGT(VT)
02340            && "Invalid truncate node, src < dst!");
02341     if (OpOpcode == ISD::TRUNCATE)
02342       return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
02343     else if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
02344              OpOpcode == ISD::ANY_EXTEND) {
02345       // If the source is smaller than the dest, we still need an extend.
02346       if (Operand.getNode()->getOperand(0).getValueType().bitsLT(VT))
02347         return getNode(OpOpcode, DL, VT, Operand.getNode()->getOperand(0));
02348       else if (Operand.getNode()->getOperand(0).getValueType().bitsGT(VT))
02349         return getNode(ISD::TRUNCATE, DL, VT, Operand.getNode()->getOperand(0));
02350       else
02351         return Operand.getNode()->getOperand(0);
02352     }
02353     break;
02354   case ISD::BIT_CONVERT:
02355     // Basic sanity checking.
02356     assert(VT.getSizeInBits() == Operand.getValueType().getSizeInBits()
02357            && "Cannot BIT_CONVERT between types of different sizes!");
02358     if (VT == Operand.getValueType()) return Operand;  // noop conversion.
02359     if (OpOpcode == ISD::BIT_CONVERT)  // bitconv(bitconv(x)) -> bitconv(x)
02360       return getNode(ISD::BIT_CONVERT, DL, VT, Operand.getOperand(0));
02361     if (OpOpcode == ISD::UNDEF)
02362       return getNode(ISD::UNDEF, DL, VT);
02363     break;
02364   case ISD::SCALAR_TO_VECTOR:
02365     assert(VT.isVector() && !Operand.getValueType().isVector() &&
02366            VT.getVectorElementType() == Operand.getValueType() &&
02367            "Illegal SCALAR_TO_VECTOR node!");
02368     if (OpOpcode == ISD::UNDEF)
02369       return getNode(ISD::UNDEF, DL, VT);
02370     // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
02371     if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
02372         isa<ConstantSDNode>(Operand.getOperand(1)) &&
02373         Operand.getConstantOperandVal(1) == 0 &&
02374         Operand.getOperand(0).getValueType() == VT)
02375       return Operand.getOperand(0);
02376     break;
02377   case ISD::FNEG:
02378     // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
02379     if (UnsafeFPMath && OpOpcode == ISD::FSUB)
02380       return getNode(ISD::FSUB, DL, VT, Operand.getNode()->getOperand(1),
02381                      Operand.getNode()->getOperand(0));
02382     if (OpOpcode == ISD::FNEG)  // --X -> X
02383       return Operand.getNode()->getOperand(0);
02384     break;
02385   case ISD::FABS:
02386     if (OpOpcode == ISD::FNEG)  // abs(-X) -> abs(X)
02387       return getNode(ISD::FABS, DL, VT, Operand.getNode()->getOperand(0));
02388     break;
02389   }
02390 
02391   SDNode *N;
02392   SDVTList VTs = getVTList(VT);
02393   if (VT != MVT::Flag) { // Don't CSE flag producing nodes
02394     FoldingSetNodeID ID;
02395     SDValue Ops[1] = { Operand };
02396     AddNodeIDNode(ID, Opcode, VTs, Ops, 1);
02397     void *IP = 0;
02398     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
02399       return SDValue(E, 0);
02400     N = NodeAllocator.Allocate<UnarySDNode>();
02401     new (N) UnarySDNode(Opcode, DL, VTs, Operand);
02402     CSEMap.InsertNode(N, IP);
02403   } else {
02404     N = NodeAllocator.Allocate<UnarySDNode>();
02405     new (N) UnarySDNode(Opcode, DL, VTs, Operand);
02406   }
02407 
02408   AllNodes.push_back(N);
02409 #ifndef NDEBUG
02410   VerifyNode(N);
02411 #endif
02412   return SDValue(N, 0);
02413 }
02414 
02415 SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode,
02416                                              MVT VT,
02417                                              ConstantSDNode *Cst1,
02418                                              ConstantSDNode *Cst2) {
02419   const APInt &C1 = Cst1->getAPIntValue(), &C2 = Cst2->getAPIntValue();
02420 
02421   switch (Opcode) {
02422   case ISD::ADD:  return getConstant(C1 + C2, VT);
02423   case ISD::SUB:  return getConstant(C1 - C2, VT);
02424   case ISD::MUL:  return getConstant(C1 * C2, VT);
02425   case ISD::UDIV:
02426     if (C2.getBoolValue()) return getConstant(C1.udiv(C2), VT);
02427     break;
02428   case ISD::UREM:
02429     if (C2.getBoolValue()) return getConstant(C1.urem(C2), VT);
02430     break;
02431   case ISD::SDIV:
02432     if (C2.getBoolValue()) return getConstant(C1.sdiv(C2), VT);
02433     break;
02434   case ISD::SREM:
02435     if (C2.getBoolValue()) return getConstant(C1.srem(C2), VT);
02436     break;
02437   case ISD::AND:  return getConstant(C1 & C2, VT);
02438   case ISD::OR:   return getConstant(C1 | C2, VT);
02439   case ISD::XOR:  return getConstant(C1 ^ C2, VT);
02440   case ISD::SHL:  return getConstant(C1 << C2, VT);
02441   case ISD::SRL:  return getConstant(C1.lshr(C2), VT);
02442   case ISD::SRA:  return getConstant(C1.ashr(C2), VT);
02443   case ISD::ROTL: return getConstant(C1.rotl(C2), VT);
02444   case ISD::ROTR: return getConstant(C1.rotr(C2), VT);
02445   default: break;
02446   }
02447 
02448   return SDValue();
02449 }
02450 
02451 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
02452                               SDValue N1, SDValue N2) {
02453   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2);
02454 }
02455 
02456 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
02457                               SDValue N1, SDValue N2) {
02458   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
02459   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
02460   switch (Opcode) {
02461   default: break;
02462   case ISD::TokenFactor:
02463     assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
02464            N2.getValueType() == MVT::Other && "Invalid token factor!");
02465     // Fold trivial token factors.
02466     if (N1.getOpcode() == ISD::EntryToken) return N2;
02467     if (N2.getOpcode() == ISD::EntryToken) return N1;
02468     if (N1 == N2) return N1;
02469     break;
02470   case ISD::CONCAT_VECTORS:
02471     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
02472     // one big BUILD_VECTOR.
02473     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
02474         N2.getOpcode() == ISD::BUILD_VECTOR) {
02475       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
02476       Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
02477       return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
02478     }
02479     break;
02480   case ISD::AND:
02481     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
02482            N1.getValueType() == VT && "Binary operator types must match!");
02483     // (X & 0) -> 0.  This commonly occurs when legalizing i64 values, so it's
02484     // worth handling here.
02485     if (N2C && N2C->isNullValue())
02486       return N2;
02487     if (N2C && N2C->isAllOnesValue())  // X & -1 -> X
02488       return N1;
02489     break;
02490   case ISD::OR:
02491   case ISD::XOR:
02492   case ISD::ADD:
02493   case ISD::SUB:
02494     assert(VT.isInteger() && N1.getValueType() == N2.getValueType() &&
02495            N1.getValueType() == VT && "Binary operator types must match!");
02496     // (X ^|+- 0) -> X.  This commonly occurs when legalizing i64 values, so
02497     // it's worth handling here.
02498     if (N2C && N2C->isNullValue())
02499       return N1;
02500     break;
02501   case ISD::UDIV:
02502   case ISD::UREM:
02503   case ISD::MULHU:
02504   case ISD::MULHS:
02505   case ISD::MUL:
02506   case ISD::SDIV:
02507   case ISD::SREM:
02508     assert(VT.isInteger() && "This operator does not apply to FP types!");
02509     // fall through
02510   case ISD::FADD:
02511   case ISD::FSUB:
02512   case ISD::FMUL:
02513   case ISD::FDIV:
02514   case ISD::FREM:
02515     if (UnsafeFPMath) {
02516       if (Opcode == ISD::FADD) {
02517         // 0+x --> x
02518         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1))
02519           if (CFP->getValueAPF().isZero())
02520             return N2;
02521         // x+0 --> x
02522         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
02523           if (CFP->getValueAPF().isZero())
02524             return N1;
02525       } else if (Opcode == ISD::FSUB) {
02526         // x-0 --> x
02527         if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N2))
02528           if (CFP->getValueAPF().isZero())
02529             return N1;
02530       }
02531     }
02532     assert(N1.getValueType() == N2.getValueType() &&
02533            N1.getValueType() == VT && "Binary operator types must match!");
02534     break;
02535   case ISD::FCOPYSIGN:   // N1 and result must match.  N1/N2 need not match.
02536     assert(N1.getValueType() == VT &&
02537            N1.getValueType().isFloatingPoint() &&
02538            N2.getValueType().isFloatingPoint() &&
02539            "Invalid FCOPYSIGN!");
02540     break;
02541   case ISD::SHL:
02542   case ISD::SRA:
02543   case ISD::SRL:
02544   case ISD::ROTL:
02545   case ISD::ROTR:
02546     assert(VT == N1.getValueType() &&
02547            "Shift operators return type must be the same as their first arg");
02548     assert(VT.isInteger() && N2.getValueType().isInteger() &&
02549            "Shifts only work on integers");
02550 
02551     // Always fold shifts of i1 values so the code generator doesn't need to
02552     // handle them.  Since we know the size of the shift has to be less than the
02553     // size of the value, the shift/rotate count is guaranteed to be zero.
02554     if (VT == MVT::i1)
02555       return N1;
02556     break;
02557   case ISD::FP_ROUND_INREG: {
02558     MVT EVT = cast<VTSDNode>(N2)->getVT();
02559     assert(VT == N1.getValueType() && "Not an inreg round!");
02560     assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
02561            "Cannot FP_ROUND_INREG integer types");
02562     assert(EVT.bitsLE(VT) && "Not rounding down!");
02563     if (cast<VTSDNode>(N2)->getVT() == VT) return N1;  // Not actually rounding.
02564     break;
02565   }
02566   case ISD::FP_ROUND:
02567     assert(VT.isFloatingPoint() &&
02568            N1.getValueType().isFloatingPoint() &&
02569            VT.bitsLE(N1.getValueType()) &&
02570            isa<ConstantSDNode>(N2) && "Invalid FP_ROUND!");
02571     if (N1.getValueType() == VT) return N1;  // noop conversion.
02572     break;
02573   case ISD::AssertSext:
02574   case ISD::AssertZext: {
02575     MVT EVT = cast<VTSDNode>(N2)->getVT();
02576     assert(VT == N1.getValueType() && "Not an inreg extend!");
02577     assert(VT.isInteger() && EVT.isInteger() &&
02578            "Cannot *_EXTEND_INREG FP types");
02579     assert(EVT.bitsLE(VT) && "Not extending!");
02580     if (VT == EVT) return N1; // noop assertion.
02581     break;
02582   }
02583   case ISD::SIGN_EXTEND_INREG: {
02584     MVT EVT = cast<VTSDNode>(N2)->getVT();
02585     assert(VT == N1.getValueType() && "Not an inreg extend!");
02586     assert(VT.isInteger() && EVT.isInteger() &&
02587            "Cannot *_EXTEND_INREG FP types");
02588     assert(EVT.bitsLE(VT) && "Not extending!");
02589     if (EVT == VT) return N1;  // Not actually extending
02590 
02591     if (N1C) {
02592       APInt Val = N1C->getAPIntValue();
02593       unsigned FromBits = cast<VTSDNode>(N2)->getVT().getSizeInBits();
02594       Val <<= Val.getBitWidth()-FromBits;
02595       Val = Val.ashr(Val.getBitWidth()-FromBits);
02596       return getConstant(Val, VT);
02597     }
02598     break;
02599   }
02600   case ISD::EXTRACT_VECTOR_ELT:
02601     // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
02602     if (N1.getOpcode() == ISD::UNDEF)
02603       return getNode(ISD::UNDEF, DL, VT);
02604       
02605     // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
02606     // expanding copies of large vectors from registers.
02607     if (N2C &&
02608         N1.getOpcode() == ISD::CONCAT_VECTORS &&
02609         N1.getNumOperands() > 0) {
02610       unsigned Factor =
02611         N1.getOperand(0).getValueType().getVectorNumElements();
02612       return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
02613                      N1.getOperand(N2C->getZExtValue() / Factor),
02614                      getConstant(N2C->getZExtValue() % Factor,
02615                                  N2.getValueType()));
02616     }
02617 
02618     // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
02619     // expanding large vector constants.
02620     if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR)
02621       return N1.getOperand(N2C->getZExtValue());
02622       
02623     // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
02624     // operations are lowered to scalars.
02625     if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
02626       // If the indices are the same, return the inserted element.
02627       if (N1.getOperand(2) == N2)
02628         return N1.getOperand(1);
02629       // If the indices are known different, extract the element from
02630       // the original vector.
02631       else if (isa<ConstantSDNode>(N1.getOperand(2)) &&
02632                isa<ConstantSDNode>(N2))
02633         return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
02634     }
02635     break;
02636   case ISD::EXTRACT_ELEMENT:
02637     assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
02638     assert(!N1.getValueType().isVector() && !VT.isVector() &&
02639            (N1.getValueType().isInteger() == VT.isInteger()) &&
02640            "Wrong types for EXTRACT_ELEMENT!");
02641 
02642     // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
02643     // 64-bit integers into 32-bit parts.  Instead of building the extract of
02644     // the BUILD_PAIR, only to have legalize rip it apart, just do it now. 
02645     if (N1.getOpcode() == ISD::BUILD_PAIR)
02646       return N1.getOperand(N2C->getZExtValue());
02647 
02648     // EXTRACT_ELEMENT of a constant int is also very common.
02649     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
02650       unsigned ElementSize = VT.getSizeInBits();
02651       unsigned Shift = ElementSize * N2C->getZExtValue();
02652       APInt ShiftedVal = C->getAPIntValue().lshr(Shift);
02653       return getConstant(ShiftedVal.trunc(ElementSize), VT);
02654     }
02655     break;
02656   case ISD::EXTRACT_SUBVECTOR:
02657     if (N1.getValueType() == VT) // Trivial extraction.
02658       return N1;
02659     break;
02660   }
02661 
02662   if (N1C) {
02663     if (N2C) {
02664       SDValue SV = FoldConstantArithmetic(Opcode, VT, N1C, N2C);
02665       if (SV.getNode()) return SV;
02666     } else {      // Cannonicalize constant to RHS if commutative
02667       if (isCommutativeBinOp(Opcode)) {
02668         std::swap(N1C, N2C);
02669         std::swap(N1, N2);
02670       }
02671     }
02672   }
02673 
02674   // Constant fold FP operations.
02675   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
02676   ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
02677   if (N1CFP) {
02678     if (!N2CFP && isCommutativeBinOp(Opcode)) {
02679       // Cannonicalize constant to RHS if commutative
02680       std::swap(N1CFP, N2CFP);
02681       std::swap(N1, N2);
02682     } else if (N2CFP && VT != MVT::ppcf128) {
02683       APFloat V1 = N1CFP->getValueAPF(), V2 = N2CFP->getValueAPF();
02684       APFloat::opStatus s;
02685       switch (Opcode) {
02686       case ISD::FADD: 
02687         s = V1.add(V2, APFloat::rmNearestTiesToEven);
02688         if (s != APFloat::opInvalidOp)
02689           return getConstantFP(V1, VT);
02690         break;
02691       case ISD::FSUB: 
02692         s = V1.subtract(V2, APFloat::rmNearestTiesToEven);
02693         if (s!=APFloat::opInvalidOp)
02694           return getConstantFP(V1, VT);
02695         break;
02696       case ISD::FMUL:
02697         s = V1.multiply(V2, APFloat::rmNearestTiesToEven);
02698         if (s!=APFloat::opInvalidOp)
02699           return getConstantFP(V1, VT);
02700         break;
02701       case ISD::FDIV:
02702         s = V1.divide(V2, APFloat::rmNearestTiesToEven);
02703         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
02704           return getConstantFP(V1, VT);
02705         break;
02706       case ISD::FREM :
02707         s = V1.mod(V2, APFloat::rmNearestTiesToEven);
02708         if (s!=APFloat::opInvalidOp && s!=APFloat::opDivByZero)
02709           return getConstantFP(V1, VT);
02710         break;
02711       case ISD::FCOPYSIGN:
02712         V1.copySign(V2);
02713         return getConstantFP(V1, VT);
02714       default: break;
02715       }
02716     }
02717   }
02718   
02719   // Canonicalize an UNDEF to the RHS, even over a constant.
02720   if (N1.getOpcode() == ISD::UNDEF) {
02721     if (isCommutativeBinOp(Opcode)) {
02722       std::swap(N1, N2);
02723     } else {
02724       switch (Opcode) {
02725       case ISD::FP_ROUND_INREG:
02726       case ISD::SIGN_EXTEND_INREG:
02727       case ISD::SUB:
02728       case ISD::FSUB:
02729       case ISD::FDIV:
02730       case ISD::FREM:
02731       case ISD::SRA:
02732         return N1;     // fold op(undef, arg2) -> undef
02733       case ISD::UDIV:
02734       case ISD::SDIV:
02735       case ISD::UREM:
02736       case ISD::SREM:
02737       case ISD::SRL:
02738       case ISD::SHL:
02739         if (!VT.isVector())
02740           return getConstant(0, VT);    // fold op(undef, arg2) -> 0
02741         // For vectors, we can't easily build an all zero vector, just return
02742         // the LHS.
02743         return N2;
02744       }
02745     }
02746   }
02747   
02748   // Fold a bunch of operators when the RHS is undef. 
02749   if (N2.getOpcode() == ISD::UNDEF) {
02750     switch (Opcode) {
02751     case ISD::XOR:
02752       if (N1.getOpcode() == ISD::UNDEF)
02753         // Handle undef ^ undef -> 0 special case. This is a common
02754         // idiom (misuse).
02755         return getConstant(0, VT);
02756       // fallthrough
02757     case ISD::ADD:
02758     case ISD::ADDC:
02759     case ISD::ADDE:
02760     case ISD::SUB:
02761     case ISD::FADD:
02762     case ISD::FSUB:
02763     case ISD::FMUL:
02764     case ISD::FDIV:
02765     case ISD::FREM:
02766     case ISD::UDIV:
02767     case ISD::SDIV:
02768     case ISD::UREM:
02769     case ISD::SREM:
02770       return N2;       // fold op(arg1, undef) -> undef
02771     case ISD::MUL: 
02772     case ISD::AND:
02773     case ISD::SRL:
02774     case ISD::SHL:
02775       if (!VT.isVector())
02776         return getConstant(0, VT);  // fold op(arg1, undef) -> 0
02777       // For vectors, we can't easily build an all zero vector, just return
02778       // the LHS.
02779       return N1;
02780     case ISD::OR:
02781       if (!VT.isVector())
02782         return getConstant(APInt::getAllOnesValue(VT.getSizeInBits()), VT);
02783       // For vectors, we can't easily build an all one vector, just return
02784       // the LHS.
02785       return N1;
02786     case ISD::SRA:
02787       return N1;
02788     }
02789   }
02790 
02791   // Memoize this node if possible.
02792   SDNode *N;
02793   SDVTList VTs = getVTList(VT);
02794   if (VT != MVT::Flag) {
02795     SDValue Ops[] = { N1, N2 };
02796     FoldingSetNodeID ID;
02797     AddNodeIDNode(ID, Opcode, VTs, Ops, 2);
02798     void *IP = 0;
02799     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
02800       return SDValue(E, 0);
02801     N = NodeAllocator.Allocate<BinarySDNode>();
02802     new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
02803     CSEMap.InsertNode(N, IP);
02804   } else {
02805     N = NodeAllocator.Allocate<BinarySDNode>();
02806     new (N) BinarySDNode(Opcode, DL, VTs, N1, N2);
02807   }
02808 
02809   AllNodes.push_back(N);
02810 #ifndef NDEBUG
02811   VerifyNode(N);
02812 #endif
02813   return SDValue(N, 0);
02814 }
02815 
02816 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
02817                               SDValue N1, SDValue N2, SDValue N3) {
02818   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3);
02819 }
02820 
02821 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
02822                               SDValue N1, SDValue N2, SDValue N3) {
02823   // Perform various simplifications.
02824   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
02825   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
02826   switch (Opcode) {
02827   case ISD::CONCAT_VECTORS:
02828     // A CONCAT_VECTOR with all operands BUILD_VECTOR can be simplified to
02829     // one big BUILD_VECTOR.
02830     if (N1.getOpcode() == ISD::BUILD_VECTOR &&
02831         N2.getOpcode() == ISD::BUILD_VECTOR &&
02832         N3.getOpcode() == ISD::BUILD_VECTOR) {
02833       SmallVector<SDValue, 16> Elts(N1.getNode()->op_begin(), N1.getNode()->op_end());
02834       Elts.insert(Elts.end(), N2.getNode()->op_begin(), N2.getNode()->op_end());
02835       Elts.insert(Elts.end(), N3.getNode()->op_begin(), N3.getNode()->op_end());
02836       return getNode(ISD::BUILD_VECTOR, DL, VT, &Elts[0], Elts.size());
02837     }
02838     break;
02839   case ISD::SETCC: {
02840     // Use FoldSetCC to simplify SETCC's.
02841     SDValue Simp = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL);
02842     if (Simp.getNode()) return Simp;
02843     break;
02844   }
02845   case ISD::SELECT:
02846     if (N1C) {
02847      if (N1C->getZExtValue())
02848         return N2;             // select true, X, Y -> X
02849       else
02850         return N3;             // select false, X, Y -> Y
02851     }
02852 
02853     if (N2 == N3) return N2;   // select C, X, X -> X
02854     break;
02855   case ISD::BRCOND:
02856     if (N2C) {
02857       if (N2C->getZExtValue()) // Unconditional branch
02858         return getNode(ISD::BR, DL, MVT::Other, N1, N3);
02859       else
02860         return N1;         // Never-taken branch
02861     }
02862     break;
02863   case ISD::VECTOR_SHUFFLE:
02864     assert(N1.getValueType() == N2.getValueType() &&
02865            N1.getValueType().isVector() &&
02866            VT.isVector() && N3.getValueType().isVector() &&
02867            N3.getOpcode() == ISD::BUILD_VECTOR &&
02868            VT.getVectorNumElements() == N3.getNumOperands() &&
02869            "Illegal VECTOR_SHUFFLE node!");
02870     break;
02871   case ISD::BIT_CONVERT:
02872     // Fold bit_convert nodes from a type to themselves.
02873     if (N1.getValueType() == VT)
02874       return N1;
02875     break;
02876   }
02877 
02878   // Memoize node if it doesn't produce a flag.
02879   SDNode *N;
02880   SDVTList VTs = getVTList(VT);
02881   if (VT != MVT::Flag) {
02882     SDValue Ops[] = { N1, N2, N3 };
02883     FoldingSetNodeID ID;
02884     AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
02885     void *IP = 0;
02886     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
02887       return SDValue(E, 0);
02888     N = NodeAllocator.Allocate<TernarySDNode>();
02889     new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
02890     CSEMap.InsertNode(N, IP);
02891   } else {
02892     N = NodeAllocator.Allocate<TernarySDNode>();
02893     new (N) TernarySDNode(Opcode, DL, VTs, N1, N2, N3);
02894   }
02895   AllNodes.push_back(N);
02896 #ifndef NDEBUG
02897   VerifyNode(N);
02898 #endif
02899   return SDValue(N, 0);
02900 }
02901 
02902 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
02903                               SDValue N1, SDValue N2, SDValue N3,
02904                               SDValue N4) {
02905   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4);
02906 }
02907 
02908 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
02909                               SDValue N1, SDValue N2, SDValue N3,
02910                               SDValue N4) {
02911   SDValue Ops[] = { N1, N2, N3, N4 };
02912   return getNode(Opcode, DL, VT, Ops, 4);
02913 }
02914 
02915 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
02916                               SDValue N1, SDValue N2, SDValue N3,
02917                               SDValue N4, SDValue N5) {
02918   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, N1, N2, N3, N4, N5);
02919 }
02920 
02921 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
02922                               SDValue N1, SDValue N2, SDValue N3,
02923                               SDValue N4, SDValue N5) {
02924   SDValue Ops[] = { N1, N2, N3, N4, N5 };
02925   return getNode(Opcode, DL, VT, Ops, 5);
02926 }
02927 
02928 /// getMemsetValue - Vectorized representation of the memset value
02929 /// operand.
02930 static SDValue getMemsetValue(SDValue Value, MVT VT, SelectionDAG &DAG) {
02931   unsigned NumBits = VT.isVector() ?
02932     VT.getVectorElementType().getSizeInBits() : VT.getSizeInBits();
02933   if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
02934     APInt Val = APInt(NumBits, C->getZExtValue() & 255);
02935     unsigned Shift = 8;
02936     for (unsigned i = NumBits; i > 8; i >>= 1) {
02937       Val = (Val << Shift) | Val;
02938       Shift <<= 1;
02939     }
02940     if (VT.isInteger())
02941       return DAG.getConstant(Val, VT);
02942     return DAG.getConstantFP(APFloat(Val), VT);
02943   }
02944 
02945   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
02946   Value = DAG.getNode(ISD::ZERO_EXTEND, VT, Value);
02947   unsigned Shift = 8;
02948   for (unsigned i = NumBits; i > 8; i >>= 1) {
02949     Value = DAG.getNode(ISD::OR, VT,
02950                         DAG.getNode(ISD::SHL, VT, Value,
02951                                     DAG.getConstant(Shift,
02952                                                     TLI.getShiftAmountTy())),
02953                         Value);
02954     Shift <<= 1;
02955   }
02956 
02957   return Value;
02958 }
02959 
02960 /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
02961 /// used when a memcpy is turned into a memset when the source is a constant
02962 /// string ptr.
02963 static SDValue getMemsetStringVal(MVT VT, SelectionDAG &DAG,
02964                                     const TargetLowering &TLI,
02965                                     std::string &Str, unsigned Offset) {
02966   // Handle vector with all elements zero.
02967   if (Str.empty()) {
02968     if (VT.isInteger())
02969       return DAG.getConstant(0, VT);
02970     unsigned NumElts = VT.getVectorNumElements();
02971     MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
02972     return DAG.getNode(ISD::BIT_CONVERT, VT,
02973                        DAG.getConstant(0, MVT::getVectorVT(EltVT, NumElts)));
02974   }
02975 
02976   assert(!VT.isVector() && "Can't handle vector type here!");
02977   unsigned NumBits = VT.getSizeInBits();
02978   unsigned MSB = NumBits / 8;
02979   uint64_t Val = 0;
02980   if (TLI.isLittleEndian())
02981     Offset = Offset + MSB - 1;
02982   for (unsigned i = 0; i != MSB; ++i) {
02983     Val = (Val << 8) | (unsigned char)Str[Offset];
02984     Offset += TLI.isLittleEndian() ? -1 : 1;
02985   }
02986   return DAG.getConstant(Val, VT);
02987 }
02988 
02989 /// getMemBasePlusOffset - Returns base and offset node for the 
02990 ///
02991 static SDValue getMemBasePlusOffset(SDValue Base, unsigned Offset,
02992                                       SelectionDAG &DAG) {
02993   MVT VT = Base.getValueType();
02994   return DAG.getNode(ISD::ADD, Base.getNode()->getDebugLoc(),
02995                      VT, Base, DAG.getConstant(Offset, VT));
02996 }
02997 
02998 /// isMemSrcFromString - Returns true if memcpy source is a string constant.
02999 ///
03000 static bool isMemSrcFromString(SDValue Src, std::string &Str) {
03001   unsigned SrcDelta = 0;
03002   GlobalAddressSDNode *G = NULL;
03003   if (Src.getOpcode() == ISD::GlobalAddress)
03004     G = cast<GlobalAddressSDNode>(Src);
03005   else if (Src.getOpcode() == ISD::ADD &&
03006            Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
03007            Src.getOperand(1).getOpcode() == ISD::Constant) {
03008     G = cast<GlobalAddressSDNode>(Src.getOperand(0));
03009     SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
03010   }
03011   if (!G)
03012     return false;
03013 
03014   GlobalVariable *GV = dyn_cast<GlobalVariable>(G->getGlobal());
03015   if (GV && GetConstantStringInfo(GV, Str, SrcDelta, false))
03016     return true;
03017 
03018   return false;
03019 }
03020 
03021 /// MeetsMaxMemopRequirement - Determines if the number of memory ops required
03022 /// to replace the memset / memcpy is below the threshold. It also returns the
03023 /// types of the sequence of memory ops to perform memset / memcpy.
03024 static
03025 bool MeetsMaxMemopRequirement(std::vector<MVT> &MemOps,
03026                               SDValue Dst, SDValue Src,
03027                               unsigned Limit, uint64_t Size, unsigned &Align,
03028                               std::string &Str, bool &isSrcStr,
03029                               SelectionDAG &DAG,
03030                               const TargetLowering &TLI) {
03031   isSrcStr = isMemSrcFromString(Src, Str);
03032   bool isSrcConst = isa<ConstantSDNode>(Src);
03033   bool AllowUnalign = TLI.allowsUnalignedMemoryAccesses();
03034   MVT VT = TLI.getOptimalMemOpType(Size, Align, isSrcConst, isSrcStr);
03035   if (VT != MVT::iAny) {
03036     unsigned NewAlign = (unsigned)
03037       TLI.getTargetData()->getABITypeAlignment(VT.getTypeForMVT());
03038     // If source is a string constant, this will require an unaligned load.
03039     if (NewAlign > Align && (isSrcConst || AllowUnalign)) {
03040       if (Dst.getOpcode() != ISD::FrameIndex) {
03041         // Can't change destination alignment. It requires a unaligned store.
03042         if (AllowUnalign)
03043           VT = MVT::iAny;
03044       } else {
03045         int FI = cast<FrameIndexSDNode>(Dst)->getIndex();
03046         MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
03047         if (MFI->isFixedObjectIndex(FI)) {
03048           // Can't change destination alignment. It requires a unaligned store.
03049           if (AllowUnalign)
03050             VT = MVT::iAny;
03051         } else {
03052           // Give the stack frame object a larger alignment if needed.
03053           if (MFI->getObjectAlignment(FI) < NewAlign)
03054             MFI->setObjectAlignment(FI, NewAlign);
03055           Align = NewAlign;
03056         }
03057       }
03058     }
03059   }
03060 
03061   if (VT == MVT::iAny) {
03062     if (AllowUnalign) {
03063       VT = MVT::i64;
03064     } else {
03065       switch (Align & 7) {
03066       case 0:  VT = MVT::i64; break;
03067       case 4:  VT = MVT::i32; break;
03068       case 2:  VT = MVT::i16; break;
03069       default: VT = MVT::i8;  break;
03070       }
03071     }
03072 
03073     MVT LVT = MVT::i64;
03074     while (!TLI.isTypeLegal(LVT))
03075       LVT = (MVT::SimpleValueType)(LVT.getSimpleVT() - 1);
03076     assert(LVT.isInteger());
03077 
03078     if (VT.bitsGT(LVT))
03079       VT = LVT;
03080   }
03081 
03082   unsigned NumMemOps = 0;
03083   while (Size != 0) {
03084     unsigned VTSize = VT.getSizeInBits() / 8;
03085     while (VTSize > Size) {
03086       // For now, only use non-vector load / store's for the left-over pieces.
03087       if (VT.isVector()) {
03088         VT = MVT::i64;
03089         while (!TLI.isTypeLegal(VT))
03090           VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
03091         VTSize = VT.getSizeInBits() / 8;
03092       } else {
03093         VT = (MVT::SimpleValueType)(VT.getSimpleVT() - 1);
03094         VTSize >>= 1;
03095       }
03096     }
03097 
03098     if (++NumMemOps > Limit)
03099       return false;
03100     MemOps.push_back(VT);
03101     Size -= VTSize;
03102   }
03103 
03104   return true;
03105 }
03106 
03107 static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG,
03108                                          SDValue Chain, SDValue Dst,
03109                                          SDValue Src, uint64_t Size,
03110                                          unsigned Align, bool AlwaysInline,
03111                                          const Value *DstSV, uint64_t DstSVOff,
03112                                          const Value *SrcSV, uint64_t SrcSVOff){
03113   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03114 
03115   // Expand memcpy to a series of load and store ops if the size operand falls
03116   // below a certain threshold.
03117   std::vector<MVT> MemOps;
03118   uint64_t Limit = -1ULL;
03119   if (!AlwaysInline)
03120     Limit = TLI.getMaxStoresPerMemcpy();
03121   unsigned DstAlign = Align;  // Destination alignment can change.
03122   std::string Str;
03123   bool CopyFromStr;
03124   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
03125                                 Str, CopyFromStr, DAG, TLI))
03126     return SDValue();
03127 
03128 
03129   bool isZeroStr = CopyFromStr && Str.empty();
03130   SmallVector<SDValue, 8> OutChains;
03131   unsigned NumMemOps = MemOps.size();
03132   uint64_t SrcOff = 0, DstOff = 0;
03133   for (unsigned i = 0; i < NumMemOps; i++) {
03134     MVT VT = MemOps[i];
03135     unsigned VTSize = VT.getSizeInBits() / 8;
03136     SDValue Value, Store;
03137 
03138     if (CopyFromStr && (isZeroStr || !VT.isVector())) {
03139       // It's unlikely a store of a vector immediate can be done in a single
03140       // instruction. It would require a load from a constantpool first.
03141       // We also handle store a vector with all zero's.
03142       // FIXME: Handle other cases where store of vector immediate is done in
03143       // a single instruction.
03144       Value = getMemsetStringVal(VT, DAG, TLI, Str, SrcOff);
03145       Store = DAG.getStore(Chain, Value,
03146                            getMemBasePlusOffset(Dst, DstOff, DAG),
03147                            DstSV, DstSVOff + DstOff, false, DstAlign);
03148     } else {
03149       Value = DAG.getLoad(VT, Chain,
03150                           getMemBasePlusOffset(Src, SrcOff, DAG),
03151                           SrcSV, SrcSVOff + SrcOff, false, Align);
03152       Store = DAG.getStore(Chain, Value,
03153                            getMemBasePlusOffset(Dst, DstOff, DAG),
03154                            DstSV, DstSVOff + DstOff, false, DstAlign);
03155     }
03156     OutChains.push_back(Store);
03157     SrcOff += VTSize;
03158     DstOff += VTSize;
03159   }
03160 
03161   return DAG.getNode(ISD::TokenFactor, MVT::Other,
03162                      &OutChains[0], OutChains.size());
03163 }
03164 
03165 static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG,
03166                                           SDValue Chain, SDValue Dst,
03167                                           SDValue Src, uint64_t Size,
03168                                           unsigned Align, bool AlwaysInline,
03169                                           const Value *DstSV, uint64_t DstSVOff,
03170                                           const Value *SrcSV, uint64_t SrcSVOff){
03171   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03172 
03173   // Expand memmove to a series of load and store ops if the size operand falls
03174   // below a certain threshold.
03175   std::vector<MVT> MemOps;
03176   uint64_t Limit = -1ULL;
03177   if (!AlwaysInline)
03178     Limit = TLI.getMaxStoresPerMemmove();
03179   unsigned DstAlign = Align;  // Destination alignment can change.
03180   std::string Str;
03181   bool CopyFromStr;
03182   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, Limit, Size, DstAlign,
03183                                 Str, CopyFromStr, DAG, TLI))
03184     return SDValue();
03185 
03186   uint64_t SrcOff = 0, DstOff = 0;
03187 
03188   SmallVector<SDValue, 8> LoadValues;
03189   SmallVector<SDValue, 8> LoadChains;
03190   SmallVector<SDValue, 8> OutChains;
03191   unsigned NumMemOps = MemOps.size();
03192   for (unsigned i = 0; i < NumMemOps; i++) {
03193     MVT VT = MemOps[i];
03194     unsigned VTSize = VT.getSizeInBits() / 8;
03195     SDValue Value, Store;
03196 
03197     Value = DAG.getLoad(VT, Chain,
03198                         getMemBasePlusOffset(Src, SrcOff, DAG),
03199                         SrcSV, SrcSVOff + SrcOff, false, Align);
03200     LoadValues.push_back(Value);
03201     LoadChains.push_back(Value.getValue(1));
03202     SrcOff += VTSize;
03203   }
03204   Chain = DAG.getNode(ISD::TokenFactor, MVT::Other,
03205                       &LoadChains[0], LoadChains.size());
03206   OutChains.clear();
03207   for (unsigned i = 0; i < NumMemOps; i++) {
03208     MVT VT = MemOps[i];
03209     unsigned VTSize = VT.getSizeInBits() / 8;
03210     SDValue Value, Store;
03211 
03212     Store = DAG.getStore(Chain, LoadValues[i],
03213                          getMemBasePlusOffset(Dst, DstOff, DAG),
03214                          DstSV, DstSVOff + DstOff, false, DstAlign);
03215     OutChains.push_back(Store);
03216     DstOff += VTSize;
03217   }
03218 
03219   return DAG.getNode(ISD::TokenFactor, MVT::Other,
03220                      &OutChains[0], OutChains.size());
03221 }
03222 
03223 static SDValue getMemsetStores(SelectionDAG &DAG,
03224                                  SDValue Chain, SDValue Dst,
03225                                  SDValue Src, uint64_t Size,
03226                                  unsigned Align,
03227                                  const Value *DstSV, uint64_t DstSVOff) {
03228   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
03229 
03230   // Expand memset to a series of load/store ops if the size operand
03231   // falls below a certain threshold.
03232   std::vector<MVT> MemOps;
03233   std::string Str;
03234   bool CopyFromStr;
03235   if (!MeetsMaxMemopRequirement(MemOps, Dst, Src, TLI.getMaxStoresPerMemset(),
03236                                 Size, Align, Str, CopyFromStr, DAG, TLI))
03237     return SDValue();
03238 
03239   SmallVector<SDValue, 8> OutChains;
03240   uint64_t DstOff = 0;
03241 
03242   unsigned NumMemOps = MemOps.size();
03243   for (unsigned i = 0; i < NumMemOps; i++) {
03244     MVT VT = MemOps[i];
03245     unsigned VTSize = VT.getSizeInBits() / 8;
03246     SDValue Value = getMemsetValue(Src, VT, DAG);
03247     SDValue Store = DAG.getStore(Chain, Value,
03248                                  getMemBasePlusOffset(Dst, DstOff, DAG),
03249                                  DstSV, DstSVOff + DstOff);
03250     OutChains.push_back(Store);
03251     DstOff += VTSize;
03252   }
03253 
03254   return DAG.getNode(ISD::TokenFactor, MVT::Other,
03255                      &OutChains[0], OutChains.size());
03256 }
03257 
03258 SDValue SelectionDAG::getMemcpy(SDValue Chain, SDValue Dst,
03259                                 SDValue Src, SDValue Size,
03260                                 unsigned Align, bool AlwaysInline,
03261                                 const Value *DstSV, uint64_t DstSVOff,
03262                                 const Value *SrcSV, uint64_t SrcSVOff) {
03263 
03264   // Check to see if we should lower the memcpy to loads and stores first.
03265   // For cases within the target-specified limits, this is the best choice.
03266   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
03267   if (ConstantSize) {
03268     // Memcpy with size zero? Just return the original chain.
03269     if (ConstantSize->isNullValue())
03270       return Chain;
03271 
03272     SDValue Result =
03273       getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
03274                               ConstantSize->getZExtValue(),
03275                               Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
03276     if (Result.getNode())
03277       return Result;
03278   }
03279 
03280   // Then check to see if we should lower the memcpy with target-specific
03281   // code. If the target chooses to do this, this is the next best.
03282   SDValue Result =
03283     TLI.EmitTargetCodeForMemcpy(*this, Chain, Dst, Src, Size, Align,
03284                                 AlwaysInline,
03285                                 DstSV, DstSVOff, SrcSV, SrcSVOff);
03286   if (Result.getNode())
03287     return Result;
03288 
03289   // If we really need inline code and the target declined to provide it,
03290   // use a (potentially long) sequence of loads and stores.
03291   if (AlwaysInline) {
03292     assert(ConstantSize && "AlwaysInline requires a constant size!");
03293     return getMemcpyLoadsAndStores(*this, Chain, Dst, Src,
03294                                    ConstantSize->getZExtValue(), Align, true,
03295                                    DstSV, DstSVOff, SrcSV, SrcSVOff);
03296   }
03297 
03298   // Emit a library call.
03299   TargetLowering::ArgListTy Args;
03300   TargetLowering::ArgListEntry Entry;
03301   Entry.Ty = TLI.getTargetData()->getIntPtrType();
03302   Entry.Node = Dst; Args.push_back(Entry);
03303   Entry.Node = Src; Args.push_back(Entry);
03304   Entry.Node = Size; Args.push_back(Entry);
03305   // FIXME: pass in DebugLoc
03306   std::pair<SDValue,SDValue> CallResult =
03307     TLI.LowerCallTo(Chain, Type::VoidTy,
03308                     false, false, false, false, CallingConv::C, false,
03309                     getExternalSymbol("memcpy", TLI.getPointerTy()),
03310                     Args, *this, DebugLoc::getUnknownLoc());
03311   return CallResult.second;
03312 }
03313 
03314 SDValue SelectionDAG::getMemmove(SDValue Chain, SDValue Dst,
03315                                  SDValue Src, SDValue Size,
03316                                  unsigned Align,
03317                                  const Value *DstSV, uint64_t DstSVOff,
03318                                  const Value *SrcSV, uint64_t SrcSVOff) {
03319 
03320   // Check to see if we should lower the memmove to loads and stores first.
03321   // For cases within the target-specified limits, this is the best choice.
03322   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
03323   if (ConstantSize) {
03324     // Memmove with size zero? Just return the original chain.
03325     if (ConstantSize->isNullValue())
03326       return Chain;
03327 
03328     SDValue Result =
03329       getMemmoveLoadsAndStores(*this, Chain, Dst, Src,
03330                                ConstantSize->getZExtValue(),
03331                                Align, false, DstSV, DstSVOff, SrcSV, SrcSVOff);
03332     if (Result.getNode())
03333       return Result;
03334   }
03335 
03336   // Then check to see if we should lower the memmove with target-specific
03337   // code. If the target chooses to do this, this is the next best.
03338   SDValue Result =
03339     TLI.EmitTargetCodeForMemmove(*this, Chain, Dst, Src, Size, Align,
03340                                  DstSV, DstSVOff, SrcSV, SrcSVOff);
03341   if (Result.getNode())
03342     return Result;
03343 
03344   // Emit a library call.
03345   TargetLowering::ArgListTy Args;
03346   TargetLowering::ArgListEntry Entry;
03347   Entry.Ty = TLI.getTargetData()->getIntPtrType();
03348   Entry.Node = Dst; Args.push_back(Entry);
03349   Entry.Node = Src; Args.push_back(Entry);
03350   Entry.Node = Size; Args.push_back(Entry);
03351   // FIXME:  pass in DebugLoc
03352   std::pair<SDValue,SDValue> CallResult =
03353     TLI.LowerCallTo(Chain, Type::VoidTy,
03354                     false, false, false, false, CallingConv::C, false,
03355                     getExternalSymbol("memmove", TLI.getPointerTy()),
03356                     Args, *this, DebugLoc::getUnknownLoc());
03357   return CallResult.second;
03358 }
03359 
03360 SDValue SelectionDAG::getMemset(SDValue Chain, SDValue Dst,
03361                                 SDValue Src, SDValue Size,
03362                                 unsigned Align,
03363                                 const Value *DstSV, uint64_t DstSVOff) {
03364 
03365   // Check to see if we should lower the memset to stores first.
03366   // For cases within the target-specified limits, this is the best choice.
03367   ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
03368   if (ConstantSize) {
03369     // Memset with size zero? Just return the original chain.
03370     if (ConstantSize->isNullValue())
03371       return Chain;
03372 
03373     SDValue Result =
03374       getMemsetStores(*this, Chain, Dst, Src, ConstantSize->getZExtValue(),
03375                       Align, DstSV, DstSVOff);
03376     if (Result.getNode())
03377       return Result;
03378   }
03379 
03380   // Then check to see if we should lower the memset with target-specific
03381   // code. If the target chooses to do this, this is the next best.
03382   SDValue Result =
03383     TLI.EmitTargetCodeForMemset(*this, Chain, Dst, Src, Size, Align,
03384                                 DstSV, DstSVOff);
03385   if (Result.getNode())
03386     return Result;
03387 
03388   // Emit a library call.
03389   const Type *IntPtrTy = TLI.getTargetData()->getIntPtrType();
03390   TargetLowering::ArgListTy Args;
03391   TargetLowering::ArgListEntry Entry;
03392   Entry.Node = Dst; Entry.Ty = IntPtrTy;
03393   Args.push_back(Entry);
03394   // Extend or truncate the argument to be an i32 value for the call.
03395   if (Src.getValueType().bitsGT(MVT::i32))
03396     Src = getNode(ISD::TRUNCATE, MVT::i32, Src);
03397   else
03398     Src = getNode(ISD::ZERO_EXTEND, MVT::i32, Src);
03399   Entry.Node = Src; Entry.Ty = Type::Int32Ty; Entry.isSExt = true;
03400   Args.push_back(Entry);
03401   Entry.Node = Size; Entry.Ty = IntPtrTy; Entry.isSExt = false;
03402   Args.push_back(Entry);
03403   // FIXME: pass in DebugLoc
03404   std::pair<SDValue,SDValue> CallResult =
03405     TLI.LowerCallTo(Chain, Type::VoidTy,
03406                     false, false, false, false, CallingConv::C, false,
03407                     getExternalSymbol("memset", TLI.getPointerTy()),
03408                     Args, *this, DebugLoc::getUnknownLoc());
03409   return CallResult.second;
03410 }
03411 
03412 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
03413                                 SDValue Chain,
03414                                 SDValue Ptr, SDValue Cmp, 
03415                                 SDValue Swp, const Value* PtrVal,
03416                                 unsigned Alignment) {
03417   assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
03418   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
03419 
03420   MVT VT = Cmp.getValueType();
03421 
03422   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03423     Alignment = getMVTAlignment(MemVT);
03424 
03425   SDVTList VTs = getVTList(VT, MVT::Other);
03426   FoldingSetNodeID ID;
03427   ID.AddInteger(MemVT.getRawBits());
03428   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
03429   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
03430   void* IP = 0;
03431   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03432     return SDValue(E, 0);
03433   SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
03434   new (N) AtomicSDNode(Opcode, VTs, MemVT,
03435                        Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
03436   CSEMap.InsertNode(N, IP);
03437   AllNodes.push_back(N);
03438   return SDValue(N, 0);
03439 }
03440 
03441 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
03442                                 SDValue Chain,
03443                                 SDValue Ptr, SDValue Cmp, 
03444                                 SDValue Swp, const Value* PtrVal,
03445                                 unsigned Alignment) {
03446   assert(Opcode == ISD::ATOMIC_CMP_SWAP && "Invalid Atomic Op");
03447   assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
03448 
03449   MVT VT = Cmp.getValueType();
03450 
03451   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03452     Alignment = getMVTAlignment(MemVT);
03453 
03454   SDVTList VTs = getVTList(VT, MVT::Other);
03455   FoldingSetNodeID ID;
03456   ID.AddInteger(MemVT.getRawBits());
03457   SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
03458   AddNodeIDNode(ID, Opcode, VTs, Ops, 4);
03459   void* IP = 0;
03460   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03461     return SDValue(E, 0);
03462   SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
03463   new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
03464                        Chain, Ptr, Cmp, Swp, PtrVal, Alignment);
03465   CSEMap.InsertNode(N, IP);
03466   AllNodes.push_back(N);
03467   return SDValue(N, 0);
03468 }
03469 
03470 SDValue SelectionDAG::getAtomic(unsigned Opcode, MVT MemVT,
03471                                 SDValue Chain,
03472                                 SDValue Ptr, SDValue Val, 
03473                                 const Value* PtrVal,
03474                                 unsigned Alignment) {
03475   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
03476           Opcode == ISD::ATOMIC_LOAD_SUB ||
03477           Opcode == ISD::ATOMIC_LOAD_AND ||
03478           Opcode == ISD::ATOMIC_LOAD_OR ||
03479           Opcode == ISD::ATOMIC_LOAD_XOR ||
03480           Opcode == ISD::ATOMIC_LOAD_NAND ||
03481           Opcode == ISD::ATOMIC_LOAD_MIN || 
03482           Opcode == ISD::ATOMIC_LOAD_MAX ||
03483           Opcode == ISD::ATOMIC_LOAD_UMIN || 
03484           Opcode == ISD::ATOMIC_LOAD_UMAX ||
03485           Opcode == ISD::ATOMIC_SWAP) &&
03486          "Invalid Atomic Op");
03487 
03488   MVT VT = Val.getValueType();
03489 
03490   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03491     Alignment = getMVTAlignment(MemVT);
03492 
03493   SDVTList VTs = getVTList(VT, MVT::Other);
03494   FoldingSetNodeID ID;
03495   ID.AddInteger(MemVT.getRawBits());
03496   SDValue Ops[] = {Chain, Ptr, Val};
03497   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
03498   void* IP = 0;
03499   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03500     return SDValue(E, 0);
03501   SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
03502   new (N) AtomicSDNode(Opcode, VTs, MemVT,
03503                        Chain, Ptr, Val, PtrVal, Alignment);
03504   CSEMap.InsertNode(N, IP);
03505   AllNodes.push_back(N);
03506   return SDValue(N, 0);
03507 }
03508 
03509 SDValue SelectionDAG::getAtomic(unsigned Opcode, DebugLoc dl, MVT MemVT,
03510                                 SDValue Chain,
03511                                 SDValue Ptr, SDValue Val, 
03512                                 const Value* PtrVal,
03513                                 unsigned Alignment) {
03514   assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
03515           Opcode == ISD::ATOMIC_LOAD_SUB ||
03516           Opcode == ISD::ATOMIC_LOAD_AND ||
03517           Opcode == ISD::ATOMIC_LOAD_OR ||
03518           Opcode == ISD::ATOMIC_LOAD_XOR ||
03519           Opcode == ISD::ATOMIC_LOAD_NAND ||
03520           Opcode == ISD::ATOMIC_LOAD_MIN || 
03521           Opcode == ISD::ATOMIC_LOAD_MAX ||
03522           Opcode == ISD::ATOMIC_LOAD_UMIN || 
03523           Opcode == ISD::ATOMIC_LOAD_UMAX ||
03524           Opcode == ISD::ATOMIC_SWAP) &&
03525          "Invalid Atomic Op");
03526 
03527   MVT VT = Val.getValueType();
03528 
03529   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03530     Alignment = getMVTAlignment(MemVT);
03531 
03532   SDVTList VTs = getVTList(VT, MVT::Other);
03533   FoldingSetNodeID ID;
03534   ID.AddInteger(MemVT.getRawBits());
03535   SDValue Ops[] = {Chain, Ptr, Val};
03536   AddNodeIDNode(ID, Opcode, VTs, Ops, 3);
03537   void* IP = 0;
03538   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03539     return SDValue(E, 0);
03540   SDNode* N = NodeAllocator.Allocate<AtomicSDNode>();
03541   new (N) AtomicSDNode(Opcode, dl, VTs, MemVT,
03542                        Chain, Ptr, Val, PtrVal, Alignment);
03543   CSEMap.InsertNode(N, IP);
03544   AllNodes.push_back(N);
03545   return SDValue(N, 0);
03546 }
03547 
03548 /// getMergeValues - Create a MERGE_VALUES node from the given operands.
03549 /// Allowed to return something different (and simpler) if Simplify is true.
03550 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps) {
03551   if (NumOps == 1)
03552     return Ops[0];
03553 
03554   SmallVector<MVT, 4> VTs;
03555   VTs.reserve(NumOps);
03556   for (unsigned i = 0; i < NumOps; ++i)
03557     VTs.push_back(Ops[i].getValueType());
03558   return getNode(ISD::MERGE_VALUES, getVTList(&VTs[0], NumOps), Ops, NumOps);
03559 }
03560 
03561 /// DebugLoc-aware version.
03562 SDValue SelectionDAG::getMergeValues(const SDValue *Ops, unsigned NumOps,
03563                                      DebugLoc dl) {
03564   if (NumOps == 1)
03565     return Ops[0];
03566 
03567   SmallVector<MVT, 4> VTs;
03568   VTs.reserve(NumOps);
03569   for (unsigned i = 0; i < NumOps; ++i)
03570     VTs.push_back(Ops[i].getValueType());
03571   return getNode(ISD::MERGE_VALUES, dl, getVTList(&VTs[0], NumOps), 
03572                  Ops, NumOps);
03573 }
03574 
03575 SDValue
03576 SelectionDAG::getMemIntrinsicNode(unsigned Opcode,
03577                                   const MVT *VTs, unsigned NumVTs,
03578                                   const SDValue *Ops, unsigned NumOps,
03579                                   MVT MemVT, const Value *srcValue, int SVOff,
03580                                   unsigned Align, bool Vol,
03581                                   bool ReadMem, bool WriteMem) {
03582   return getMemIntrinsicNode(Opcode, makeVTList(VTs, NumVTs), Ops, NumOps,
03583                              MemVT, srcValue, SVOff, Align, Vol,
03584                              ReadMem, WriteMem);
03585 }
03586 
03587 SDValue
03588 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl,
03589                                   const MVT *VTs, unsigned NumVTs,
03590                                   const SDValue *Ops, unsigned NumOps,
03591                                   MVT MemVT, const Value *srcValue, int SVOff,
03592                                   unsigned Align, bool Vol,
03593                                   bool ReadMem, bool WriteMem) {
03594   return getMemIntrinsicNode(Opcode, dl, makeVTList(VTs, NumVTs), Ops, NumOps,
03595                              MemVT, srcValue, SVOff, Align, Vol,
03596                              ReadMem, WriteMem);
03597 }
03598 
03599 SDValue
03600 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, SDVTList VTList,
03601                                   const SDValue *Ops, unsigned NumOps,
03602                                   MVT MemVT, const Value *srcValue, int SVOff,
03603                                   unsigned Align, bool Vol,
03604                                   bool ReadMem, bool WriteMem) {
03605   // Memoize the node unless it returns a flag.
03606   MemIntrinsicSDNode *N;
03607   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
03608     FoldingSetNodeID ID;
03609     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
03610     void *IP = 0;
03611     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03612       return SDValue(E, 0);
03613     
03614     N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
03615     new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
03616                                srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
03617     CSEMap.InsertNode(N, IP);
03618   } else {
03619     N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
03620     new (N) MemIntrinsicSDNode(Opcode, VTList, Ops, NumOps, MemVT,
03621                                srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
03622   }
03623   AllNodes.push_back(N);
03624   return SDValue(N, 0);
03625 }
03626 
03627 SDValue
03628 SelectionDAG::getMemIntrinsicNode(unsigned Opcode, DebugLoc dl, SDVTList VTList,
03629                                   const SDValue *Ops, unsigned NumOps,
03630                                   MVT MemVT, const Value *srcValue, int SVOff,
03631                                   unsigned Align, bool Vol,
03632                                   bool ReadMem, bool WriteMem) {
03633   // Memoize the node unless it returns a flag.
03634   MemIntrinsicSDNode *N;
03635   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
03636     FoldingSetNodeID ID;
03637     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
03638     void *IP = 0;
03639     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03640       return SDValue(E, 0);
03641     
03642     N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
03643     new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
03644                                srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
03645     CSEMap.InsertNode(N, IP);
03646   } else {
03647     N = NodeAllocator.Allocate<MemIntrinsicSDNode>();
03648     new (N) MemIntrinsicSDNode(Opcode, dl, VTList, Ops, NumOps, MemVT,
03649                                srcValue, SVOff, Align, Vol, ReadMem, WriteMem);
03650   }
03651   AllNodes.push_back(N);
03652   return SDValue(N, 0);
03653 }
03654 
03655 SDValue
03656 SelectionDAG::getCall(unsigned CallingConv, bool IsVarArgs, bool IsTailCall,
03657                       bool IsInreg, SDVTList VTs,
03658                       const SDValue *Operands, unsigned NumOperands) {
03659   // Do not include isTailCall in the folding set profile.
03660   FoldingSetNodeID ID;
03661   AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
03662   ID.AddInteger(CallingConv);
03663   ID.AddInteger(IsVarArgs);
03664   void *IP = 0;
03665   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
03666     // Instead of including isTailCall in the folding set, we just
03667     // set the flag of the existing node.
03668     if (!IsTailCall)
03669       cast<CallSDNode>(E)->setNotTailCall();
03670     return SDValue(E, 0);
03671   }
03672   SDNode *N = NodeAllocator.Allocate<CallSDNode>();
03673   new (N) CallSDNode(CallingConv, IsVarArgs, IsTailCall, IsInreg,
03674                      VTs, Operands, NumOperands);
03675   CSEMap.InsertNode(N, IP);
03676   AllNodes.push_back(N);
03677   return SDValue(N, 0);
03678 }
03679 
03680 SDValue
03681 SelectionDAG::getCall(unsigned CallingConv, DebugLoc dl, bool IsVarArgs,
03682                       bool IsTailCall, bool IsInreg, SDVTList VTs,
03683                       const SDValue *Operands, unsigned NumOperands) {
03684   // Do not include isTailCall in the folding set profile.
03685   FoldingSetNodeID ID;
03686   AddNodeIDNode(ID, ISD::CALL, VTs, Operands, NumOperands);
03687   ID.AddInteger(CallingConv);
03688   ID.AddInteger(IsVarArgs);
03689   void *IP = 0;
03690   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP)) {
03691     // Instead of including isTailCall in the folding set, we just
03692     // set the flag of the existing node.
03693     if (!IsTailCall)
03694       cast<CallSDNode>(E)->setNotTailCall();
03695     return SDValue(E, 0);
03696   }
03697   SDNode *N = NodeAllocator.Allocate<CallSDNode>();
03698   new (N) CallSDNode(CallingConv, dl, IsVarArgs, IsTailCall, IsInreg,
03699                      VTs, Operands, NumOperands);
03700   CSEMap.InsertNode(N, IP);
03701   AllNodes.push_back(N);
03702   return SDValue(N, 0);
03703 }
03704 
03705 SDValue
03706 SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
03707                       MVT VT, SDValue Chain,
03708                       SDValue Ptr, SDValue Offset,
03709                       const Value *SV, int SVOffset, MVT EVT,
03710                       bool isVolatile, unsigned Alignment) {
03711   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03712     Alignment = getMVTAlignment(VT);
03713 
03714   if (VT == EVT) {
03715     ExtType = ISD::NON_EXTLOAD;
03716   } else if (ExtType == ISD::NON_EXTLOAD) {
03717     assert(VT == EVT && "Non-extending load from different memory type!");
03718   } else {
03719     // Extending load.
03720     if (VT.isVector())
03721       assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
03722              "Invalid vector extload!");
03723     else
03724       assert(EVT.bitsLT(VT) &&
03725              "Should only be an extending load, not truncating!");
03726     assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
03727            "Cannot sign/zero extend a FP/Vector load!");
03728     assert(VT.isInteger() == EVT.isInteger() &&
03729            "Cannot convert from FP to Int or Int -> FP!");
03730   }
03731 
03732   bool Indexed = AM != ISD::UNINDEXED;
03733   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
03734          "Unindexed load with an offset!");
03735 
03736   SDVTList VTs = Indexed ?
03737     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
03738   SDValue Ops[] = { Chain, Ptr, Offset };
03739   FoldingSetNodeID ID;
03740   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
03741   ID.AddInteger(EVT.getRawBits());
03742   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
03743   void *IP = 0;
03744   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03745     return SDValue(E, 0);
03746   SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
03747   new (N) LoadSDNode(Ops, VTs, AM, ExtType, EVT, SV, SVOffset,
03748                      Alignment, isVolatile);
03749   CSEMap.InsertNode(N, IP);
03750   AllNodes.push_back(N);
03751   return SDValue(N, 0);
03752 }
03753 
03754 SDValue
03755 SelectionDAG::getLoad(ISD::MemIndexedMode AM, DebugLoc dl, 
03756                       ISD::LoadExtType ExtType, MVT VT, SDValue Chain,
03757                       SDValue Ptr, SDValue Offset,
03758                       const Value *SV, int SVOffset, MVT EVT,
03759                       bool isVolatile, unsigned Alignment) {
03760   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03761     Alignment = getMVTAlignment(VT);
03762 
03763   if (VT == EVT) {
03764     ExtType = ISD::NON_EXTLOAD;
03765   } else if (ExtType == ISD::NON_EXTLOAD) {
03766     assert(VT == EVT && "Non-extending load from different memory type!");
03767   } else {
03768     // Extending load.
03769     if (VT.isVector())
03770       assert(EVT.getVectorNumElements() == VT.getVectorNumElements() &&
03771              "Invalid vector extload!");
03772     else
03773       assert(EVT.bitsLT(VT) &&
03774              "Should only be an extending load, not truncating!");
03775     assert((ExtType == ISD::EXTLOAD || VT.isInteger()) &&
03776            "Cannot sign/zero extend a FP/Vector load!");
03777     assert(VT.isInteger() == EVT.isInteger() &&
03778            "Cannot convert from FP to Int or Int -> FP!");
03779   }
03780 
03781   bool Indexed = AM != ISD::UNINDEXED;
03782   assert((Indexed || Offset.getOpcode() == ISD::UNDEF) &&
03783          "Unindexed load with an offset!");
03784 
03785   SDVTList VTs = Indexed ?
03786     getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
03787   SDValue Ops[] = { Chain, Ptr, Offset };
03788   FoldingSetNodeID ID;
03789   AddNodeIDNode(ID, ISD::LOAD, VTs, Ops, 3);
03790   ID.AddInteger(EVT.getRawBits());
03791   ID.AddInteger(encodeMemSDNodeFlags(ExtType, AM, isVolatile, Alignment));
03792   void *IP = 0;
03793   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03794     return SDValue(E, 0);
03795   SDNode *N = NodeAllocator.Allocate<LoadSDNode>();
03796   new (N) LoadSDNode(Ops, dl, VTs, AM, ExtType, EVT, SV, SVOffset,
03797                      Alignment, isVolatile);
03798   CSEMap.InsertNode(N, IP);
03799   AllNodes.push_back(N);
03800   return SDValue(N, 0);
03801 }
03802 
03803 SDValue SelectionDAG::getLoad(MVT VT,
03804                               SDValue Chain, SDValue Ptr,
03805                               const Value *SV, int SVOffset,
03806                               bool isVolatile, unsigned Alignment) {
03807   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03808   return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
03809                  SV, SVOffset, VT, isVolatile, Alignment);
03810 }
03811 
03812 SDValue SelectionDAG::getLoad(MVT VT, DebugLoc dl,
03813                               SDValue Chain, SDValue Ptr,
03814                               const Value *SV, int SVOffset,
03815                               bool isVolatile, unsigned Alignment) {
03816   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03817   return getLoad(ISD::UNINDEXED, dl, ISD::NON_EXTLOAD, VT, Chain, Ptr, Undef,
03818                  SV, SVOffset, VT, isVolatile, Alignment);
03819 }
03820 
03821 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, MVT VT,
03822                                  SDValue Chain, SDValue Ptr,
03823                                  const Value *SV,
03824                                  int SVOffset, MVT EVT,
03825                                  bool isVolatile, unsigned Alignment) {
03826   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03827   return getLoad(ISD::UNINDEXED, ExtType, VT, Chain, Ptr, Undef,
03828                  SV, SVOffset, EVT, isVolatile, Alignment);
03829 }
03830 
03831 SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, DebugLoc dl, MVT VT,
03832                                  SDValue Chain, SDValue Ptr,
03833                                  const Value *SV,
03834                                  int SVOffset, MVT EVT,
03835                                  bool isVolatile, unsigned Alignment) {
03836   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03837   return getLoad(ISD::UNINDEXED, dl, ExtType, VT, Chain, Ptr, Undef,
03838                  SV, SVOffset, EVT, isVolatile, Alignment);
03839 }
03840 
03841 SDValue
03842 SelectionDAG::getIndexedLoad(SDValue OrigLoad, SDValue Base,
03843                              SDValue Offset, ISD::MemIndexedMode AM) {
03844   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
03845   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
03846          "Load is already a indexed load!");
03847   return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(),
03848                  LD->getChain(), Base, Offset, LD->getSrcValue(),
03849                  LD->getSrcValueOffset(), LD->getMemoryVT(),
03850                  LD->isVolatile(), LD->getAlignment());
03851 }
03852 
03853 SDValue
03854 SelectionDAG::getIndexedLoad(SDValue OrigLoad, DebugLoc dl, SDValue Base,
03855                              SDValue Offset, ISD::MemIndexedMode AM) {
03856   LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
03857   assert(LD->getOffset().getOpcode() == ISD::UNDEF &&
03858          "Load is already a indexed load!");
03859   return getLoad(AM, dl, LD->getExtensionType(), OrigLoad.getValueType(),
03860                  LD->getChain(), Base, Offset, LD->getSrcValue(),
03861                  LD->getSrcValueOffset(), LD->getMemoryVT(),
03862                  LD->isVolatile(), LD->getAlignment());
03863 }
03864 
03865 SDValue SelectionDAG::getStore(SDValue Chain, SDValue Val,
03866                                SDValue Ptr, const Value *SV, int SVOffset,
03867                                bool isVolatile, unsigned Alignment) {
03868   MVT VT = Val.getValueType();
03869 
03870   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03871     Alignment = getMVTAlignment(VT);
03872 
03873   SDVTList VTs = getVTList(MVT::Other);
03874   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03875   SDValue Ops[] = { Chain, Val, Ptr, Undef };
03876   FoldingSetNodeID ID;
03877   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
03878   ID.AddInteger(VT.getRawBits());
03879   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
03880                                      isVolatile, Alignment));
03881   void *IP = 0;
03882   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03883     return SDValue(E, 0);
03884   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
03885   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, false,
03886                       VT, SV, SVOffset, Alignment, isVolatile);
03887   CSEMap.InsertNode(N, IP);
03888   AllNodes.push_back(N);
03889   return SDValue(N, 0);
03890 }
03891 
03892 SDValue SelectionDAG::getStore(SDValue Chain, DebugLoc dl, SDValue Val,
03893                                SDValue Ptr, const Value *SV, int SVOffset,
03894                                bool isVolatile, unsigned Alignment) {
03895   MVT VT = Val.getValueType();
03896 
03897   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03898     Alignment = getMVTAlignment(VT);
03899 
03900   SDVTList VTs = getVTList(MVT::Other);
03901   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03902   SDValue Ops[] = { Chain, Val, Ptr, Undef };
03903   FoldingSetNodeID ID;
03904   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
03905   ID.AddInteger(VT.getRawBits());
03906   ID.AddInteger(encodeMemSDNodeFlags(false, ISD::UNINDEXED,
03907                                      isVolatile, Alignment));
03908   void *IP = 0;
03909   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03910     return SDValue(E, 0);
03911   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
03912   new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, false,
03913                       VT, SV, SVOffset, Alignment, isVolatile);
03914   CSEMap.InsertNode(N, IP);
03915   AllNodes.push_back(N);
03916   return SDValue(N, 0);
03917 }
03918 
03919 SDValue SelectionDAG::getTruncStore(SDValue Chain, SDValue Val,
03920                                     SDValue Ptr, const Value *SV,
03921                                     int SVOffset, MVT SVT,
03922                                     bool isVolatile, unsigned Alignment) {
03923   MVT VT = Val.getValueType();
03924 
03925   if (VT == SVT)
03926     return getStore(Chain, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
03927 
03928   assert(VT.bitsGT(SVT) && "Not a truncation?");
03929   assert(VT.isInteger() == SVT.isInteger() &&
03930          "Can't do FP-INT conversion!");
03931 
03932   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03933     Alignment = getMVTAlignment(VT);
03934 
03935   SDVTList VTs = getVTList(MVT::Other);
03936   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03937   SDValue Ops[] = { Chain, Val, Ptr, Undef };
03938   FoldingSetNodeID ID;
03939   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
03940   ID.AddInteger(SVT.getRawBits());
03941   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
03942                                      isVolatile, Alignment));
03943   void *IP = 0;
03944   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03945     return SDValue(E, 0);
03946   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
03947   new (N) StoreSDNode(Ops, VTs, ISD::UNINDEXED, true,
03948                       SVT, SV, SVOffset, Alignment, isVolatile);
03949   CSEMap.InsertNode(N, IP);
03950   AllNodes.push_back(N);
03951   return SDValue(N, 0);
03952 }
03953 
03954 SDValue SelectionDAG::getTruncStore(SDValue Chain, DebugLoc dl, SDValue Val,
03955                                     SDValue Ptr, const Value *SV,
03956                                     int SVOffset, MVT SVT,
03957                                     bool isVolatile, unsigned Alignment) {
03958   MVT VT = Val.getValueType();
03959 
03960   if (VT == SVT)
03961     return getStore(Chain, dl, Val, Ptr, SV, SVOffset, isVolatile, Alignment);
03962 
03963   assert(VT.bitsGT(SVT) && "Not a truncation?");
03964   assert(VT.isInteger() == SVT.isInteger() &&
03965          "Can't do FP-INT conversion!");
03966 
03967   if (Alignment == 0)  // Ensure that codegen never sees alignment 0
03968     Alignment = getMVTAlignment(VT);
03969 
03970   SDVTList VTs = getVTList(MVT::Other);
03971   SDValue Undef = getNode(ISD::UNDEF, Ptr.getValueType());
03972   SDValue Ops[] = { Chain, Val, Ptr, Undef };
03973   FoldingSetNodeID ID;
03974   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
03975   ID.AddInteger(SVT.getRawBits());
03976   ID.AddInteger(encodeMemSDNodeFlags(true, ISD::UNINDEXED,
03977                                      isVolatile, Alignment));
03978   void *IP = 0;
03979   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
03980     return SDValue(E, 0);
03981   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
03982   new (N) StoreSDNode(Ops, dl, VTs, ISD::UNINDEXED, true,
03983                       SVT, SV, SVOffset, Alignment, isVolatile);
03984   CSEMap.InsertNode(N, IP);
03985   AllNodes.push_back(N);
03986   return SDValue(N, 0);
03987 }
03988 
03989 SDValue
03990 SelectionDAG::getIndexedStore(SDValue OrigStore, SDValue Base,
03991                               SDValue Offset, ISD::MemIndexedMode AM) {
03992   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
03993   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
03994          "Store is already a indexed store!");
03995   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
03996   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
03997   FoldingSetNodeID ID;
03998   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
03999   ID.AddInteger(ST->getMemoryVT().getRawBits());
04000   ID.AddInteger(ST->getRawSubclassData());
04001   void *IP = 0;
04002   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
04003     return SDValue(E, 0);
04004   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
04005   new (N) StoreSDNode(Ops, VTs, AM,
04006                       ST->isTruncatingStore(), ST->getMemoryVT(),
04007                       ST->getSrcValue(), ST->getSrcValueOffset(),
04008                       ST->getAlignment(), ST->isVolatile());
04009   CSEMap.InsertNode(N, IP);
04010   AllNodes.push_back(N);
04011   return SDValue(N, 0);
04012 }
04013 
04014 SDValue
04015 SelectionDAG::getIndexedStore(SDValue OrigStore, DebugLoc dl, SDValue Base,
04016                               SDValue Offset, ISD::MemIndexedMode AM) {
04017   StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
04018   assert(ST->getOffset().getOpcode() == ISD::UNDEF &&
04019          "Store is already a indexed store!");
04020   SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
04021   SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
04022   FoldingSetNodeID ID;
04023   AddNodeIDNode(ID, ISD::STORE, VTs, Ops, 4);
04024   ID.AddInteger(ST->getMemoryVT().getRawBits());
04025   ID.AddInteger(ST->getRawSubclassData());
04026   void *IP = 0;
04027   if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
04028     return SDValue(E, 0);
04029   SDNode *N = NodeAllocator.Allocate<StoreSDNode>();
04030   new (N) StoreSDNode(Ops, dl, VTs, AM,
04031                       ST->isTruncatingStore(), ST->getMemoryVT(),
04032                       ST->getSrcValue(), ST->getSrcValueOffset(),
04033                       ST->getAlignment(), ST->isVolatile());
04034   CSEMap.InsertNode(N, IP);
04035   AllNodes.push_back(N);
04036   return SDValue(N, 0);
04037 }
04038 
04039 SDValue SelectionDAG::getVAArg(MVT VT,
04040                                SDValue Chain, SDValue Ptr,
04041                                SDValue SV) {
04042   SDValue Ops[] = { Chain, Ptr, SV };
04043   return getNode(ISD::VAARG, getVTList(VT, MVT::Other), Ops, 3);
04044 }
04045 
04046 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
04047                               const SDUse *Ops, unsigned NumOps) {
04048   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
04049 }
04050 
04051 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
04052                               const SDUse *Ops, unsigned NumOps) {
04053   switch (NumOps) {
04054   case 0: return getNode(Opcode, DL, VT);
04055   case 1: return getNode(Opcode, DL, VT, Ops[0]);
04056   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
04057   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
04058   default: break;
04059   }
04060 
04061   // Copy from an SDUse array into an SDValue array for use with
04062   // the regular getNode logic.
04063   SmallVector<SDValue, 8> NewOps(Ops, Ops + NumOps);
04064   return getNode(Opcode, DL, VT, &NewOps[0], NumOps);
04065 }
04066 
04067 SDValue SelectionDAG::getNode(unsigned Opcode, MVT VT,
04068                               const SDValue *Ops, unsigned NumOps) {
04069   return getNode(Opcode, DebugLoc::getUnknownLoc(), VT, Ops, NumOps);
04070 }
04071 
04072 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, MVT VT,
04073                               const SDValue *Ops, unsigned NumOps) {
04074   switch (NumOps) {
04075   case 0: return getNode(Opcode, DL, VT);
04076   case 1: return getNode(Opcode, DL, VT, Ops[0]);
04077   case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
04078   case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
04079   default: break;
04080   }
04081   
04082   switch (Opcode) {
04083   default: break;
04084   case ISD::SELECT_CC: {
04085     assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
04086     assert(Ops[0].getValueType() == Ops[1].getValueType() &&
04087            "LHS and RHS of condition must have same type!");
04088     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
04089            "True and False arms of SelectCC must have same type!");
04090     assert(Ops[2].getValueType() == VT &&
04091            "select_cc node must be of same type as true and false value!");
04092     break;
04093   }
04094   case ISD::BR_CC: {
04095     assert(NumOps == 5 && "BR_CC takes 5 operands!");
04096     assert(Ops[2].getValueType() == Ops[3].getValueType() &&
04097            "LHS/RHS of comparison should match types!");
04098     break;
04099   }
04100   }
04101 
04102   // Memoize nodes.
04103   SDNode *N;
04104   SDVTList VTs = getVTList(VT);
04105 
04106   if (VT != MVT::Flag) {
04107     FoldingSetNodeID ID;
04108     AddNodeIDNode(ID, Opcode, VTs, Ops, NumOps);
04109     void *IP = 0;
04110 
04111     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
04112       return SDValue(E, 0);
04113 
04114     N = NodeAllocator.Allocate<SDNode>();
04115     new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
04116     CSEMap.InsertNode(N, IP);
04117   } else {
04118     N = NodeAllocator.Allocate<SDNode>();
04119     new (N) SDNode(Opcode, DL, VTs, Ops, NumOps);
04120   }
04121 
04122   AllNodes.push_back(N);
04123 #ifndef NDEBUG
04124   VerifyNode(N);
04125 #endif
04126   return SDValue(N, 0);
04127 }
04128 
04129 SDValue SelectionDAG::getNode(unsigned Opcode,
04130                               const std::vector<MVT> &ResultTys,
04131                               const SDValue *Ops, unsigned NumOps) {
04132   return getNode(Opcode, DebugLoc::getUnknownLoc(), ResultTys, Ops, NumOps);
04133 }
04134 
04135 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
04136                               const std::vector<MVT> &ResultTys,
04137                               const SDValue *Ops, unsigned NumOps) {
04138   return getNode(Opcode, DL, getNodeValueTypes(ResultTys), ResultTys.size(),
04139                  Ops, NumOps);
04140 }
04141 
04142 SDValue SelectionDAG::getNode(unsigned Opcode,
04143                               const MVT *VTs, unsigned NumVTs,
04144                               const SDValue *Ops, unsigned NumOps) {
04145   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTs, NumVTs, Ops, NumOps);
04146 }
04147 
04148 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL,
04149                               const MVT *VTs, unsigned NumVTs,
04150                               const SDValue *Ops, unsigned NumOps) {
04151   if (NumVTs == 1)
04152     return getNode(Opcode, DL, VTs[0], Ops, NumOps);
04153   return getNode(Opcode, DL, makeVTList(VTs, NumVTs), Ops, NumOps);
04154 }  
04155   
04156 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04157                               const SDValue *Ops, unsigned NumOps) {
04158   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, Ops, NumOps);
04159 }
04160 
04161 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04162                               const SDValue *Ops, unsigned NumOps) {
04163   if (VTList.NumVTs == 1)
04164     return getNode(Opcode, DL, VTList.VTs[0], Ops, NumOps);
04165 
04166   switch (Opcode) {
04167   // FIXME: figure out how to safely handle things like
04168   // int foo(int x) { return 1 << (x & 255); }
04169   // int bar() { return foo(256); }
04170 #if 0
04171   case ISD::SRA_PARTS:
04172   case ISD::SRL_PARTS:
04173   case ISD::SHL_PARTS:
04174     if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
04175         cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
04176       return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
04177     else if (N3.getOpcode() == ISD::AND)
04178       if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
04179         // If the and is only masking out bits that cannot effect the shift,
04180         // eliminate the and.
04181         unsigned NumBits = VT.getSizeInBits()*2;
04182         if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
04183           return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
04184       }
04185     break;
04186 #endif
04187   }
04188 
04189   // Memoize the node unless it returns a flag.
04190   SDNode *N;
04191   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
04192     FoldingSetNodeID ID;
04193     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
04194     void *IP = 0;
04195     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
04196       return SDValue(E, 0);
04197     if (NumOps == 1) {
04198       N = NodeAllocator.Allocate<UnarySDNode>();
04199       new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
04200     } else if (NumOps == 2) {
04201       N = NodeAllocator.Allocate<BinarySDNode>();
04202       new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
04203     } else if (NumOps == 3) {
04204       N = NodeAllocator.Allocate<TernarySDNode>();
04205       new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
04206     } else {
04207       N = NodeAllocator.Allocate<SDNode>();
04208       new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
04209     }
04210     CSEMap.InsertNode(N, IP);
04211   } else {
04212     if (NumOps == 1) {
04213       N = NodeAllocator.Allocate<UnarySDNode>();
04214       new (N) UnarySDNode(Opcode, DL, VTList, Ops[0]);
04215     } else if (NumOps == 2) {
04216       N = NodeAllocator.Allocate<BinarySDNode>();
04217       new (N) BinarySDNode(Opcode, DL, VTList, Ops[0], Ops[1]);
04218     } else if (NumOps == 3) {
04219       N = NodeAllocator.Allocate<TernarySDNode>();
04220       new (N) TernarySDNode(Opcode, DL, VTList, Ops[0], Ops[1], Ops[2]);
04221     } else {
04222       N = NodeAllocator.Allocate<SDNode>();
04223       new (N) SDNode(Opcode, DL, VTList, Ops, NumOps);
04224     }
04225   }
04226   AllNodes.push_back(N);
04227 #ifndef NDEBUG
04228   VerifyNode(N);
04229 #endif
04230   return SDValue(N, 0);
04231 }
04232 
04233 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList) {
04234   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList); 
04235 }
04236 
04237 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList) {
04238   return getNode(Opcode, DL, VTList, 0, 0);
04239 }
04240 
04241 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04242                               SDValue N1) {
04243   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1);
04244 }
04245 
04246 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04247                               SDValue N1) {
04248   SDValue Ops[] = { N1 };
04249   return getNode(Opcode, DL, VTList, Ops, 1);
04250 }
04251 
04252 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04253                               SDValue N1, SDValue N2) {
04254   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2);
04255 }
04256 
04257 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04258                               SDValue N1, SDValue N2) {
04259   SDValue Ops[] = { N1, N2 };
04260   return getNode(Opcode, DL, VTList, Ops, 2);
04261 }
04262 
04263 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04264                               SDValue N1, SDValue N2, SDValue N3) {
04265   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3);
04266 }
04267 
04268 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04269                               SDValue N1, SDValue N2, SDValue N3) {
04270   SDValue Ops[] = { N1, N2, N3 };
04271   return getNode(Opcode, DL, VTList, Ops, 3);
04272 }
04273 
04274 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04275                               SDValue N1, SDValue N2, SDValue N3,
04276                               SDValue N4) {
04277   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4);
04278 }
04279 
04280 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04281                               SDValue N1, SDValue N2, SDValue N3,
04282                               SDValue N4) {
04283   SDValue Ops[] = { N1, N2, N3, N4 };
04284   return getNode(Opcode, DL, VTList, Ops, 4);
04285 }
04286 
04287 SDValue SelectionDAG::getNode(unsigned Opcode, SDVTList VTList,
04288                               SDValue N1, SDValue N2, SDValue N3,
04289                               SDValue N4, SDValue N5) {
04290   return getNode(Opcode, DebugLoc::getUnknownLoc(), VTList, N1, N2, N3, N4, N5);
04291 }
04292 
04293 SDValue SelectionDAG::getNode(unsigned Opcode, DebugLoc DL, SDVTList VTList,
04294                               SDValue N1, SDValue N2, SDValue N3,
04295                               SDValue N4, SDValue N5) {
04296   SDValue Ops[] = { N1, N2, N3, N4, N5 };
04297   return getNode(Opcode, DL, VTList, Ops, 5);
04298 }
04299 
04300 SDVTList SelectionDAG::getVTList(MVT VT) {
04301   return makeVTList(SDNode::getValueTypeList(VT), 1);
04302 }
04303 
04304 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2) {
04305   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
04306        E = VTList.rend(); I != E; ++I)
04307     if (I->NumVTs == 2 && I->VTs[0] == VT1 && I->VTs[1] == VT2)
04308       return *I;
04309 
04310   MVT *Array = Allocator.Allocate<MVT>(2);
04311   Array[0] = VT1;
04312   Array[1] = VT2;
04313   SDVTList Result = makeVTList(Array, 2);
04314   VTList.push_back(Result);
04315   return Result;
04316 }
04317 
04318 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3) {
04319   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
04320        E = VTList.rend(); I != E; ++I)
04321     if (I->NumVTs == 3 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
04322                           I->VTs[2] == VT3)
04323       return *I;
04324 
04325   MVT *Array = Allocator.Allocate<MVT>(3);
04326   Array[0] = VT1;
04327   Array[1] = VT2;
04328   Array[2] = VT3;
04329   SDVTList Result = makeVTList(Array, 3);
04330   VTList.push_back(Result);
04331   return Result;
04332 }
04333 
04334 SDVTList SelectionDAG::getVTList(MVT VT1, MVT VT2, MVT VT3, MVT VT4) {
04335   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
04336        E = VTList.rend(); I != E; ++I)
04337     if (I->NumVTs == 4 && I->VTs[0] == VT1 && I->VTs[1] == VT2 &&
04338                           I->VTs[2] == VT3 && I->VTs[3] == VT4)
04339       return *I;
04340 
04341   MVT *Array = Allocator.Allocate<MVT>(3);
04342   Array[0] = VT1;
04343   Array[1] = VT2;
04344   Array[2] = VT3;
04345   Array[3] = VT4;
04346   SDVTList Result = makeVTList(Array, 4);
04347   VTList.push_back(Result);
04348   return Result;
04349 }
04350 
04351 SDVTList SelectionDAG::getVTList(const MVT *VTs, unsigned NumVTs) {
04352   switch (NumVTs) {
04353     case 0: assert(0 && "Cannot have nodes without results!");
04354     case 1: return getVTList(VTs[0]);
04355     case 2: return getVTList(VTs[0], VTs[1]);
04356     case 3: return getVTList(VTs[0], VTs[1], VTs[2]);
04357     default: break;
04358   }
04359 
04360   for (std::vector<SDVTList>::reverse_iterator I = VTList.rbegin(),
04361        E = VTList.rend(); I != E; ++I) {
04362     if (I->NumVTs != NumVTs || VTs[0] != I->VTs[0] || VTs[1] != I->VTs[1])
04363       continue;
04364    
04365     bool NoMatch = false;
04366     for (unsigned i = 2; i != NumVTs; ++i)
04367       if (VTs[i] != I->VTs[i]) {
04368         NoMatch = true;
04369         break;
04370       }
04371     if (!NoMatch)
04372       return *I;
04373   }
04374   
04375   MVT *Array = Allocator.Allocate<MVT>(NumVTs);
04376   std::copy(VTs, VTs+NumVTs, Array);
04377   SDVTList Result = makeVTList(Array, NumVTs);
04378   VTList.push_back(Result);
04379   return Result;
04380 }
04381 
04382 
04383 /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
04384 /// specified operands.  If the resultant node already exists in the DAG,
04385 /// this does not modify the specified node, instead it returns the node that
04386 /// already exists.  If the resultant node does not exist in the DAG, the
04387 /// input node is returned.  As a degenerate case, if you specify the same
04388 /// input operands as the node already has, the input node is returned.
04389 SDValue SelectionDAG::UpdateNodeOperands(SDValue InN, SDValue Op) {
04390   SDNode *N = InN.getNode();
04391   assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
04392   
04393   // Check to see if there is no change.
04394   if (Op == N->getOperand(0)) return InN;
04395   
04396   // See if the modified node already exists.
04397   void *InsertPos = 0;
04398   if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
04399     return SDValue(Existing, InN.getResNo());
04400   
04401   // Nope it doesn't.  Remove the node from its current place in the maps.
04402   if (InsertPos)
04403     if (!RemoveNodeFromCSEMaps(N))
04404       InsertPos = 0;
04405   
04406   // Now we update the operands.
04407   N->OperandList[0].set(Op);
04408   
04409   // If this gets put into a CSE map, add it.
04410   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
04411   return InN;
04412 }
04413 
04414 SDValue SelectionDAG::
04415 UpdateNodeOperands(SDValue InN, SDValue Op1, SDValue Op2) {
04416   SDNode *N = InN.getNode();
04417   assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
04418   
04419   // Check to see if there is no change.
04420   if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
04421     return InN;   // No operands changed, just return the input node.
04422   
04423   // See if the modified node already exists.
04424   void *InsertPos = 0;
04425   if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
04426     return SDValue(Existing, InN.getResNo());
04427   
04428   // Nope it doesn't.  Remove the node from its current place in the maps.
04429   if (InsertPos)
04430     if (!RemoveNodeFromCSEMaps(N))
04431       InsertPos = 0;
04432   
04433   // Now we update the operands.
04434   if (N->OperandList[0] != Op1)
04435     N->OperandList[0].set(Op1);
04436   if (N->OperandList[1] != Op2)
04437     N->OperandList[1].set(Op2);
04438   
04439   // If this gets put into a CSE map, add it.
04440   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
04441   return InN;
04442 }
04443 
04444 SDValue SelectionDAG::
04445 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, SDValue Op3) {
04446   SDValue Ops[] = { Op1, Op2, Op3 };
04447   return UpdateNodeOperands(N, Ops, 3);
04448 }
04449 
04450 SDValue SelectionDAG::
04451 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2, 
04452                    SDValue Op3, SDValue Op4) {
04453   SDValue Ops[] = { Op1, Op2, Op3, Op4 };
04454   return UpdateNodeOperands(N, Ops, 4);
04455 }
04456 
04457 SDValue SelectionDAG::
04458 UpdateNodeOperands(SDValue N, SDValue Op1, SDValue Op2,
04459                    SDValue Op3, SDValue Op4, SDValue Op5) {
04460   SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
04461   return UpdateNodeOperands(N, Ops, 5);
04462 }
04463 
04464 SDValue SelectionDAG::
04465 UpdateNodeOperands(SDValue InN, const SDValue *Ops, unsigned NumOps) {
04466   SDNode *N = InN.getNode();
04467   assert(N->getNumOperands() == NumOps &&
04468          "Update with wrong number of operands");
04469   
04470   // Check to see if there is no change.
04471   bool AnyChange = false;
04472   for (unsigned i = 0; i != NumOps; ++i) {
04473     if (Ops[i] != N->getOperand(i)) {
04474       AnyChange = true;
04475       break;
04476     }
04477   }
04478   
04479   // No operands changed, just return the input node.
04480   if (!AnyChange) return InN;
04481   
04482   // See if the modified node already exists.
04483   void *InsertPos = 0;
04484   if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, NumOps, InsertPos))
04485     return SDValue(Existing, InN.getResNo());
04486   
04487   // Nope it doesn't.  Remove the node from its current place in the maps.
04488   if (InsertPos)
04489     if (!RemoveNodeFromCSEMaps(N))
04490       InsertPos = 0;
04491   
04492   // Now we update the operands.
04493   for (unsigned i = 0; i != NumOps; ++i)
04494     if (N->OperandList[i] != Ops[i])
04495       N->OperandList[i].set(Ops[i]);
04496 
04497   // If this gets put into a CSE map, add it.
04498   if (InsertPos) CSEMap.InsertNode(N, InsertPos);
04499   return InN;
04500 }
04501 
04502 /// DropOperands - Release the operands and set this node to have
04503 /// zero operands.
04504 void SDNode::DropOperands() {
04505   // Unlike the code in MorphNodeTo that does this, we don't need to
04506   // watch for dead nodes here.
04507   for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
04508     SDUse &Use = *I++;
04509     Use.set(SDValue());
04510   }
04511 }
04512 
04513 /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
04514 /// machine opcode.
04515 ///
04516 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04517                                    MVT VT) {
04518   SDVTList VTs = getVTList(VT);
04519   return SelectNodeTo(N, MachineOpc, VTs, 0, 0);
04520 }
04521 
04522 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04523                                    MVT VT, SDValue Op1) {
04524   SDVTList VTs = getVTList(VT);
04525   SDValue Ops[] = { Op1 };
04526   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
04527 }
04528 
04529 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04530                                    MVT VT, SDValue Op1,
04531                                    SDValue Op2) {
04532   SDVTList VTs = getVTList(VT);
04533   SDValue Ops[] = { Op1, Op2 };
04534   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
04535 }
04536 
04537 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04538                                    MVT VT, SDValue Op1,
04539                                    SDValue Op2, SDValue Op3) {
04540   SDVTList VTs = getVTList(VT);
04541   SDValue Ops[] = { Op1, Op2, Op3 };
04542   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
04543 }
04544 
04545 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04546                                    MVT VT, const SDValue *Ops,
04547                                    unsigned NumOps) {
04548   SDVTList VTs = getVTList(VT);
04549   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
04550 }
04551 
04552 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04553                                    MVT VT1, MVT VT2, const SDValue *Ops,
04554                                    unsigned NumOps) {
04555   SDVTList VTs = getVTList(VT1, VT2);
04556   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
04557 }
04558 
04559 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04560                                    MVT VT1, MVT VT2) {
04561   SDVTList VTs = getVTList(VT1, VT2);
04562   return SelectNodeTo(N, MachineOpc, VTs, (SDValue *)0, 0);
04563 }
04564 
04565 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04566                                    MVT VT1, MVT VT2, MVT VT3,
04567                                    const SDValue *Ops, unsigned NumOps) {
04568   SDVTList VTs = getVTList(VT1, VT2, VT3);
04569   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
04570 }
04571 
04572 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04573                                    MVT VT1, MVT VT2, MVT VT3, MVT VT4,
04574                                    const SDValue *Ops, unsigned NumOps) {
04575   SDVTList VTs = getVTList(VT1, VT2, VT3, VT4);
04576   return SelectNodeTo(N, MachineOpc, VTs, Ops, NumOps);
04577 }
04578 
04579 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 
04580                                    MVT VT1, MVT VT2,
04581                                    SDValue Op1) {
04582   SDVTList VTs = getVTList(VT1, VT2);
04583   SDValue Ops[] = { Op1 };
04584   return SelectNodeTo(N, MachineOpc, VTs, Ops, 1);
04585 }
04586 
04587 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc, 
04588                                    MVT VT1, MVT VT2,
04589                                    SDValue Op1, SDValue Op2) {
04590   SDVTList VTs = getVTList(VT1, VT2);
04591   SDValue Ops[] = { Op1, Op2 };
04592   return SelectNodeTo(N, MachineOpc, VTs, Ops, 2);
04593 }
04594 
04595 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04596                                    MVT VT1, MVT VT2,
04597                                    SDValue Op1, SDValue Op2, 
04598                                    SDValue Op3) {
04599   SDVTList VTs = getVTList(VT1, VT2);
04600   SDValue Ops[] = { Op1, Op2, Op3 };
04601   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
04602 }
04603 
04604 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04605                                    MVT VT1, MVT VT2, MVT VT3,
04606                                    SDValue Op1, SDValue Op2, 
04607                                    SDValue Op3) {
04608   SDVTList VTs = getVTList(VT1, VT2, VT3);
04609   SDValue Ops[] = { Op1, Op2, Op3 };
04610   return SelectNodeTo(N, MachineOpc, VTs, Ops, 3);
04611 }
04612 
04613 SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
04614                                    SDVTList VTs, const SDValue *Ops,
04615                                    unsigned NumOps) {
04616   return MorphNodeTo(N, ~MachineOpc, VTs, Ops, NumOps);
04617 }
04618 
04619 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04620                                   MVT VT) {
04621   SDVTList VTs = getVTList(VT);
04622   return MorphNodeTo(N, Opc, VTs, 0, 0);
04623 }
04624 
04625 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04626                                   MVT VT, SDValue Op1) {
04627   SDVTList VTs = getVTList(VT);
04628   SDValue Ops[] = { Op1 };
04629   return MorphNodeTo(N, Opc, VTs, Ops, 1);
04630 }
04631 
04632 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04633                                   MVT VT, SDValue Op1,
04634                                   SDValue Op2) {
04635   SDVTList VTs = getVTList(VT);
04636   SDValue Ops[] = { Op1, Op2 };
04637   return MorphNodeTo(N, Opc, VTs, Ops, 2);
04638 }
04639 
04640 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04641                                   MVT VT, SDValue Op1,
04642                                   SDValue Op2, SDValue Op3) {
04643   SDVTList VTs = getVTList(VT);
04644   SDValue Ops[] = { Op1, Op2, Op3 };
04645   return MorphNodeTo(N, Opc, VTs, Ops, 3);
04646 }
04647 
04648 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04649                                   MVT VT, const SDValue *Ops,
04650                                   unsigned NumOps) {
04651   SDVTList VTs = getVTList(VT);
04652   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
04653 }
04654 
04655 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04656                                   MVT VT1, MVT VT2, const SDValue *Ops,
04657                                   unsigned NumOps) {
04658   SDVTList VTs = getVTList(VT1, VT2);
04659   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
04660 }
04661 
04662 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04663                                   MVT VT1, MVT VT2) {
04664   SDVTList VTs = getVTList(VT1, VT2);
04665   return MorphNodeTo(N, Opc, VTs, (SDValue *)0, 0);
04666 }
04667 
04668 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04669                                   MVT VT1, MVT VT2, MVT VT3,
04670                                   const SDValue *Ops, unsigned NumOps) {
04671   SDVTList VTs = getVTList(VT1, VT2, VT3);
04672   return MorphNodeTo(N, Opc, VTs, Ops, NumOps);
04673 }
04674 
04675 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 
04676                                   MVT VT1, MVT VT2,
04677                                   SDValue Op1) {
04678   SDVTList VTs = getVTList(VT1, VT2);
04679   SDValue Ops[] = { Op1 };
04680   return MorphNodeTo(N, Opc, VTs, Ops, 1);
04681 }
04682 
04683 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc, 
04684                                   MVT VT1, MVT VT2,
04685                                   SDValue Op1, SDValue Op2) {
04686   SDVTList VTs = getVTList(VT1, VT2);
04687   SDValue Ops[] = { Op1, Op2 };
04688   return MorphNodeTo(N, Opc, VTs, Ops, 2);
04689 }
04690 
04691 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04692                                   MVT VT1, MVT VT2,
04693                                   SDValue Op1, SDValue Op2, 
04694                                   SDValue Op3) {
04695   SDVTList VTs = getVTList(VT1, VT2);
04696   SDValue Ops[] = { Op1, Op2, Op3 };
04697   return MorphNodeTo(N, Opc, VTs, Ops, 3);
04698 }
04699 
04700 /// MorphNodeTo - These *mutate* the specified node to have the specified
04701 /// return type, opcode, and operands.
04702 ///
04703 /// Note that MorphNodeTo returns the resultant node.  If there is already a
04704 /// node of the specified opcode and operands, it returns that node instead of
04705 /// the current one.
04706 ///
04707 /// Using MorphNodeTo is faster than creating a new node and swapping it in
04708 /// with ReplaceAllUsesWith both because it often avoids allocating a new
04709 /// node, and because it doesn't require CSE recalculation for any of
04710 /// the node's users.
04711 ///
04712 SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
04713                                   SDVTList VTs, const SDValue *Ops,
04714                                   unsigned NumOps) {
04715   // If an identical node already exists, use it.
04716   void *IP = 0;
04717   if (VTs.VTs[VTs.NumVTs-1] != MVT::Flag) {
04718     FoldingSetNodeID ID;
04719     AddNodeIDNode(ID, Opc, VTs, Ops, NumOps);
04720     if (SDNode *ON = CSEMap.FindNodeOrInsertPos(ID, IP))
04721       return ON;
04722   }
04723 
04724   if (!RemoveNodeFromCSEMaps(N))
04725     IP = 0;
04726 
04727   // Start the morphing.
04728   N->NodeType = Opc;
04729   N->ValueList = VTs.VTs;
04730   N->NumValues = VTs.NumVTs;
04731   
04732   // Clear the operands list, updating used nodes to remove this from their
04733   // use list.  Keep track of any operands that become dead as a result.
04734   SmallPtrSet<SDNode*, 16> DeadNodeSet;
04735   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
04736     SDUse &Use = *I++;
04737     SDNode *Used = Use.getNode();
04738     Use.set(SDValue());
04739     if (Used->use_empty())
04740       DeadNodeSet.insert(Used);
04741   }
04742 
04743   // If NumOps is larger than the # of operands we currently have, reallocate
04744   // the operand list.
04745   if (NumOps > N->NumOperands) {
04746     if (N->OperandsNeedDelete)
04747       delete[] N->OperandList;
04748 
04749     if (N->isMachineOpcode()) {
04750       // We're creating a final node that will live unmorphed for the
04751       // remainder of the current SelectionDAG iteration, so we can allocate
04752       // the operands directly out of a pool with no recycling metadata.
04753       N->OperandList = OperandAllocator.Allocate<SDUse>(NumOps);
04754       N->OperandsNeedDelete = false;
04755     } else {
04756       N->OperandList = new SDUse[NumOps];
04757       N->OperandsNeedDelete = true;
04758     }
04759   }
04760   
04761   // Assign the new operands.
04762   N->NumOperands = NumOps;
04763   for (unsigned i = 0, e = NumOps; i != e; ++i) {
04764     N->OperandList[i].setUser(N);
04765     N->OperandList[i].setInitial(Ops[i]);
04766   }
04767 
04768   // Delete any nodes that are still dead after adding the uses for the
04769   // new operands.
04770   SmallVector<SDNode *, 16> DeadNodes;
04771   for (SmallPtrSet<SDNode *, 16>::iterator I = DeadNodeSet.begin(),
04772        E = DeadNodeSet.end(); I != E; ++I)
04773     if ((*I)->use_empty())
04774       DeadNodes.push_back(*I);
04775   RemoveDeadNodes(DeadNodes);
04776 
04777   if (IP)
04778     CSEMap.InsertNode(N, IP);   // Memoize the new node.
04779   return N;
04780 }
04781 
04782 
04783 /// getTargetNode - These are used for target selectors to create a new node
04784 /// with specified return type(s), target opcode, and operands.
04785 ///
04786 /// Note that getTargetNode returns the resultant node.  If there is already a
04787 /// node of the specified opcode and operands, it returns that node instead of
04788 /// the current one.
04789 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT) {
04790   return getNode(~Opcode, VT).getNode();
04791 }
04792 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT) {
04793   return getNode(~Opcode, dl, VT).getNode();
04794 }
04795 
04796 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT, SDValue Op1) {
04797   return getNode(~Opcode, VT, Op1).getNode();
04798 }
04799 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
04800                                     SDValue Op1) {
04801   return getNode(~Opcode, dl, VT, Op1).getNode();
04802 }
04803 
04804 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
04805                                     SDValue Op1, SDValue Op2) {
04806   return getNode(~Opcode, VT, Op1, Op2).getNode();
04807 }
04808 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
04809                                     SDValue Op1, SDValue Op2) {
04810   return getNode(~Opcode, dl, VT, Op1, Op2).getNode();
04811 }
04812 
04813 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
04814                                     SDValue Op1, SDValue Op2,
04815                                     SDValue Op3) {
04816   return getNode(~Opcode, VT, Op1, Op2, Op3).getNode();
04817 }
04818 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
04819                                     SDValue Op1, SDValue Op2,
04820                                     SDValue Op3) {
04821   return getNode(~Opcode, dl, VT, Op1, Op2, Op3).getNode();
04822 }
04823 
04824 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT,
04825                                     const SDValue *Ops, unsigned NumOps) {
04826   return getNode(~Opcode, VT, Ops, NumOps).getNode();
04827 }
04828 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT,
04829                                     const SDValue *Ops, unsigned NumOps) {
04830   return getNode(~Opcode, dl, VT, Ops, NumOps).getNode();
04831 }
04832 
04833 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2) {
04834   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04835   SDValue Op;
04836   return getNode(~Opcode, VTs, 2, &Op, 0).getNode();
04837 }
04838 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 
04839                                     MVT VT1, MVT VT2) {
04840   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04841   SDValue Op;
04842   return getNode(~Opcode, dl, VTs, 2, &Op, 0).getNode();
04843 }
04844 
04845 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
04846                                     MVT VT2, SDValue Op1) {
04847   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04848   return getNode(~Opcode, VTs, 2, &Op1, 1).getNode();
04849 }
04850 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
04851                                     MVT VT2, SDValue Op1) {
04852   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04853   return getNode(~Opcode, dl, VTs, 2, &Op1, 1).getNode();
04854 }
04855 
04856 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
04857                                     MVT VT2, SDValue Op1,
04858                                     SDValue Op2) {
04859   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04860   SDValue Ops[] = { Op1, Op2 };
04861   return getNode(~Opcode, VTs, 2, Ops, 2).getNode();
04862 }
04863 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
04864                                     MVT VT2, SDValue Op1,
04865                                     SDValue Op2) {
04866   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04867   SDValue Ops[] = { Op1, Op2 };
04868   return getNode(~Opcode, dl, VTs, 2, Ops, 2).getNode();
04869 }
04870 
04871 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
04872                                     MVT VT2, SDValue Op1,
04873                                     SDValue Op2, SDValue Op3) {
04874   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04875   SDValue Ops[] = { Op1, Op2, Op3 };
04876   return getNode(~Opcode, VTs, 2, Ops, 3).getNode();
04877 }
04878 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
04879                                     MVT VT2, SDValue Op1,
04880                                     SDValue Op2, SDValue Op3) {
04881   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04882   SDValue Ops[] = { Op1, Op2, Op3 };
04883   return getNode(~Opcode, dl, VTs, 2, Ops, 3).getNode();
04884 }
04885 
04886 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2,
04887                                     const SDValue *Ops, unsigned NumOps) {
04888   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04889   return getNode(~Opcode, VTs, 2, Ops, NumOps).getNode();
04890 }
04891 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, 
04892                                     MVT VT1, MVT VT2,
04893                                     const SDValue *Ops, unsigned NumOps) {
04894   const MVT *VTs = getNodeValueTypes(VT1, VT2);
04895   return getNode(~Opcode, dl, VTs, 2, Ops, NumOps).getNode();
04896 }
04897 
04898 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
04899                                     SDValue Op1, SDValue Op2) {
04900   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04901   SDValue Ops[] = { Op1, Op2 };
04902   return getNode(~Opcode, VTs, 3, Ops, 2).getNode();
04903 }
04904 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
04905                                     MVT VT1, MVT VT2, MVT VT3,
04906                                     SDValue Op1, SDValue Op2) {
04907   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04908   SDValue Ops[] = { Op1, Op2 };
04909   return getNode(~Opcode, dl, VTs, 3, Ops, 2).getNode();
04910 }
04911 
04912 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
04913                                     SDValue Op1, SDValue Op2,
04914                                     SDValue Op3) {
04915   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04916   SDValue Ops[] = { Op1, Op2, Op3 };
04917   return getNode(~Opcode, VTs, 3, Ops, 3).getNode();
04918 }
04919 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
04920                                     MVT VT1, MVT VT2, MVT VT3,
04921                                     SDValue Op1, SDValue Op2,
04922                                     SDValue Op3) {
04923   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04924   SDValue Ops[] = { Op1, Op2, Op3 };
04925   return getNode(~Opcode, dl, VTs, 3, Ops, 3).getNode();
04926 }
04927 
04928 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1, MVT VT2, MVT VT3,
04929                                     const SDValue *Ops, unsigned NumOps) {
04930   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04931   return getNode(~Opcode, VTs, 3, Ops, NumOps).getNode();
04932 }
04933 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
04934                                     MVT VT1, MVT VT2, MVT VT3,
04935                                     const SDValue *Ops, unsigned NumOps) {
04936   const MVT *VTs = getNodeValueTypes(VT1, VT2, VT3);
04937   return getNode(~Opcode, dl, VTs, 3, Ops, NumOps).getNode();
04938 }
04939 
04940 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, MVT VT1,
04941                                     MVT VT2, MVT VT3, MVT VT4,
04942                                     const SDValue *Ops, unsigned NumOps) {
04943   std::vector<MVT> VTList;
04944   VTList.push_back(VT1);
04945   VTList.push_back(VT2);
04946   VTList.push_back(VT3);
04947   VTList.push_back(VT4);
04948   const MVT *VTs = getNodeValueTypes(VTList);
04949   return getNode(~Opcode, VTs, 4, Ops, NumOps).getNode();
04950 }
04951 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl, MVT VT1,
04952                                     MVT VT2, MVT VT3, MVT VT4,
04953                                     const SDValue *Ops, unsigned NumOps) {
04954   std::vector<MVT> VTList;
04955   VTList.push_back(VT1);
04956   VTList.push_back(VT2);
04957   VTList.push_back(VT3);
04958   VTList.push_back(VT4);
04959   const MVT *VTs = getNodeValueTypes(VTList);
04960   return getNode(~Opcode, dl, VTs, 4, Ops, NumOps).getNode();
04961 }
04962 
04963 SDNode *SelectionDAG::getTargetNode(unsigned Opcode,
04964                                     const std::vector<MVT> &ResultTys,
04965                                     const SDValue *Ops, unsigned NumOps) {
04966   const MVT *VTs = getNodeValueTypes(ResultTys);
04967   return getNode(~Opcode, VTs, ResultTys.size(),
04968                  Ops, NumOps).getNode();
04969 }
04970 SDNode *SelectionDAG::getTargetNode(unsigned Opcode, DebugLoc dl,
04971                                     const std::vector<MVT> &ResultTys,
04972                                     const SDValue *Ops, unsigned NumOps) {
04973   const MVT *VTs = getNodeValueTypes(ResultTys);
04974   return getNode(~Opcode, dl, VTs, ResultTys.size(),
04975                  Ops, NumOps).getNode();
04976 }
04977 
04978 /// getNodeIfExists - Get the specified node if it's already available, or
04979 /// else return NULL.
04980 SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
04981                                       const SDValue *Ops, unsigned NumOps) {
04982   if (VTList.VTs[VTList.NumVTs-1] != MVT::Flag) {
04983     FoldingSetNodeID ID;
04984     AddNodeIDNode(ID, Opcode, VTList, Ops, NumOps);
04985     void *IP = 0;
04986     if (SDNode *E = CSEMap.FindNodeOrInsertPos(ID, IP))
04987       return E;
04988   }
04989   return NULL;
04990 }
04991 
04992 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
04993 /// This can cause recursive merging of nodes in the DAG.
04994 ///
04995 /// This version assumes From has a single result value.
04996 ///
04997 void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To,
04998                                       DAGUpdateListener *UpdateListener) {
04999   SDNode *From = FromN.getNode();
05000   assert(From->getNumValues() == 1 && FromN.getResNo() == 0 && 
05001          "Cannot replace with this method!");
05002   assert(From != To.getNode() && "Cannot replace uses of with self");
05003 
05004   // Iterate over all the existing uses of From. New uses will be added
05005   // to the beginning of the use list, which we avoid visiting.
05006   // This specifically avoids visiting uses of From that arise while the
05007   // replacement is happening, because any such uses would be the result
05008   // of CSE: If an existing node looks like From after one of its operands
05009   // is replaced by To, we don't want to replace of all its users with To
05010   // too. See PR3018 for more info.
05011   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
05012   while (UI != UE) {
05013     SDNode *User = *UI;
05014 
05015     // This node is about to morph, remove its old self from the CSE maps.
05016     RemoveNodeFromCSEMaps(User);
05017 
05018     // A user can appear in a use list multiple times, and when this
05019     // happens the uses are usually next to each other in the list.
05020     // To help reduce the number of CSE recomputations, process all
05021     // the uses of this user that we can find this way.
05022     do {
05023       SDUse &Use = UI.getUse();
05024       ++UI;
05025       Use.set(To);
05026     } while (UI != UE && *UI == User);
05027 
05028     // Now that we have modified User, add it back to the CSE maps.  If it
05029     // already exists there, recursively merge the results together.
05030     AddModifiedNodeToCSEMaps(User, UpdateListener);
05031   }
05032 }
05033 
05034 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
05035 /// This can cause recursive merging of nodes in the DAG.
05036 ///
05037 /// This version assumes From/To have matching types and numbers of result
05038 /// values.
05039 ///
05040 void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To,
05041                                       DAGUpdateListener *UpdateListener) {
05042   assert(From->getVTList().VTs == To->getVTList().VTs &&
05043          From->getNumValues() == To->getNumValues() &&
05044          "Cannot use this version of ReplaceAllUsesWith!");
05045 
05046   // Handle the trivial case.
05047   if (From == To)
05048     return;
05049 
05050   // Iterate over just the existing users of From. See the comments in
05051   // the ReplaceAllUsesWith above.
05052   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
05053   while (UI != UE) {
05054     SDNode *User = *UI;
05055 
05056     // This node is about to morph, remove its old self from the CSE maps.
05057     RemoveNodeFromCSEMaps(User);
05058 
05059     // A user can appear in a use list multiple times, and when this
05060     // happens the uses are usually next to each other in the list.
05061     // To help reduce the number of CSE recomputations, process all
05062     // the uses of this user that we can find this way.
05063     do {
05064       SDUse &Use = UI.getUse();
05065       ++UI;
05066       Use.setNode(To);
05067     } while (UI != UE && *UI == User);
05068 
05069     // Now that we have modified User, add it back to the CSE maps.  If it
05070     // already exists there, recursively merge the results together.
05071     AddModifiedNodeToCSEMaps(User, UpdateListener);
05072   }
05073 }
05074 
05075 /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
05076 /// This can cause recursive merging of nodes in the DAG.
05077 ///
05078 /// This version can replace From with any result values.  To must match the
05079 /// number and types of values returned by From.
05080 void SelectionDAG::ReplaceAllUsesWith(SDNode *From,
05081                                       const SDValue *To,
05082                                       DAGUpdateListener *UpdateListener) {
05083   if (From->getNumValues() == 1)  // Handle the simple case efficiently.
05084     return ReplaceAllUsesWith(SDValue(From, 0), To[0], UpdateListener);
05085 
05086   // Iterate over just the existing users of From. See the comments in
05087   // the ReplaceAllUsesWith above.
05088   SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
05089   while (UI != UE) {
05090     SDNode *User = *UI;
05091 
05092     // This node is about to morph, remove its old self from the CSE maps.
05093     RemoveNodeFromCSEMaps(User);
05094 
05095     // A user can appear in a use list multiple times, and when this
05096     // happens the uses are usually next to each other in the list.
05097     // To help reduce the number of CSE recomputations, process all
05098     // the uses of this user that we can find this way.
05099     do {
05100       SDUse &Use = UI.getUse();
05101       const SDValue &ToOp = To[Use.getResNo()];
05102       ++UI;
05103       Use.set(ToOp);
05104     } while (UI != UE && *UI == User);
05105 
05106     // Now that we have modified User, add it back to the CSE maps.  If it
05107     // already exists there, recursively merge the results together.
05108     AddModifiedNodeToCSEMaps(User, UpdateListener);
05109   }
05110 }
05111 
05112 /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
05113 /// uses of other values produced by From.getNode() alone.  The Deleted
05114 /// vector is handled the same way as for ReplaceAllUsesWith.
05115 void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To,
05116                                              DAGUpdateListener *UpdateListener){
05117   // Handle the really simple, really trivial case efficiently.
05118   if (From == To) return;
05119 
05120   // Handle the simple, trivial, case efficiently.
05121   if (From.getNode()->getNumValues() == 1) {
05122     ReplaceAllUsesWith(From, To, UpdateListener);
05123     return;
05124   }
05125 
05126   // Iterate over just the existing users of From. See the comments in
05127   // the ReplaceAllUsesWith above.
05128   SDNode::use_iterator UI = From.getNode()->use_begin(),
05129                        UE = From.getNode()->use_end();
05130   while (UI != UE) {
05131     SDNode *User = *UI;
05132     bool UserRemovedFromCSEMaps = false;
05133 
05134     // A user can appear in a use list multiple times, and when this
05135     // happens the uses are usually next to each other in the list.
05136     // To help reduce the number of CSE recomputations, process all
05137     // the uses of this user that we can find this way.
05138     do {
05139       SDUse &Use = UI.getUse();
05140 
05141       // Skip uses of different values from the same node.
05142       if (Use.getResNo() != From.getResNo()) {
05143         ++UI;
05144         continue;
05145       }
05146 
05147       // If this node hasn't been modified yet, it's still in the CSE maps,
05148       // so remove its old self from the CSE maps.
05149       if (!UserRemovedFromCSEMaps) {
05150         RemoveNodeFromCSEMaps(User);
05151         UserRemovedFromCSEMaps = true;
05152       }
05153 
05154       ++UI;
05155       Use.set(To);
05156     } while (UI != UE && *UI == User);
05157 
05158     // We are iterating over all uses of the From node, so if a use
05159     // doesn't use the specific value, no changes are made.
05160     if (!UserRemovedFromCSEMaps)
05161       continue;
05162 
05163     // Now that we have modified User, add it back to the CSE maps.  If it
05164     // already exists there, recursively merge the results together.
05165     AddModifiedNodeToCSEMaps(User, UpdateListener);
05166   }
05167 }
05168 
05169 namespace {
05170   /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
05171   /// to record information about a use.
05172   struct UseMemo {
05173     SDNode *User;
05174     unsigned Index;
05175     SDUse *Use;
05176   };
05177 
05178   /// operator< - Sort Memos by User.
05179   bool operator<(const UseMemo &L, const UseMemo &R) {
05180     return (intptr_t)L.User < (intptr_t)R.User;
05181   }
05182 }
05183 
05184 /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
05185 /// uses of other values produced by From.getNode() alone.  The same value
05186 /// may appear in both the From and To list.  The Deleted vector is
05187 /// handled the same way as for ReplaceAllUsesWith.
05188 void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
05189                                               const SDValue *To,
05190                                               unsigned Num,
05191                                               DAGUpdateListener *UpdateListener){
05192   // Handle the simple, trivial case efficiently.
05193   if (Num == 1)
05194     return ReplaceAllUsesOfValueWith(*From, *To, UpdateListener);
05195 
05196   // Read up all the uses and make records of them. This helps
05197   // processing new uses that are introduced during the
05198   // replacement process.
05199   SmallVector<UseMemo, 4> Uses;
05200   for (unsigned i = 0; i != Num; ++i) {
05201     unsigned FromResNo = From[i].getResNo();
05202     SDNode *FromNode = From[i].getNode();
05203     for (SDNode::use_iterator UI = FromNode->use_begin(), 
05204          E = FromNode->use_end(); UI != E; ++UI) {
05205       SDUse &Use = UI.getUse();
05206       if (Use.getResNo() == FromResNo) {
05207         UseMemo Memo = { *UI, i, &Use };
05208         Uses.push_back(Memo);
05209       }
05210     }
05211   }
05212 
05213   // Sort the uses, so that all the uses from a given User are together.
05214   std::sort(Uses.begin(), Uses.end());
05215 
05216   for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
05217        UseIndex != UseIndexEnd; ) {
05218     // We know that this user uses some value of From.  If it is the right
05219     // value, update it.
05220     SDNode *User = Uses[UseIndex].User;
05221 
05222     // This node is about to morph, remove its old self from the CSE maps.
05223     RemoveNodeFromCSEMaps(User);
05224 
05225     // The Uses array is sorted, so all the uses for a given User
05226     // are next to each other in the list.
05227     // To help reduce the number of CSE recomputations, process all
05228     // the uses of this user that we can find this way.
05229     do {
05230       unsigned i = Uses[UseIndex].Index;
05231       SDUse &Use = *Uses[UseIndex].Use;
05232       ++UseIndex;
05233 
05234       Use.set(To[i]);
05235     } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
05236 
05237     // Now that we have modified User, add it back to the CSE maps.  If it
05238     // already exists there, recursively merge the results together.
05239     AddModifiedNodeToCSEMaps(User, UpdateListener);
05240   }
05241 }
05242 
05243 /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
05244 /// based on their topological order. It returns the maximum id and a vector
05245 /// of the SDNodes* in assigned order by reference.
05246 unsigned SelectionDAG::AssignTopologicalOrder() {
05247 
05248   unsigned DAGSize = 0;
05249 
05250   // SortedPos tracks the progress of the algorithm. Nodes before it are
05251   // sorted, nodes after it are unsorted. When the algorithm completes
05252   // it is at the end of the list.
05253   allnodes_iterator SortedPos = allnodes_begin();
05254 
05255   // Visit all the nodes. Move nodes with no operands to the front of
05256   // the list immediately. Annotate nodes that do have operands with their
05257   // operand count. Before we do this, the Node Id fields of the nodes
05258   // may contain arbitrary values. After, the Node Id fields for nodes
05259   // before SortedPos will contain the topological sort index, and the
05260   // Node Id fields for nodes At SortedPos and after will contain the
05261   // count of outstanding operands.
05262   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
05263     SDNode *N = I++;
05264     unsigned Degree = N->getNumOperands();
05265     if (Degree == 0) {
05266       // A node with no uses, add it to the result array immediately.
05267       N->setNodeId(DAGSize++);
05268       allnodes_iterator Q = N;
05269       if (Q != SortedPos)
05270         SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
05271       ++SortedPos;
05272     } else {
05273       // Temporarily use the Node Id as scratch space for the degree count.
05274       N->setNodeId(Degree);
05275     }
05276   }
05277 
05278   // Visit all the nodes. As we iterate, moves nodes into sorted order,
05279   // such that by the time the end is reached all nodes will be sorted.
05280   for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ++I) {
05281     SDNode *N = I;
05282     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
05283          UI != UE; ++UI) {
05284       SDNode *P = *UI;
05285       unsigned Degree = P->getNodeId();
05286       --Degree;
05287       if (Degree == 0) {
05288         // All of P's operands are sorted, so P may sorted now.
05289         P->setNodeId(DAGSize++);
05290         if (P != SortedPos)
05291           SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
05292         ++SortedPos;
05293       } else {
05294         // Update P's outstanding operand count.
05295         P->setNodeId(Degree);
05296       }
05297     }
05298   }
05299 
05300   assert(SortedPos == AllNodes.end() &&
05301          "Topological sort incomplete!");
05302   assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
05303          "First node in topological sort is not the entry token!");
05304   assert(AllNodes.front().getNodeId() == 0 &&
05305          "First node in topological sort has non-zero id!");
05306   assert(AllNodes.front().getNumOperands() == 0 &&
05307          "First node in topological sort has operands!");
05308   assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
05309          "Last node in topologic sort has unexpected id!");
05310   assert(AllNodes.back().use_empty() &&
05311          "Last node in topologic sort has users!");
05312   assert(DAGSize == allnodes_size() && "Node count mismatch!");
05313   return DAGSize;
05314 }
05315 
05316 
05317 
05318 //===----------------------------------------------------------------------===//
05319 //                              SDNode Class
05320 //===----------------------------------------------------------------------===//
05321 
05322 HandleSDNode::~HandleSDNode() {
05323   DropOperands();
05324 }
05325 
05326 GlobalAddressSDNode::GlobalAddressSDNode(bool isTarget, const GlobalValue *GA,
05327                                          MVT VT, int64_t o)
05328   : SDNode(isa<GlobalVariable>(GA) &&
05329            cast<GlobalVariable>(GA)->isThreadLocal() ?
05330            // Thread Local
05331            (isTarget ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress) :
05332            // Non Thread Local
05333            (isTarget ? ISD::TargetGlobalAddress : ISD::GlobalAddress),
05334            getSDVTList(VT)), Offset(o) {
05335   TheGlobal = const_cast<GlobalValue*>(GA);
05336 }
05337 
05338 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, MVT memvt,
05339                      const Value *srcValue, int SVO,
05340                      unsigned alignment, bool vol)
05341  : SDNode(Opc, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
05342   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
05343   assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
05344   assert(getAlignment() == alignment && "Alignment representation error!");
05345   assert(isVolatile() == vol && "Volatile representation error!");
05346 }
05347 
05348 MemSDNode::MemSDNode(unsigned Opc, SDVTList VTs, const SDValue *Ops,
05349                      unsigned NumOps, MVT memvt, const Value *srcValue,
05350                      int SVO, unsigned alignment, bool vol)
05351    : SDNode(Opc, VTs, Ops, NumOps),
05352      MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
05353   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
05354   assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
05355   assert(getAlignment() == alignment && "Alignment representation error!");
05356   assert(isVolatile() == vol && "Volatile representation error!");
05357 }
05358 
05359 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, MVT memvt,
05360                      const Value *srcValue, int SVO,
05361                      unsigned alignment, bool vol)
05362  : SDNode(Opc, dl, VTs), MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
05363   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
05364   assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
05365   assert(getAlignment() == alignment && "Alignment representation error!");
05366   assert(isVolatile() == vol && "Volatile representation error!");
05367 }
05368 
05369 MemSDNode::MemSDNode(unsigned Opc, DebugLoc dl, SDVTList VTs, 
05370                      const SDValue *Ops,
05371                      unsigned NumOps, MVT memvt, const Value *srcValue,
05372                      int SVO, unsigned alignment, bool vol)
05373    : SDNode(Opc, dl, VTs, Ops, NumOps),
05374      MemoryVT(memvt), SrcValue(srcValue), SVOffset(SVO) {
05375   SubclassData = encodeMemSDNodeFlags(0, ISD::UNINDEXED, vol, alignment);
05376   assert(isPowerOf2_32(alignment) && "Alignment is not a power of 2!");
05377   assert(getAlignment() == alignment && "Alignment representation error!");
05378   assert(isVolatile() == vol && "Volatile representation error!");
05379 }
05380 
05381 /// getMemOperand - Return a MachineMemOperand object describing the memory
05382 /// reference performed by this memory reference.
05383 MachineMemOperand MemSDNode::getMemOperand() const {
05384   int Flags = 0;
05385   if (isa<LoadSDNode>(this))
05386     Flags = MachineMemOperand::MOLoad;
05387   else if (isa<StoreSDNode>(this))
05388     Flags = MachineMemOperand::MOStore;
05389   else if (isa<AtomicSDNode>(this)) {
05390     Flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore;
05391   }
05392   else {
05393     const MemIntrinsicSDNode* MemIntrinNode = dyn_cast<MemIntrinsicSDNode>(this);
05394     assert(MemIntrinNode && "Unknown MemSDNode opcode!");
05395     if (MemIntrinNode->readMem()) Flags |= MachineMemOperand::MOLoad;
05396     if (MemIntrinNode->writeMem()) Flags |= MachineMemOperand::MOStore;
05397   }
05398 
05399   int Size = (getMemoryVT().getSizeInBits() + 7) >> 3;
05400   if (isVolatile()) Flags |= MachineMemOperand::MOVolatile;
05401   
05402   // Check if the memory reference references a frame index
05403   const FrameIndexSDNode *FI = 
05404   dyn_cast<const FrameIndexSDNode>(getBasePtr().getNode());
05405   if (!getSrcValue() && FI)
05406     return MachineMemOperand(PseudoSourceValue::getFixedStack(FI->getIndex()),
05407                              Flags, 0, Size, getAlignment());
05408   else
05409     return MachineMemOperand(getSrcValue(), Flags, getSrcValueOffset(),
05410                              Size, getAlignment());
05411 }
05412 
05413 /// Profile - Gather unique data for the node.
05414 ///
05415 void SDNode::Profile(FoldingSetNodeID &ID) const {
05416   AddNodeIDNode(ID, this);
05417 }
05418 
05419 /// getValueTypeList - Return a pointer to the specified value type.
05420 ///
05421 const MVT *SDNode::getValueTypeList(MVT VT) {
05422   if (VT.isExtended()) {
05423     static std::set<MVT, MVT::compareRawBits> EVTs;
05424     return &(*EVTs.insert(VT).first);
05425   } else {
05426     static MVT VTs[MVT::LAST_VALUETYPE];
05427     VTs[VT.getSimpleVT()] = VT;
05428     return &VTs[VT.getSimpleVT()];
05429   }
05430 }
05431 
05432 /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
05433 /// indicated value.  This method ignores uses of other values defined by this
05434 /// operation.
05435 bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
05436   assert(Value < getNumValues() && "Bad value!");
05437 
05438   // TODO: Only iterate over uses of a given value of the node
05439   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
05440     if (UI.getUse().getResNo() == Value) {
05441       if (NUses == 0)
05442         return false;
05443       --NUses;
05444     }
05445   }
05446 
05447   // Found exactly the right number of uses?
05448   return NUses == 0;
05449 }
05450 
05451 
05452 /// hasAnyUseOfValue - Return true if there are any use of the indicated
05453 /// value. This method ignores uses of other values defined by this operation.
05454 bool SDNode::hasAnyUseOfValue(unsigned Value) const {
05455   assert(Value < getNumValues() && "Bad value!");
05456 
05457   for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
05458     if (UI.getUse().getResNo() == Value)
05459       return true;
05460 
05461   return false;
05462 }
05463 
05464 
05465 /// isOnlyUserOf - Return true if this node is the only use of N.
05466 ///
05467 bool SDNode::isOnlyUserOf(SDNode *N) const {
05468   bool Seen = false;
05469   for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
05470     SDNode *User = *I;
05471     if (User == this)
05472       Seen = true;
05473     else
05474       return false;
05475   }
05476 
05477   return Seen;
05478 }
05479 
05480 /// isOperand - Return true if this node is an operand of N.
05481 ///
05482 bool SDValue::isOperandOf(SDNode *N) const {
05483   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
05484     if (*this == N->getOperand(i))
05485       return true;
05486   return false;
05487 }
05488 
05489 bool SDNode::isOperandOf(SDNode *N) const {
05490   for (unsigned i = 0, e = N->NumOperands; i != e; ++i)
05491     if (this == N->OperandList[i].getNode())
05492       return true;
05493   return false;
05494 }
05495 
05496 /// reachesChainWithoutSideEffects - Return true if this operand (which must
05497 /// be a chain) reaches the specified operand without crossing any 
05498 /// side-effecting instructions.  In practice, this looks through token
05499 /// factors and non-volatile loads.  In order to remain efficient, this only
05500 /// looks a couple of nodes in, it does not do an exhaustive search.
05501 bool SDValue::reachesChainWithoutSideEffects(SDValue Dest, 
05502                                                unsigned Depth) const {
05503   if (*this == Dest) return true;
05504   
05505   // Don't search too deeply, we just want to be able to see through
05506   // TokenFactor's etc.
05507   if (Depth == 0) return false;
05508   
05509   // If this is a token factor, all inputs to the TF happen in parallel.  If any
05510   // of the operands of the TF reach dest, then we can do the xform.
05511   if (getOpcode() == ISD::TokenFactor) {
05512     for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
05513       if (getOperand(i).reachesChainWithoutSideEffects(Dest, Depth-1))
05514         return true;
05515     return false;
05516   }
05517   
05518   // Loads don't have side effects, look through them.
05519   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
05520     if (!Ld->isVolatile())
05521       return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
05522   }
05523   return false;
05524 }
05525 
05526 
05527 static void findPredecessor(SDNode *N, const SDNode *P, bool &found,
05528                             SmallPtrSet<SDNode *, 32> &Visited) {
05529   if (found || !Visited.insert(N))
05530     return;
05531 
05532   for (unsigned i = 0, e = N->getNumOperands(); !found && i != e; ++i) {
05533     SDNode *Op = N->getOperand(i).getNode();
05534     if (Op == P) {
05535       found = true;
05536       return;
05537     }
05538     findPredecessor(Op, P, found, Visited);
05539   }
05540 }
05541 
05542 /// isPredecessorOf - Return true if this node is a predecessor of N. This node
05543 /// is either an operand of N or it can be reached by recursively traversing
05544 /// up the operands.
05545 /// NOTE: this is an expensive method. Use it carefully.
05546 bool SDNode::isPredecessorOf(SDNode *N) const {
05547   SmallPtrSet<SDNode *, 32> Visited;
05548   bool found = false;
05549   findPredecessor(N, this, found, Visited);
05550   return found;
05551 }
05552 
05553 uint64_t SDNode::getConstantOperandVal(unsigned Num) const {
05554   assert(Num < NumOperands && "Invalid child # of SDNode!");
05555   return cast<ConstantSDNode>(OperandList[Num])->getZExtValue();
05556 }
05557 
05558 std::string SDNode::getOperationName(const SelectionDAG *G) const {
05559   switch (getOpcode()) {
05560   default:
05561     if (getOpcode() < ISD::BUILTIN_OP_END)
05562       return "<<Unknown DAG Node>>";
05563     if (isMachineOpcode()) {
05564       if (G)
05565         if (const TargetInstrInfo *TII = G->getTarget().getInstrInfo())
05566           if (getMachineOpcode() < TII->getNumOpcodes())
05567             return TII->get(getMachineOpcode()).getName();
05568       return "<<Unknown Machine Node>>";
05569     }
05570     if (G) {
05571       const TargetLowering &TLI = G->getTargetLoweringInfo();
05572       const char *Name = TLI.getTargetNodeName(getOpcode());
05573       if (Name) return Name;
05574       return "<<Unknown Target Node>>";
05575     }
05576     return "<<Unknown Node>>";
05577    
05578 #ifndef NDEBUG
05579   case ISD::DELETED_NODE:
05580     return "<<Deleted Node!>>";
05581 #endif
05582   case ISD::PREFETCH:      return "Prefetch";
05583   case ISD::MEMBARRIER:    return "MemBarrier";
05584   case ISD::ATOMIC_CMP_SWAP:    return "AtomicCmpSwap";
05585   case ISD::ATOMIC_SWAP:        return "AtomicSwap";
05586   case ISD::ATOMIC_LOAD_ADD:    return "AtomicLoadAdd";
05587   case ISD::ATOMIC_LOAD_SUB:    return "AtomicLoadSub";
05588   case ISD::ATOMIC_LOAD_AND:    return "AtomicLoadAnd";
05589   case ISD::ATOMIC_LOAD_OR:     return "AtomicLoadOr";
05590   case ISD::ATOMIC_LOAD_XOR:    return "AtomicLoadXor";
05591   case ISD::ATOMIC_LOAD_NAND:   return "AtomicLoadNand";
05592   case ISD::ATOMIC_LOAD_MIN:    return "AtomicLoadMin";
05593   case ISD::ATOMIC_LOAD_MAX:    return "AtomicLoadMax";
05594   case ISD::ATOMIC_LOAD_UMIN:   return "AtomicLoadUMin";
05595   case ISD::ATOMIC_LOAD_UMAX:   return "AtomicLoadUMax";
05596   case ISD::PCMARKER:      return "PCMarker";
05597   case ISD::READCYCLECOUNTER: return "ReadCycleCounter";
05598   case ISD::SRCVALUE:      return "SrcValue";
05599   case ISD::MEMOPERAND:    return "MemOperand";
05600   case ISD::EntryToken:    return "EntryToken";
05601   case ISD::TokenFactor:   return "TokenFactor";
05602   case ISD::AssertSext:    return "AssertSext";
05603   case ISD::AssertZext:    return "AssertZext";
05604 
05605   case ISD::BasicBlock:    return "BasicBlock";
05606   case ISD::ARG_FLAGS:     return "ArgFlags";
05607   case ISD::VALUETYPE:     return "ValueType";
05608   case ISD::Register:      return "Register";
05609 
05610   case ISD::Constant:      return "Constant";
05611   case ISD::ConstantFP:    return "ConstantFP";
05612   case ISD::GlobalAddress: return "GlobalAddress";
05613   case ISD::GlobalTLSAddress: return "GlobalTLSAddress";
05614   case ISD::FrameIndex:    return "FrameIndex";
05615   case ISD::JumpTable:     return "JumpTable";
05616   case ISD::GLOBAL_OFFSET_TABLE: return "GLOBAL_OFFSET_TABLE";
05617   case ISD::RETURNADDR: return "RETURNADDR";
05618   case ISD::FRAMEADDR: return "FRAMEADDR";
05619   case ISD::FRAME_TO_ARGS_OFFSET: return "FRAME_TO_ARGS_OFFSET";
05620   case ISD::EXCEPTIONADDR: return "EXCEPTIONADDR";
05621   case ISD::EHSELECTION: return "EHSELECTION";
05622   case ISD::EH_RETURN: return "EH_RETURN";
05623   case ISD::ConstantPool:  return "ConstantPool";
05624   case ISD::ExternalSymbol: return "ExternalSymbol";
05625   case ISD::INTRINSIC_WO_CHAIN: {
05626     unsigned IID = cast<ConstantSDNode>(getOperand(0))->getZExtValue();
05627     return Intrinsic::getName((Intrinsic::ID)IID);
05628   }
05629   case ISD::INTRINSIC_VOID:
05630   case ISD::INTRINSIC_W_CHAIN: {
05631     unsigned IID = cast<ConstantSDNode>(getOperand(1))->getZExtValue();
05632     return Intrinsic::getName((Intrinsic::ID)IID);
05633   }
05634 
05635   case ISD::BUILD_VECTOR:   return "BUILD_VECTOR";
05636   case ISD::TargetConstant: return "TargetConstant";
05637   case ISD::TargetConstantFP:return "TargetConstantFP";
05638   case ISD::TargetGlobalAddress: return "TargetGlobalAddress";
05639   case ISD::TargetGlobalTLSAddress: return "TargetGlobalTLSAddress";
05640   case ISD::TargetFrameIndex: return "TargetFrameIndex";
05641   case ISD::TargetJumpTable:  return "TargetJumpTable";
05642   case ISD::TargetConstantPool:  return "TargetConstantPool";
05643   case ISD::TargetExternalSymbol: return "TargetExternalSymbol";
05644 
05645   case ISD::CopyToReg:     return "CopyToReg";
05646   case ISD::CopyFromReg:   return "CopyFromReg";
05647   case ISD::UNDEF:         return "undef";
05648   case ISD::MERGE_VALUES:  return "merge_values";
05649   case ISD::INLINEASM:     return "inlineasm";
05650   case ISD::DBG_LABEL:     return "dbg_label";
05651   case ISD::EH_LABEL:      return "eh_label";
05652   case ISD::DECLARE:       return "declare";
05653   case ISD::HANDLENODE:    return "handlenode";
05654   case ISD::FORMAL_ARGUMENTS: return "formal_arguments";
05655   case ISD::CALL:          return "call";
05656     
05657   // Unary operators
05658   case ISD::FABS:   return "fabs";
05659   case ISD::FNEG:   return "fneg";
05660   case ISD::FSQRT:  return "fsqrt";
05661   case ISD::FSIN:   return "fsin";
05662   case ISD::FCOS:   return "fcos";
05663   case ISD::FPOWI:  return "fpowi";
05664   case ISD::FPOW:   return "fpow";
05665   case ISD::FTRUNC: return "ftrunc";
05666   case ISD::FFLOOR: return "ffloor";
05667   case ISD::FCEIL:  return "fceil";
05668   case ISD::FRINT:  return "frint";
05669   case ISD::FNEARBYINT: return "fnearbyint";
05670 
05671   // Binary operators
05672   case ISD::ADD:    return "add";
05673   case ISD::SUB:    return "sub";
05674   case ISD::MUL:    return "mul";
05675   case ISD::MULHU:  return "mulhu";
05676   case ISD::MULHS:  return "mulhs";
05677   case ISD::SDIV:   return "sdiv";
05678   case ISD::UDIV:   return "udiv";
05679   case ISD::SREM:   return "srem";
05680   case ISD::UREM:   return "urem";
05681   case ISD::SMUL_LOHI:  return "smul_lohi";
05682   case ISD::UMUL_LOHI:  return "umul_lohi";
05683   case ISD::SDIVREM:    return "sdivrem";
05684   case ISD::UDIVREM:    return "udivrem";
05685   case ISD::AND:    return "and";
05686   case ISD::OR:     return "or";
05687   case ISD::XOR:    return "xor";
05688   case ISD::SHL:    return "shl";
05689   case ISD::SRA:    return "sra";
05690   case ISD::SRL:    return "srl";
05691   case ISD::ROTL:   return "rotl";
05692   case ISD::ROTR:   return "rotr";
05693   case ISD::FADD:   return "fadd";
05694   case ISD::FSUB:   return "fsub";
05695   case ISD::FMUL:   return "fmul";
05696   case ISD::FDIV:   return "fdiv";
05697   case ISD::FREM:   return "frem";
05698   case ISD::FCOPYSIGN: return "fcopysign";
05699   case ISD::FGETSIGN:  return "fgetsign";
05700 
05701   case ISD::SETCC:       return "setcc";
05702   case ISD::VSETCC:      return "vsetcc";
05703   case ISD::SELECT:      return "select";
05704   case ISD::SELECT_CC:   return "select_cc";
05705   case ISD::INSERT_VECTOR_ELT:   return "insert_vector_elt";
05706   case ISD::EXTRACT_VECTOR_ELT:  return "extract_vector_elt";
05707   case ISD::CONCAT_VECTORS:      return "concat_vectors";
05708   case ISD::EXTRACT_SUBVECTOR:   return "extract_subvector";
05709   case ISD::SCALAR_TO_VECTOR:    return "scalar_to_vector";
05710   case ISD::VECTOR_SHUFFLE:      return "vector_shuffle";
05711   case ISD::CARRY_FALSE:         return "carry_false";
05712   case ISD::ADDC:        return "addc";
05713   case ISD::ADDE:        return "adde";
05714   case ISD::SADDO:       return "saddo";
05715   case ISD::UADDO:       return "uaddo";
05716   case ISD::SSUBO:       return "ssubo";
05717   case ISD::USUBO:       return "usubo";
05718   case ISD::SMULO:       return "smulo";
05719   case ISD::UMULO:       return "umulo";
05720   case ISD::SUBC:        return "subc";
05721   case ISD::SUBE:        return "sube";
05722   case ISD::SHL_PARTS:   return "shl_parts";
05723   case ISD::SRA_PARTS:   return "sra_parts";
05724   case ISD::SRL_PARTS:   return "srl_parts";
05725   
05726   case ISD::EXTRACT_SUBREG:     return "extract_subreg";
05727   case ISD::INSERT_SUBREG:      return "insert_subreg";
05728   
05729   // Conversion operators.
05730   case ISD::SIGN_EXTEND: return "sign_extend";
05731   case ISD::ZERO_EXTEND: return "zero_extend";
05732   case ISD::ANY_EXTEND:  return "any_extend";
05733   case ISD::SIGN_EXTEND_INREG: return "sign_extend_inreg";
05734   case ISD::TRUNCATE:    return "truncate";
05735   case ISD::FP_ROUND:    return "fp_round";
05736   case ISD::FLT_ROUNDS_: return "flt_rounds";
05737   case ISD::FP_ROUND_INREG: return "fp_round_inreg";
05738   case ISD::FP_EXTEND:   return "fp_extend";
05739 
05740   case ISD::SINT_TO_FP:  return "sint_to_fp";
05741   case ISD::UINT_TO_FP:  return "uint_to_fp";
05742   case ISD::FP_TO_SINT:  return "fp_to_sint";
05743   case ISD::FP_TO_UINT:  return "fp_to_uint";
05744   case ISD::BIT_CONVERT: return "bit_convert";
05745   
05746   case ISD::CONVERT_RNDSAT: {
05747     switch (cast<CvtRndSatSDNode>(this)->getCvtCode()) {
05748     default: assert(0 && "Unknown cvt code!");
05749     case ISD::CVT_FF:  return "cvt_ff";
05750     case ISD::CVT_FS:  return "cvt_fs";
05751     case ISD::CVT_FU:  return "cvt_fu";
05752     case ISD::CVT_SF:  return "cvt_sf";
05753     case ISD::CVT_UF:  return "cvt_uf";
05754     case ISD::CVT_SS:  return "cvt_ss";
05755     case ISD::CVT_SU:  return "cvt_su";
05756     case ISD::CVT_US:  return "cvt_us";
05757     case ISD::CVT_UU:  return "cvt_uu";
05758     }
05759   }
05760 
05761     // Control flow instructions
05762   case ISD::BR:      return "br";
05763   case ISD::BRIND:   return "brind";
05764   case ISD::BR_JT:   return "br_jt";
05765   case ISD::BRCOND:  return "brcond";
05766   case ISD::BR_CC:   return "br_cc";
05767   case ISD::RET:     return "ret";
05768   case ISD::CALLSEQ_START:  return "callseq_start";
05769   case ISD::CALLSEQ_END:    return "callseq_end";
05770 
05771     // Other operators
05772   case ISD::LOAD:               return "load";
05773   case ISD::STORE:              return "store";
05774   case ISD::VAARG:              return "vaarg";
05775   case ISD::VACOPY:             return "vacopy";
05776   case ISD::VAEND:              return "vaend";
05777   case ISD::VASTART:            return "vastart";
05778   case ISD::DYNAMIC_STACKALLOC: return "dynamic_stackalloc";
05779   case ISD::EXTRACT_ELEMENT:    return "extract_element";
05780   case ISD::BUILD_PAIR:         return "build_pair";
05781   case ISD::STACKSAVE:          return "stacksave";
05782   case ISD::STACKRESTORE:       return "stackrestore";
05783   case ISD::TRAP:               return "trap";
05784 
05785   // Bit manipulation
05786   case ISD::BSWAP:   return "bswap";
05787   case ISD::CTPOP:   return "ctpop";
05788   case ISD::CTTZ:    return "cttz";
05789   case ISD::CTLZ:    return "ctlz";
05790 
05791   // Debug info
05792   case ISD::DBG_STOPPOINT: return "dbg_stoppoint";
05793   case ISD::DEBUG_LOC: return "debug_loc";
05794 
05795   // Trampolines
05796   case ISD::TRAMPOLINE: return "trampoline";
05797 
05798   case ISD::CONDCODE:
05799     switch (cast<CondCodeSDNode>(this)->get()) {
05800     default: assert(0 && "Unknown setcc condition!");
05801     case ISD::SETOEQ:  return "setoeq";
05802     case ISD::SETOGT:  return "setogt";
05803     case ISD::SETOGE:  return "setoge";
05804     case ISD::SETOLT:  return "setolt";
05805     case ISD::SETOLE:  return "setole";
05806     case ISD::SETONE:  return "setone";
05807 
05808     case ISD::SETO:    return "seto";
05809     case ISD::SETUO:   return "setuo";
05810     case ISD::SETUEQ:  return "setue";
05811     case ISD::SETUGT:  return "setugt";
05812     case ISD::SETUGE:  return "setuge";
05813     case ISD::SETULT:  return "setult";
05814     case ISD::SETULE:  return "setule";
05815     case ISD::SETUNE:  return "setune";
05816 
05817     case ISD::SETEQ:   return "seteq";
05818     case ISD::SETGT:   return "setgt";
05819     case ISD::SETGE:   return "setge";
05820     case ISD::SETLT:   return "setlt";
05821     case ISD::SETLE:   return "setle";
05822     case ISD::SETNE:   return "setne";
05823     }
05824   }
05825 }
05826 
05827 const char *SDNode::getIndexedModeName(ISD::MemIndexedMode AM) {
05828   switch (AM) {
05829   default:
05830     return "";
05831   case ISD::PRE_INC:
05832     return "<pre-inc>";
05833   case ISD::PRE_DEC:
05834     return "<pre-dec>";
05835   case ISD::POST_INC:
05836     return "<post-inc>";
05837   case ISD::POST_DEC:
05838     return "<post-dec>";
05839   }
05840 }
05841 
05842 std::string ISD::ArgFlagsTy::getArgFlagsString() {
05843   std::string S = "< ";
05844 
05845   if (isZExt())
05846     S += "zext ";
05847   if (isSExt())
05848     S += "sext ";
05849   if (isInReg())
05850     S += "inreg ";
05851   if (isSRet())
05852     S += "sret ";
05853   if (isByVal())
05854     S += "byval ";
05855   if (isNest())
05856     S += "nest ";
05857   if (getByValAlign())
05858     S += "byval-align:" + utostr(getByValAlign()) + " ";
05859   if (getOrigAlign())
05860     S += "orig-align:" + utostr(getOrigAlign()) + " ";
05861   if (getByValSize())
05862     S += "byval-size:" + utostr(getByValSize()) + " ";
05863   return S + ">";
05864 }
05865 
05866 void SDNode::dump() const { dump(0); }
05867 void SDNode::dump(const SelectionDAG *G) const {
05868   print(errs(), G);
05869   errs().flush();
05870 }
05871 
05872 void SDNode::print(raw_ostream &OS, const SelectionDAG *G) const {
05873   OS << (void*)this << ": ";
05874 
05875   for (unsigned i = 0, e = getNumValues(); i != e; ++i) {
05876     if (i) OS << ",";
05877     if (getValueType(i) == MVT::Other)
05878       OS << "ch";
05879     else
05880       OS << getValueType(i).getMVTString();
05881   }
05882   OS << " = " << getOperationName(G);
05883 
05884   OS << " ";
05885   for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
05886     if (i) OS << ", ";
05887     OS << (void*)getOperand(i).getNode();
05888     if (unsigned RN = getOperand(i).getResNo())
05889       OS << ":" << RN;
05890   }
05891 
05892   if (!isTargetOpcode() && getOpcode() == ISD::VECTOR_SHUFFLE) {
05893     SDNode *Mask = getOperand(2).getNode();
05894     OS << "<";
05895     for (unsigned i = 0, e = Mask->getNumOperands(); i != e; ++i) {
05896       if (i) OS << ",";
05897       if (Mask->getOperand(i).getOpcode() == ISD::UNDEF)
05898         OS << "u";
05899       else
05900         OS << cast<ConstantSDNode>(Mask->getOperand(i))->getZExtValue();
05901     }
05902     OS << ">";
05903   }
05904 
05905   if (const ConstantSDNode *CSDN = dyn_cast<ConstantSDNode>(this)) {
05906     OS << '<' << CSDN->getAPIntValue() << '>';
05907   } else if (const ConstantFPSDNode *CSDN = dyn_cast<ConstantFPSDNode>(this)) {
05908     if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEsingle)
05909       OS << '<' << CSDN->getValueAPF().convertToFloat() << '>';
05910     else if (&CSDN->getValueAPF().getSemantics()==&APFloat::IEEEdouble)
05911       OS << '<' << CSDN->getValueAPF().convertToDouble() << '>';
05912     else {
05913       OS << "<APFloat(";
05914       CSDN->getValueAPF().bitcastToAPInt().dump();
05915       OS << ")>";
05916     }
05917   } else if (const GlobalAddressSDNode *GADN =
05918              dyn_cast<GlobalAddressSDNode>(this)) {
05919     int64_t offset = GADN->getOffset();
05920     OS << '<';
05921     WriteAsOperand(OS, GADN->getGlobal());
05922     OS << '>';
05923     if (offset > 0)
05924       OS << " + " << offset;
05925     else
05926       OS << " " << offset;
05927   } else if (const FrameIndexSDNode *FIDN = dyn_cast<FrameIndexSDNode>(this)) {
05928     OS << "<" << FIDN->getIndex() << ">";
05929   } else if (const JumpTableSDNode *JTDN = dyn_cast<JumpTableSDNode>(this)) {
05930     OS << "<" << JTDN->getIndex() << ">";
05931   } else if (const ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(this)){
05932     int offset = CP->getOffset();
05933     if (CP->isMachineConstantPoolEntry())
05934       OS << "<" << *CP->getMachineCPVal() << ">";
05935     else
05936       OS << "<" << *CP->getConstVal() << ">";
05937     if (offset > 0)
05938       OS << " + " << offset;
05939     else
05940       OS << " " << offset;
05941   } else if (const BasicBlockSDNode *BBDN = dyn_cast<BasicBlockSDNode>(this)) {
05942     OS << "<";
05943     const Value *LBB = (const Value*)BBDN->getBasicBlock()->getBasicBlock();
05944     if (LBB)
05945       OS << LBB->getName() << " ";
05946     OS << (const void*)BBDN->getBasicBlock() << ">";
05947   } else if (const RegisterSDNode *R = dyn_cast<RegisterSDNode>(this)) {
05948     if (G && R->getReg() &&
05949         TargetRegisterInfo::isPhysicalRegister(R->getReg())) {
05950       OS << " " << G->getTarget().getRegisterInfo()->getName(R->getReg());
05951     } else {
05952       OS << " #" << R->getReg();
05953     }
05954   } else if (const ExternalSymbolSDNode *ES =
05955              dyn_cast<ExternalSymbolSDNode>(this)) {
05956     OS << "'" << ES->getSymbol() << "'";
05957   } else if (const SrcValueSDNode *M = dyn_cast<SrcValueSDNode>(this)) {
05958     if (M->getValue())
05959       OS << "<" << M->getValue() << ">";
05960     else
05961       OS << "<null>";
05962   } else if (const MemOperandSDNode *M = dyn_cast<MemOperandSDNode>(this)) {
05963     if (M->MO.getValue())
05964       OS << "<" << M->MO.getValue() << ":" << M->MO.getOffset() << ">";
05965     else
05966       OS << "<null:" << M->MO.getOffset() << ">";
05967   } else if (const ARG_FLAGSSDNode *N = dyn_cast<ARG_FLAGSSDNode>(this)) {
05968     OS << N->getArgFlags().getArgFlagsString();
05969   } else if (const VTSDNode *N = dyn_cast<VTSDNode>(this)) {
05970     OS << ":" << N->getVT().getMVTString();
05971   }
05972   else if (const LoadSDNode *LD = dyn_cast<LoadSDNode>(this)) {
05973     const Value *SrcValue = LD->getSrcValue();
05974     int SrcOffset = LD->getSrcValueOffset();
05975     OS << " <";
05976     if (SrcValue)
05977       OS << SrcValue;
05978     else
05979       OS << "null";
05980     OS << ":" << SrcOffset << ">";
05981 
05982     bool doExt = true;
05983     switch (LD->getExtensionType()) {
05984     default: doExt = false; break;
05985     case ISD::EXTLOAD: OS << " <anyext "; break;
05986     case ISD::SEXTLOAD: OS << " <sext "; break;
05987     case ISD::ZEXTLOAD: OS << " <zext "; break;
05988     }
05989     if (doExt)
05990       OS << LD->getMemoryVT().getMVTString() << ">";
05991 
05992     const char *AM = getIndexedModeName(LD->getAddressingMode());
05993     if (*AM)
05994       OS << " " << AM;
05995     if (LD->isVolatile())
05996       OS << " <volatile>";
05997     OS << " alignment=" << LD->getAlignment();
05998   } else if (const StoreSDNode *ST = dyn_cast<StoreSDNode>(this)) {
05999     const Value *SrcValue = ST->getSrcValue();
06000     int SrcOffset = ST->getSrcValueOffset();
06001     OS << " <";
06002     if (SrcValue)
06003       OS << SrcValue;
06004     else
06005       OS << "null";
06006     OS << ":" << SrcOffset << ">";
06007 
06008     if (ST->isTruncatingStore())
06009       OS << " <trunc " << ST->getMemoryVT().getMVTString() << ">";
06010 
06011     const char *AM = getIndexedModeName(ST->getAddressingMode());
06012     if (*AM)
06013       OS << " " << AM;
06014     if (ST->isVolatile())
06015       OS << " <volatile>";
06016     OS << " alignment=" << ST->getAlignment();
06017   } else if (const AtomicSDNode* AT = dyn_cast<AtomicSDNode>(this)) {
06018     const Value *SrcValue = AT->getSrcValue();
06019     int SrcOffset = AT->getSrcValueOffset();
06020     OS << " <";
06021     if (SrcValue)
06022       OS << SrcValue;
06023     else
06024       OS << "null";
06025     OS << ":" << SrcOffset << ">";
06026     if (AT->isVolatile())
06027       OS << " <volatile>";
06028     OS << " alignment=" << AT->getAlignment();
06029   }
06030 }
06031 
06032 static void DumpNodes(const SDNode *N, unsigned indent, const SelectionDAG *G) {
06033   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
06034     if (N->getOperand(i).getNode()->hasOneUse())
06035       DumpNodes(N->getOperand(i).getNode(), indent+2, G);
06036     else
06037       cerr << "\n" << std::string(indent+2, ' ')
06038            << (void*)N->getOperand(i).getNode() << ": <multiple use>";
06039 
06040 
06041   cerr << "\n" << std::string(indent, ' ');
06042   N->dump(G);
06043 }
06044 
06045 void SelectionDAG::dump() const {
06046   cerr << "SelectionDAG has " << AllNodes.size() << " nodes:";
06047   
06048   for (allnodes_const_iterator I = allnodes_begin(), E = allnodes_end();
06049        I != E; ++I) {
06050     const SDNode *N = I;
06051     if (!N->hasOneUse() && N != getRoot().getNode())
06052       DumpNodes(N, 2, this);
06053   }
06054 
06055   if (getRoot().getNode()) DumpNodes(getRoot().getNode(), 2, this);
06056 
06057   cerr << "\n\n";
06058 }
06059 
06060 const Type *ConstantPoolSDNode::getType() const {
06061   if (isMachineConstantPoolEntry())
06062     return Val.MachineCPVal->getType();
06063   return Val.ConstVal->getType();
06064 }