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/TargetInstrInfo.h"
00031 #include "llvm/Target/TargetMachine.h"
00032 #include "llvm/Support/CommandLine.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/ADT/SetVector.h"
00036 #include "llvm/ADT/SmallPtrSet.h"
00037 #include "llvm/ADT/SmallSet.h"
00038 #include "llvm/ADT/SmallVector.h"
00039 #include "llvm/ADT/StringExtras.h"
00040 #include <algorithm>
00041 #include <cmath>
00042 using namespace llvm;
00043 
00044 /// makeVTList - Return an instance of the SDVTList struct initialized with the
00045 /// specified members.
00046 static SDVTList makeVTList(const MVT *VTs, unsigned NumVTs) {
00047   SDVTList Res = {VTs, NumVTs};
00048   return Res;
00049 }
00050 
00051 static const fltSemantics *MVTToAPFloatSemantics(MVT VT) {
00052   switch (VT.getSimpleVT()) {
00053   default: assert(0 && "Unknown FP format");
00054   case MVT::f32:     return &APFloat::IEEEsingle;
00055   case MVT::f64:     return &APFloat::IEEEdouble;
00056   case MVT::f80:     return &APFloat::x87DoubleExtended;
00057   case MVT::f128:    return &APFloat::IEEEquad;
00058   case MVT::ppcf128: return &APFloat::PPCDoubleDouble;
00059   }
00060 }
00061 
00062 SelectionDAG::DAGUpdateListener::~DAGUpdateListener() {}
00063 
00064 //===----------------------------------------------------------------------===//
00065 //                              ConstantFPSDNode Class
00066 //===----------------------------------------------------------------------===//
00067 
00068 /// isExactlyValue - We don't rely on operator== working on double values, as
00069 /// it returns true for things that are clearly not equal, like -0.0 and 0.0.
00070 /// As such, this method can be used to do an exact bit-for-bit comparison of
00071 /// two floating point values.
00072 bool ConstantFPSDNode::isExactlyValue(const APFloat& V) const {
00073   return getValueAPF().bitwiseIsEqual(V);
00074 }
00075 
00076 bool ConstantFPSDNode::isValueValidForType(MVT VT,
00077                                            const APFloat& Val) {
00078   assert(VT.isFloatingPoint() && "Can only convert between FP types");
00079   
00080   // PPC long double cannot be converted to any other type.
00081   if (VT == MVT::ppcf128 ||
00082       &Val.getSemantics() == &APFloat::PPCDoubleDouble)
00083     return false;
00084   
00085   // convert modifies in place, so make a copy.
00086   APFloat Val2 = APFloat(Val);
00087   bool losesInfo;
00088   (void) Val2.convert(*MVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
00089                       &losesInfo);
00090   return !losesInfo;
00091 }
00092 
00093 //===----------------------------------------------------------------------===//
00094 //                              ISD Namespace
00095 //===----------------------------------------------------------------------===//
00096 
00097 /// isBuildVectorAllOnes - Return true if the specified node is a
00098 /// BUILD_VECTOR where all of the elements are ~0 or undef.
00099 bool ISD::isBuildVectorAllOnes(const SDNode *N) {
00100   // Look through a bit convert.
00101   if (N->getOpcode() == ISD::BIT_CONVERT)
00102     N = N->getOperand(0).getNode();
00103   
00104   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00105   
00106   unsigned i = 0, e = N->getNumOperands();
00107   
00108   // Skip over all of the undef values.
00109   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00110     ++i;
00111   
00112   // Do not accept an all-undef vector.
00113   if (i == e) return false;
00114   
00115   // Do not accept build_vectors that aren't all constants or which have non-~0
00116   // elements.
00117   SDValue NotZero = N->getOperand(i);
00118   if (isa<ConstantSDNode>(NotZero)) {
00119     if (!cast<ConstantSDNode>(NotZero)->isAllOnesValue())
00120       return false;
00121   } else if (isa<ConstantFPSDNode>(NotZero)) {
00122     if (!cast<ConstantFPSDNode>(NotZero)->getValueAPF().
00123                 bitcastToAPInt().isAllOnesValue())
00124       return false;
00125   } else
00126     return false;
00127   
00128   // Okay, we have at least one ~0 value, check to see if the rest match or are
00129   // undefs.
00130   for (++i; i != e; ++i)
00131     if (N->getOperand(i) != NotZero &&
00132         N->getOperand(i).getOpcode() != ISD::UNDEF)
00133       return false;
00134   return true;
00135 }
00136 
00137 
00138 /// isBuildVectorAllZeros - Return true if the specified node is a
00139 /// BUILD_VECTOR where all of the elements are 0 or undef.
00140 bool ISD::isBuildVectorAllZeros(const SDNode *N) {
00141   // Look through a bit convert.
00142   if (N->getOpcode() == ISD::BIT_CONVERT)
00143     N = N->getOperand(0).getNode();
00144   
00145   if (N->getOpcode() != ISD::BUILD_VECTOR) return false;
00146   
00147   unsigned i = 0, e = N->getNumOperands();
00148   
00149   // Skip over all of the undef values.
00150   while (i != e && N->getOperand(i).getOpcode() == ISD::UNDEF)
00151     ++i;
00152   
00153   // Do not accept an all-undef vector.
00154   if (i == e) return false;
00155   
00156   // Do not accept build_vectors that aren't all constants or which have non-~0
00157   // elements.
00158   SDValue Zero = N->getOperand(i);
00159   if (isa<ConstantSDNode>(Zero)) {
00160     if (!cast<ConstantSDNode>(Zero)->isNullValue())
00161       return false;
00162   } else if (isa<ConstantFPSDNode>(Zero)) {
00163     if (!cast<ConstantFPSDNode>(Zero)->getValueAPF().isPosZero())
00164       return false;
00165   } else
00166     return false;
00167   
00168   // Okay, we have at least one ~0 value, check to see if the rest match or are
00169   // undefs.
00170   for (++i; i != e; ++i)
00171     if (N->getOperand(i) != Zero &&
00172         N->getOperand(i).getOpcode() != ISD::UNDEF)
00173       return false;
00174   return true;
00175 }
00176 
00177 /// isScalarToVector - Return true if the specified node is a
00178 /// ISD::SCALAR_TO_VECTOR node or a BUILD_VECTOR node where only the low
00179 /// element is not an undef.
00180 bool ISD::isScalarToVector(const SDNode *N) {
00181   if (N->getOpcode() == ISD::SCALAR_TO_VECTOR)
00182     return true;
00183 
00184   if (N->getOpcode() != ISD::BUILD_VECTOR)
00185     return false;
00186   if (N->getOperand(0).getOpcode() == ISD::UNDEF)
00187     return false;
00188   unsigned NumElems = N->getNumOperands();
00189   for (unsigned i = 1; i < NumElems; ++i) {
00190     SDValue V = N->getOperand(i);
00191     if (V.getOpcode() != ISD::UNDEF)
00192       return false;
00193   }
00194   return true;
00195 }
00196 
00197 
00198 /// isDebugLabel - Return true if the specified node represents a debug
00199 /// label (i.e. ISD::DBG_LABEL or TargetInstrInfo::DBG_LABEL node).
00200 bool ISD::isDebugLabel(const SDNode *N) {
00201   SDValue Zero;
00202   if (N->getOpcode() == ISD::DBG_LABEL)
00203     return true;
00204   if (N->isMachineOpcode() &&
00205       N->getMachineOpcode() == TargetInstrInfo::DBG_LABEL)
00206     return true;
00207   return false;
00208 }
00209 
00210 /// getSetCCSwappedOperands - Return the operation corresponding to (Y op X)
00211 /// when given the operation for (X op Y).
00212 ISD::CondCode ISD::getSetCCSwappedOperands(ISD::CondCode Operation) {
00213   // To perform this operation, we just need to swap the L and G bits of the
00214   // operation.
00215   unsigned OldL = (Operation >> 2) & 1;
00216   unsigned OldG = (Operation >> 1) & 1;
00217   return ISD::CondCode((Operation & ~6) |  // Keep the N, U, E bits
00218                        (OldL << 1) |       // New G bit
00219                        (OldG << 2));       // New L bit.
00220 }
00221 
00222 /// getSetCCInverse - Return the operation corresponding to !(X op Y), where
00223 /// 'op' is a valid SetCC operation.
00224 ISD::CondCode ISD::getSetCCInverse(ISD::CondCode Op, bool isInteger) {
00225   unsigned Operation = Op;
00226   if (isInteger)
00227     Operation ^= 7;   // Flip L, G, E bits, but not U.
00228   else
00229     Operation ^= 15;  // Flip all of the condition bits.
00230 
00231   if (Operation > ISD::SETTRUE2)
00232     Operation &= ~8;  // Don't let N and U bits get set.
00233 
00234   return ISD::CondCode(Operation);
00235 }
00236 
00237 
00238 /// isSignedOp - For an integer comparison, return 1 if the comparison is a
00239 /// signed operation and 2 if the result is an unsigned comparison.  Return zero
00240 /// if the operation does not depend on the sign of the input (setne and seteq).
00241 static int isSignedOp(ISD::CondCode Opcode) {
00242   switch (Opcode) {
00243   default: assert(0 && "Illegal integer setcc operation!");
00244   case ISD::SETEQ:
00245   case ISD::SETNE: return 0;
00246   case ISD::SETLT:
00247   case ISD::SETLE:
00248   case ISD::SETGT:
00249   case ISD::SETGE: return 1;
00250   case ISD::SETULT:
00251   case ISD::SETULE:
00252   case ISD::SETUGT:
00253   case ISD::SETUGE: return 2;
00254   }
00255 }
00256 
00257 /// getSetCCOrOperation - Return the result of a logical OR between different
00258 /// comparisons of identical values: ((X op1 Y) | (X op2 Y)).  This function
00259 /// returns SETCC_INVALID if it is not possible to represent the resultant
00260 /// comparison.
00261 ISD::CondCode ISD::getSetCCOrOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00262                                        bool isInteger) {
00263   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00264     // Cannot fold a signed integer setcc with an unsigned integer setcc.
00265     return ISD::SETCC_INVALID;
00266 
00267   unsigned Op = Op1 | Op2;  // Combine all of the condition bits.
00268 
00269   // If the N and U bits get set then the resultant comparison DOES suddenly
00270   // care about orderedness, and is true when ordered.
00271   if (Op > ISD::SETTRUE2)
00272     Op &= ~16;     // Clear the U bit if the N bit is set.
00273   
00274   // Canonicalize illegal integer setcc's.
00275   if (isInteger && Op == ISD::SETUNE)  // e.g. SETUGT | SETULT
00276     Op = ISD::SETNE;
00277   
00278   return ISD::CondCode(Op);
00279 }
00280 
00281 /// getSetCCAndOperation - Return the result of a logical AND between different
00282 /// comparisons of identical values: ((X op1 Y) & (X op2 Y)).  This
00283 /// function returns zero if it is not possible to represent the resultant
00284 /// comparison.
00285 ISD::CondCode ISD::getSetCCAndOperation(ISD::CondCode Op1, ISD::CondCode Op2,
00286                                         bool isInteger) {
00287   if (isInteger && (isSignedOp(Op1) | isSignedOp(Op2)) == 3)
00288     // Cannot fold a signed setcc with an unsigned setcc.
00289     return ISD::SETCC_INVALID;
00290 
00291   // Combine all of the condition bits.
00292   ISD::CondCode Result = ISD::CondCode(Op1 & Op2);
00293   
00294   // Canonicalize illegal integer setcc's.
00295   if (isInteger) {
00296     switch (Result) {
00297     default: break;
00298     case ISD::SETUO : Result = ISD::SETFALSE; break;  // SETUGT & SETULT
00299     case ISD::SETOEQ:                                 // SETEQ  & SETU[LG]E
00300     case ISD::SETUEQ: Result = ISD::SETEQ   ; break;  // SETUGE & SETULE
00301     case ISD::SETOLT: Result = ISD::SETULT  ; break;  // SETULT & SETNE
00302     case ISD::SETOGT: Result = ISD::SETUGT  ; break;  // SETUGT & SETNE
00303     }
00304   }
00305   
00306   return Result;
00307 }
00308 
00309 const TargetMachine &SelectionDAG::getTarget() const {
00310   return MF->getTarget();
00311 }
00312 
00313 //===----------------------------------------------------------------------===//
00314 //                           SDNode Profile Support
00315 //===----------------------------------------------------------------------===//
00316 
00317 /// AddNodeIDOpcode - Add the node opcode to the NodeID data.
00318 ///
00319 static void AddNodeIDOpcode(FoldingSetNodeID &ID, unsigned OpC)  {
00320   ID.AddInteger(OpC);
00321 }
00322 
00323 /// AddNodeIDValueTypes - Value type lists are intern'd so we can represent them
00324 /// solely with their pointer.
00325 static void AddNodeIDValueTypes(FoldingSetNodeID &ID, SDVTList VTList) {
00326   ID.AddPointer(VTList.VTs);  
00327 }
00328 
00329 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
00330 ///
00331 static void AddNodeIDOperands(FoldingSetNodeID &ID,
00332                               const SDValue *Ops, unsigned NumOps) {
00333   for (; NumOps; --NumOps, ++Ops) {
00334     ID.AddPointer(Ops->getNode());
00335     ID.AddInteger(Ops->getResNo());
00336   }
00337 }
00338 
00339 /// AddNodeIDOperands - Various routines for adding operands to the NodeID data.
00340 ///
00341 static void AddNodeIDOperands(FoldingSetNodeID &ID,
00342                               const SDUse *Ops, unsigned NumOps) {
00343   for (; NumOps; --NumOps, ++Ops) {
00344     ID.AddPointer(Ops->getVal());
00345     ID.AddInteger(Ops->getSDValue().getResNo());
00346   }
00347 }
00348 
00349 static void AddNodeIDNode(FoldingSetNodeID &ID,
00350                           unsigned short OpC, SDVTList VTList, 
00351                           const SDValue *OpList, unsigned N) {
00352   AddNodeIDOpcode(ID, OpC);
00353   AddNodeIDValueTypes(ID, VTList);
00354   AddNodeIDOperands(ID, OpList, N);
00355 }
00356 
00357 /// AddNodeIDCustom - If this is an SDNode with special info, add this info to
00358 /// the NodeID data.
00359 static void AddNodeIDCustom(FoldingSetNodeID &ID, const SDNode *N) {
00360   switch (N->getOpcode()) {
00361   default: break;  // Normal nodes don't need extra info.
00362   case ISD::ARG_FLAGS:
00363     ID.AddInteger(cast<ARG_FLAGSSDNode>(N)->getArgFlags().getRawBits());
00364     break;
00365   case ISD::TargetConstant:
00366   case ISD::Constant:
00367     ID.AddPointer(cast<ConstantSDNode>(N)->getConstantIntValue());
00368     break;
00369   case ISD::TargetConstantFP:
00370   case ISD::ConstantFP: {
00371     ID.AddPointer(cast<ConstantFPSDNode>(N)->getConstantFPValue());
00372     break;
00373   }
00374   case ISD::TargetGlobalAddress:
00375   case ISD::GlobalAddress:
00376   case ISD::TargetGlobalTLSAddress:
00377   case ISD::GlobalTLSAddress: {
00378     const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(N);
00379     ID.AddPointer(GA->getGlobal());
00380     ID.AddInteger(GA->getOffset());
00381     break;
00382   }
00383   case ISD::BasicBlock:
00384     ID.AddPointer(cast<BasicBlockSDNode>(N)->getBasicBlock());
00385     break;
00386   case ISD::Register:
00387     ID.AddInteger(cast<RegisterSDNode>(N)->getReg());
00388     break;
00389   case ISD::DBG_STOPPOINT: {
00390     const DbgStopPointSDNode *DSP = cast<DbgStopPointSDNode>(N);
00391     ID.AddInteger(DSP->getLine());
00392     ID.AddInteger(DSP->getColumn());
00393     ID.AddPointer(DSP->getCompileUnit());
00394     break;
00395   }
00396   case ISD::SRCVALUE:
00397     ID.AddPointer(cast<SrcValueSDNode>(N)->getValue());
00398     break;
00399   case ISD::MEMOPERAND: {
00400     const MachineMemOperand &MO = cast<MemOperandSDNode>(N)->MO;
00401     MO.Profile(ID);
00402     break;
00403   }
00404   case ISD::FrameIndex:
00405   case ISD::TargetFrameIndex:
00406     ID.AddInteger(cast<FrameIndexSDNode>(N)->getIndex());
00407     break;
00408   case ISD::JumpTable:
00409   case ISD::TargetJumpTable:
00410     ID.AddInteger(cast<JumpTableSDNode>(N)->getIndex());
00411     break;
00412   case ISD::ConstantPool:
00413   case ISD::TargetConstantPool: {
00414     const ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(N);
00415     ID.AddInteger(CP->getAlignment());
00416     ID.AddInteger(CP->getOffset());
00417     if (CP->isMachineConstantPoolEntry())
00418       CP->getMachineCPVal()->AddSelectionDAGCSEId(ID);
00419     else
00420       ID.AddPointer(CP->getConstVal());
00421     break;
00422   }
00423   case ISD::CALL: {
00424     const CallSDNode *Call = cast<CallSDNode>(N);
00425     ID.AddInteger(Call->getCallingConv());
00426     ID.AddInteger(Call->isVarArg());
00427     break;
00428   }
00429   case ISD::LOAD: {
00430     const LoadSDNode *LD = cast<LoadSDNode>(N);
00431     ID.AddInteger(LD->getAddressingMode());
00432     ID.AddInteger(LD->getExtensionType());
00433     ID.AddInteger(LD->getMemoryVT().getRawBits());
00434     ID.AddInteger(LD->getRawFlags());
00435     break;
00436   }
00437   case ISD::STORE: {
00438     const StoreSDNode *ST = cast<StoreSDNode>(N);
00439     ID.AddInteger(ST->getAddressingMode());
00440     ID.AddInteger(ST->isTruncatingStore());
00441     ID.AddInteger(ST->getMemoryVT().getRawBits());
00442     ID.AddInteger(ST->getRawFlags());
00443     break;
00444   }
00445   case ISD::ATOMIC_CMP_SWAP:
00446   case ISD::ATOMIC_SWAP:
00447   case ISD::ATOMIC_LOAD_ADD:
00448   case ISD::ATOMIC_LOAD_SUB:
00449   case ISD::ATOMIC_LOAD_AND:
00450   case ISD::ATOMIC_LOAD_OR:
00451   case ISD::ATOMIC_LOAD_XOR:
00452   case ISD::ATOMIC_LOAD_NAND:
00453   case ISD::ATOMIC_LOAD_MIN:
00454   case ISD::ATOMIC_LOAD_MAX:
00455   case ISD::ATOMIC_LOAD_UMIN:
00456   case ISD::ATOMIC_LOAD_UMAX: {
00457     const AtomicSDNode *AT = cast<AtomicSDNode>(N);
00458     ID.AddInteger(AT->getRawFlags());
00459     break;
00460   }
00461   } // end switch (N->getOpcode())
00462 }
00463 
00464 /// AddNodeIDNode - Generic routine for adding a nodes info to the NodeID
00465 /// data.
00466 static void AddNodeIDNode(FoldingSetNodeID &ID, const SDNode *N) {
00467   AddNodeIDOpcode(ID, N->getOpcode());
00468   // Add the return value info.
00469   AddNodeIDValueTypes(ID, N->getVTList());
00470   // Add the operand info.
00471   AddNodeIDOperands(ID, N->op_begin(), N->getNumOperands());
00472 
00473   // Handle SDNode leafs with special info.
00474   AddNodeIDCustom(ID, N);
00475 }
00476 
00477 /// encodeMemSDNodeFlags - Generic routine for computing a value for use in
00478 /// the CSE map that carries both alignment and volatility information.
00479 ///
00480 static inline unsigned
00481 encodeMemSDNodeFlags(bool isVolatile, unsigned Alignment) {
00482   return isVolatile | ((Log2_32(Alignment) + 1) << 1);
00483 }
00484 
00485 //===----------------------------------------------------------------------===//
00486 //                              SelectionDAG Class
00487 //===----------------------------------------------------------------------===//
00488 
00489 /// doNotCSE - Return true if CSE should not be performed for this node.
00490 static bool doNotCSE(SDNode *N) {
00491   if (N->getValueType(0) == MVT::Flag)
00492     return true; // Never CSE anything that produces a flag.
00493 
00494   switch (N->getOpcode()) {
00495   default: break;
00496   case ISD::HANDLENODE:
00497   case ISD::DBG_LABEL:
00498   case ISD::DBG_STOPPOINT:
00499   case ISD::EH_LABEL:
00500   case ISD::DECLARE:
00501     return true;   // Never CSE these nodes.
00502   }
00503 
00504   // Check that remaining values produced are not flags.
00505   for (unsigned i = 1, e = N->getNumValues(); i != e; ++i)
00506     if (N->getValueType(i) == MVT::Flag)
00507       return true; // Never CSE anything that produces a flag.
00508 
00509   return false;
00510 }
00511 
00512 /// RemoveDeadNodes - This method deletes all unreachable nodes in the
00513 /// SelectionDAG.
00514 void SelectionDAG::RemoveDeadNodes() {
00515   // Create a dummy node (which is not added to allnodes), that adds a reference
00516   // to the root node, preventing it from being deleted.
00517   HandleSDNode Dummy(getRoot());
00518 
00519   SmallVector<SDNode*, 128> DeadNodes;
00520   
00521   // Add all obviously-dead nodes to the DeadNodes worklist.
00522   for (allnodes_iterator I = allnodes_begin(), E = allnodes_end(); I != E; ++I)
00523     if (I->use_empty())
00524       DeadNodes.push_back(I);
00525 
00526   RemoveDeadNodes(DeadNodes);
00527   
00528   // If the root changed (e.g. it was a dead load, update the root).
00529   setRoot(Dummy.getValue());
00530 }
00531 
00532 /// RemoveDeadNodes - This method deletes the unreachable nodes in the
00533 /// given list, and any nodes that become unreachable as a result.
00534 void SelectionDAG::RemoveDeadNodes(SmallVectorImpl<SDNode *> &DeadNodes,
00535                                    DAGUpdateListener *UpdateListener) {
00536 
00537   // Process the worklist, deleting the nodes and adding their uses to the
00538   // worklist.
00539   while (!DeadNodes.empty()) {
00540     SDNode *N = DeadNodes.back();
00541     DeadNodes.pop_back();
00542     
00543     if (UpdateListener)
00544       UpdateListener->NodeDeleted(N, 0);
00545     
00546     // Take the node out of the appropriate CSE map.
00547     RemoveNodeFromCSEMaps(N);
00548 
00549     // Next, brutally remove the operand list.  This is safe to do, as there are
00550     // no cycles in the graph.
00551     for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I) {
00552       SDNode *Operand = I->getVal();
00553       Operand->removeUser(std::distance(N->op_begin(), I), N);
00554       
00555       // Now that we removed this operand, see if there are no uses of it left.
00556       if (Operand->use_empty())
00557         DeadNodes.push_back(Operand);
00558     }
00559 
00560     if (N->OperandsNeedDelete)
00561       delete[] N->OperandList;
00562 
00563     N->OperandList = 0;
00564     N->NumOperands = 0;
00565     
00566     // Finally, remove N itself.
00567     NodeAllocator.Deallocate(AllNodes.remove(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   assert(N->use_empty() && "Cannot delete a node that is not dead!");
00578 
00579   // First take this out of the appropriate CSE map.
00580   RemoveNodeFromCSEMaps(N);
00581 
00582   // Finally, remove uses due to operands of this node, remove from the 
00583   // AllNodes list, and delete the node.
00584   DeleteNodeNotInCSEMaps(N);
00585 }
00586 
00587 void SelectionDAG::DeleteNodeNotInCSEMaps(SDNode *N) {
00588   // Drop all of the operands and decrement used node's use counts.
00589   for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
00590     I->getVal()->removeUser(std::distance(N->op_begin(), I), N);
00591 
00592   if (N->OperandsNeedDelete) {
00593     delete[] N->OperandList;
00594     N->OperandList = 0;
00595   }
00596   
00597   assert(N != AllNodes.begin());
00598   NodeAllocator.Deallocate(AllNodes.remove(N));
00599 }
00600 
00601 /// RemoveNodeFromCSEMaps - Take the specified node out of the CSE map that
00602 /// correspond to it.  This is useful when we're about to delete or repurpose
00603 /// the node.  We don't want future request for structurally identical nodes
00604 /// to return N anymore.
00605 bool SelectionDAG::RemoveNodeFromCSEMaps(SDNode *N) {
00606   bool Erased = false;
00607   switch (N->getOpcode()) {
00608   case ISD::EntryToken:
00609     assert(0 && "EntryToken should not be in CSEMaps!");
00610     return false;
00611   case ISD::HANDLENODE: return false;  // noop.
00612   case ISD::CONDCODE:
00613     assert(CondCodeNodes[cast<CondCodeSDNode>(N)->get()] &&
00614            "Cond code doesn't exist!");
00615     Erased = CondCodeNodes[cast<CondCodeSDNode>(N)->get()] != 0;
00616     CondCodeNodes[cast<CondCodeSDNode>(N)->get()] = 0;
00617     break;
00618   case ISD::ExternalSymbol:
00619     Erased = ExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00620     break;
00621   case ISD::TargetExternalSymbol:
00622     Erased =
00623       TargetExternalSymbols.erase(cast<ExternalSymbolSDNode>(N)->getSymbol());
00624     break;
00625   case ISD::VALUETYPE: {
00626     MVT VT = cast<VTSDNode>(N)->getVT();
00627     if (VT.isExtended()) {
00628       Erased = ExtendedValueTypeNodes.erase(VT);
00629     } else {
00630       Erased = ValueTypeNodes[VT.getSimpleVT()] != 0;
00631       ValueTypeNodes[VT.getSimpleVT()] = 0;
00632     }
00633     break;
00634   }
00635   default:
00636     // Remove it from the CSE Map.
00637     Erased = CSEMap.RemoveNode(N);
00638     break;
00639   }
00640 #ifndef NDEBUG
00641   // Verify that the node was actually in one of the CSE maps, unless it has a 
00642   // flag result (which cannot be CSE'd) or is one of the special cases that are
00643   // not subject to CSE.
00644   if (!Erased && N->getValueType(N->getNumValues()-1) != MVT::Flag &&
00645       !N->isMachineOpcode() && !doNotCSE(N)) {
00646     N->dump(this);
00647     cerr << "\n";
00648     assert(0 && "Node is not in map!");
00649   }
00650 #endif
00651   return Erased;
00652 }
00653 
00654 /// AddNonLeafNodeToCSEMaps - Add the specified node back to the CSE maps.  It
00655 /// has been taken out and modified in some way.  If the specified node already
00656 /// exists in the CSE maps, do not modify the maps, but return the existing node
00657 /// instead.  If it doesn't exist, add it and return null.
00658 ///
00659 SDNode *SelectionDAG::AddNonLeafNodeToCSEMaps(SDNode *N) {
00660   assert(N->getNumOperands() && "This is a leaf node!");
00661 
00662   if (doNotCSE(N))
00663     return 0;
00664 
00665   SDNode *New = CSEMap.GetOrInsertNode(N);
00666   if (New != N) return New;  // Node already existed.
00667   return 0;
00668 }
00669 
00670 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00671 /// were replaced with those specified.  If this node is never memoized, 
00672 /// return null, otherwise return a pointer to the slot it would take.  If a
00673 /// node already exists with these operands, the slot will be non-null.
00674 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, SDValue Op,
00675                                            void *&InsertPos) {
00676   if (doNotCSE(N))
00677     return 0;
00678 
00679   SDValue Ops[] = { Op };
00680   FoldingSetNodeID ID;
00681   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 1);
00682   AddNodeIDCustom(ID, N);
00683   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00684 }
00685 
00686 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00687 /// were replaced with those specified.  If this node is never memoized, 
00688 /// return null, otherwise return a pointer to the slot it would take.  If a
00689 /// node already exists with these operands, the slot will be non-null.
00690 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00691                                            SDValue Op1, SDValue Op2,
00692                                            void *&InsertPos) {
00693   if (doNotCSE(N))
00694     return 0;
00695 
00696   SDValue Ops[] = { Op1, Op2 };
00697   FoldingSetNodeID ID;
00698   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, 2);
00699   AddNodeIDCustom(ID, N);
00700   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00701 }
00702 
00703 
00704 /// FindModifiedNodeSlot - Find a slot for the specified node if its operands
00705 /// were replaced with those specified.  If this node is never memoized, 
00706 /// return null, otherwise return a pointer to the slot it would take.  If a
00707 /// node already exists with these operands, the slot will be non-null.
00708 SDNode *SelectionDAG::FindModifiedNodeSlot(SDNode *N, 
00709                                            const SDValue *Ops,unsigned NumOps,
00710                                            void *&InsertPos) {
00711   if (doNotCSE(N))
00712     return 0;
00713 
00714   FoldingSetNodeID ID;
00715   AddNodeIDNode(ID, N->getOpcode(), N->getVTList(), Ops, NumOps);
00716   AddNodeIDCustom(ID, N);
00717   return CSEMap.FindNodeOrInsertPos(ID, InsertPos);
00718 }
00719 
00720 /// VerifyNode - Sanity check the given node.  Aborts if it is invalid.
00721 void SelectionDAG::VerifyNode(SDNode *N) {
00722   switch (N->getOpcode()) {
00723   default:
00724     break;
00725   case ISD::BUILD_PAIR: {
00726     MVT VT = N->getValueType(0);
00727     assert(N->getNumValues() == 1 && "Too many results!");
00728     assert(!VT.isVector() && (VT.isInteger() || VT.isFloatingPoint()) &&
00729            "Wrong return type!");
00730     assert(N->getNumOperands() == 2 && "Wrong number of operands!");
00731     assert(N->getOperand(0).getValueType() == N->getOperand(1).getValueType() &&
00732            "Mismatched operand types!");
00733     assert(N->getOperand(0).getValueType().isInteger() == VT.isInteger() &&
00734            "Wrong operand type!");
00735     assert(VT.getSizeInBits() == 2 * N->getOperand(0).getValueSizeInBits() &&
00736            "Wrong return type size");
00737     break;
00738   }
00739   case ISD::BUILD_VECTOR: {
00740     assert(N->getNumValues() == 1 && "Too many results!");
00741     assert(N->getValueType(0).isVector() && "Wrong return type!");
00742     assert(N->getNumOperands() == N->getValueType(0).getVectorNumElements() &&
00743            "Wrong number of operands!");
00744     // FIXME: Change vector_shuffle to a variadic node with mask elements being
00745     // operands of the node.  Currently the mask is a BUILD_VECTOR passed as an
00746     // operand, and it is not always possible to legalize it.  Turning off the
00747     // following checks at least makes it possible to legalize most of the time.
00748 //    MVT EltVT = N->getValueType(0).getVectorElementType();
00749 //    for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ++I)
00750 //      assert(I->getSDValue().getValueType() == EltVT &&
00751 //             "Wrong operand type!");
00752     break;
00753   }
00754   }
00755 }
00756 
00757 /// getMVTAlignment - Compute the default alignment value for the
00758 /// given type.
00759 ///
00760 unsigned SelectionDAG::getMVTAlignment(MVT VT) const {
00761   const Type *Ty = VT == MVT::iPTR ?
00762                    PointerType::get(Type::Int8Ty, 0) :
00763                    VT.getTypeForMVT();
00764 
00765   return TLI.getTargetData()->getABITypeAlignment(Ty);
00766 }
00767 
00768 SelectionDAG::SelectionDAG(TargetLowering &tli, FunctionLoweringInfo &fli)
00769   : TLI(tli), FLI(fli),
00770     EntryNode(ISD::EntryToken, getVTList(MVT::Other)),
00771     Root(getEntryNode()) {
00772   AllNodes.push_back(&EntryNode);
00773 }
00774 
00775 void SelectionDAG::init(MachineFunction &mf, MachineModuleInfo *mmi) {
00776   MF = &mf;
00777   MMI = mmi;
00778 }
00779 
00780 SelectionDAG::~SelectionDAG() {
00781   allnodes_clear();
00782 }
00783 
00784 void SelectionDAG::allnodes_clear() {
00785   assert(&*AllNodes.begin() == &EntryNode);
00786   AllNodes.remove(AllNodes.begin());
00787   while (!AllNodes.empty()) {
00788     SDNode *N = AllNodes.remove(AllNodes.begin());
00789     N->SetNextInBucket(0);
00790 
00791     if (N->OperandsNeedDelete) {
00792       delete [] N->OperandList;
00793       N->OperandList = 0;
00794     }
00795 
00796     NodeAllocator.Deallocate(N);
00797   }
00798 }
00799 
00800 void SelectionDAG::clear() {
00801   allnodes_clear();
00802   OperandAllocator.Reset();
00803   CSEMap.clear();
00804 
00805   ExtendedValueTypeNodes.clear();
00806   ExternalSymbols.clear();
00807   TargetExternalSymbols.clear();
00808   std::fill(CondCodeNodes.begin(), CondCodeNodes.end(),
00809             static_cast<CondCodeSDNode*>(0));
00810   std::fill(ValueTypeNodes.begin(), ValueTypeNodes.end(),
00811             static_cast<SDNode*>(0));
00812 
00813   EntryNode.Uses = 0;
00814   AllNodes.push_back(&EntryNode);
00815   Root = getEntryNode();
00816 }
00817 
00818 SDValue SelectionDAG::getZeroExtendInReg(SDValue Op, MVT VT) {
00819   if (Op.getValueType() == VT) return Op;
00820   APInt Imm = APInt::getLowBitsSet(Op.getValueSizeInBits(),
00821                                    VT.getSizeInBits());
00822   return getNode(ISD::AND, Op.getValueType(), Op,
00823                  getConstant(Imm, Op.getValueType()));
00824 }
00825 
00826 SDValue SelectionDAG::getConstant(uint64_t Val, MVT VT, bool isT) {
00827   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
00828   return getConstant(APInt(EltVT.getSizeInBits(), Val), VT, isT);
00829 }
00830 
00831 SDValue SelectionDAG::getConstant(const APInt &Val, MVT VT, bool isT) {
00832   return getConstant(*ConstantInt::get(Val), VT, isT);
00833 }
00834 
00835 SDValue SelectionDAG::getConstant(const ConstantInt &Val, MVT VT, bool isT) {
00836   assert(VT.isInteger() && "Cannot create FP integer constant!");
00837 
00838   MVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
00839   assert(Val.getBitWidth() == EltVT.getSizeInBits() &&
00840          "APInt size does not match type size!");
00841 
00842   unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
00843   FoldingSetNodeID ID;
00844   AddNodeIDNode(ID, Opc, getVTList(EltVT), 0, 0);
00845   ID.AddPointer(&Val);
00846   void *IP = 0;
00847   SDNode *N = NULL;
00848   if ((N = CSEMap.FindNodeOrInsertPos(ID, IP)))
00849