LLVM API Documentation

DAGCombiner.cpp

Go to the documentation of this file.
00001 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
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 pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
00011 // both before and after the DAG is legalized.
00012 // 
00013 //===----------------------------------------------------------------------===//
00014 
00015 #define DEBUG_TYPE "dagcombine"
00016 #include "llvm/CodeGen/SelectionDAG.h"
00017 #include "llvm/CodeGen/MachineFunction.h"
00018 #include "llvm/CodeGen/MachineFrameInfo.h"
00019 #include "llvm/Analysis/AliasAnalysis.h"
00020 #include "llvm/Target/TargetData.h"
00021 #include "llvm/Target/TargetFrameInfo.h"
00022 #include "llvm/Target/TargetLowering.h"
00023 #include "llvm/Target/TargetMachine.h"
00024 #include "llvm/Target/TargetOptions.h"
00025 #include "llvm/ADT/SmallPtrSet.h"
00026 #include "llvm/ADT/Statistic.h"
00027 #include "llvm/Support/Compiler.h"
00028 #include "llvm/Support/CommandLine.h"
00029 #include "llvm/Support/Debug.h"
00030 #include "llvm/Support/MathExtras.h"
00031 #include <algorithm>
00032 #include <set>
00033 using namespace llvm;
00034 
00035 STATISTIC(NodesCombined   , "Number of dag nodes combined");
00036 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
00037 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
00038 
00039 namespace {
00040   static cl::opt<bool>
00041     CombinerAA("combiner-alias-analysis", cl::Hidden,
00042                cl::desc("Turn on alias analysis during testing"));
00043 
00044   static cl::opt<bool>
00045     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
00046                cl::desc("Include global information in alias analysis"));
00047 
00048 //------------------------------ DAGCombiner ---------------------------------//
00049 
00050   class VISIBILITY_HIDDEN DAGCombiner {
00051     SelectionDAG &DAG;
00052     const TargetLowering &TLI;
00053     CombineLevel Level;
00054     bool LegalOperations;
00055     bool LegalTypes;
00056     bool Fast;
00057 
00058     // Worklist of all of the nodes that need to be simplified.
00059     std::vector<SDNode*> WorkList;
00060 
00061     // AA - Used for DAG load/store alias analysis.
00062     AliasAnalysis &AA;
00063 
00064     /// AddUsersToWorkList - When an instruction is simplified, add all users of
00065     /// the instruction to the work lists because they might get more simplified
00066     /// now.
00067     ///
00068     void AddUsersToWorkList(SDNode *N) {
00069       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
00070            UI != UE; ++UI)
00071         AddToWorkList(*UI);
00072     }
00073 
00074     /// visit - call the node-specific routine that knows how to fold each
00075     /// particular type of node.
00076     SDValue visit(SDNode *N);
00077 
00078   public:
00079     /// AddToWorkList - Add to the work list making sure it's instance is at the
00080     /// the back (next to be processed.)
00081     void AddToWorkList(SDNode *N) {
00082       removeFromWorkList(N);
00083       WorkList.push_back(N);
00084     }
00085 
00086     /// removeFromWorkList - remove all instances of N from the worklist.
00087     ///
00088     void removeFromWorkList(SDNode *N) {
00089       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
00090                      WorkList.end());
00091     }
00092     
00093     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00094                         bool AddTo = true);
00095     
00096     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
00097       return CombineTo(N, &Res, 1, AddTo);
00098     }
00099     
00100     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
00101                         bool AddTo = true) {
00102       SDValue To[] = { Res0, Res1 };
00103       return CombineTo(N, To, 2, AddTo);
00104     }
00105 
00106     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
00107     
00108   private:    
00109     
00110     /// SimplifyDemandedBits - Check the specified integer node value to see if
00111     /// it can be simplified or if things it uses can be simplified by bit
00112     /// propagation.  If so, return true.
00113     bool SimplifyDemandedBits(SDValue Op) {
00114       APInt Demanded = APInt::getAllOnesValue(Op.getValueSizeInBits());
00115       return SimplifyDemandedBits(Op, Demanded);
00116     }
00117 
00118     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
00119 
00120     bool CombineToPreIndexedLoadStore(SDNode *N);
00121     bool CombineToPostIndexedLoadStore(SDNode *N);
00122     
00123     
00124     /// combine - call the node-specific routine that knows how to fold each
00125     /// particular type of node. If that doesn't do anything, try the
00126     /// target-specific DAG combines.
00127     SDValue combine(SDNode *N);
00128 
00129     // Visitation implementation - Implement dag node combining for different
00130     // node types.  The semantics are as follows:
00131     // Return Value:
00132     //   SDValue.getNode() == 0 - No change was made
00133     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
00134     //   otherwise              - N should be replaced by the returned Operand.
00135     //
00136     SDValue visitTokenFactor(SDNode *N);
00137     SDValue visitMERGE_VALUES(SDNode *N);
00138     SDValue visitADD(SDNode *N);
00139     SDValue visitSUB(SDNode *N);
00140     SDValue visitADDC(SDNode *N);
00141     SDValue visitADDE(SDNode *N);
00142     SDValue visitMUL(SDNode *N);
00143     SDValue visitSDIV(SDNode *N);
00144     SDValue visitUDIV(SDNode *N);
00145     SDValue visitSREM(SDNode *N);
00146     SDValue visitUREM(SDNode *N);
00147     SDValue visitMULHU(SDNode *N);
00148     SDValue visitMULHS(SDNode *N);
00149     SDValue visitSMUL_LOHI(SDNode *N);
00150     SDValue visitUMUL_LOHI(SDNode *N);
00151     SDValue visitSDIVREM(SDNode *N);
00152     SDValue visitUDIVREM(SDNode *N);
00153     SDValue visitAND(SDNode *N);
00154     SDValue visitOR(SDNode *N);
00155     SDValue visitXOR(SDNode *N);
00156     SDValue SimplifyVBinOp(SDNode *N);
00157     SDValue visitSHL(SDNode *N);
00158     SDValue visitSRA(SDNode *N);
00159     SDValue visitSRL(SDNode *N);
00160     SDValue visitCTLZ(SDNode *N);
00161     SDValue visitCTTZ(SDNode *N);
00162     SDValue visitCTPOP(SDNode *N);
00163     SDValue visitSELECT(SDNode *N);
00164     SDValue visitSELECT_CC(SDNode *N);
00165     SDValue visitSETCC(SDNode *N);
00166     SDValue visitSIGN_EXTEND(SDNode *N);
00167     SDValue visitZERO_EXTEND(SDNode *N);
00168     SDValue visitANY_EXTEND(SDNode *N);
00169     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
00170     SDValue visitTRUNCATE(SDNode *N);
00171     SDValue visitBIT_CONVERT(SDNode *N);
00172     SDValue visitBUILD_PAIR(SDNode *N);
00173     SDValue visitFADD(SDNode *N);
00174     SDValue visitFSUB(SDNode *N);
00175     SDValue visitFMUL(SDNode *N);
00176     SDValue visitFDIV(SDNode *N);
00177     SDValue visitFREM(SDNode *N);
00178     SDValue visitFCOPYSIGN(SDNode *N);
00179     SDValue visitSINT_TO_FP(SDNode *N);
00180     SDValue visitUINT_TO_FP(SDNode *N);
00181     SDValue visitFP_TO_SINT(SDNode *N);
00182     SDValue visitFP_TO_UINT(SDNode *N);
00183     SDValue visitFP_ROUND(SDNode *N);
00184     SDValue visitFP_ROUND_INREG(SDNode *N);
00185     SDValue visitFP_EXTEND(SDNode *N);
00186     SDValue visitFNEG(SDNode *N);
00187     SDValue visitFABS(SDNode *N);
00188     SDValue visitBRCOND(SDNode *N);
00189     SDValue visitBR_CC(SDNode *N);
00190     SDValue visitLOAD(SDNode *N);
00191     SDValue visitSTORE(SDNode *N);
00192     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
00193     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
00194     SDValue visitBUILD_VECTOR(SDNode *N);
00195     SDValue visitCONCAT_VECTORS(SDNode *N);
00196     SDValue visitVECTOR_SHUFFLE(SDNode *N);
00197 
00198     SDValue XformToShuffleWithZero(SDNode *N);
00199     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
00200     
00201     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
00202 
00203     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
00204     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
00205     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
00206     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2, 
00207                              SDValue N3, ISD::CondCode CC, 
00208                              bool NotExtCompare = false);
00209     SDValue SimplifySetCC(MVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
00210                           DebugLoc DL, bool foldBooleans = true);
00211     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 
00212                                          unsigned HiOp);
00213     SDValue CombineConsecutiveLoads(SDNode *N, MVT VT);
00214     SDValue ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *, MVT);
00215     SDValue BuildSDIV(SDNode *N);
00216     SDValue BuildUDIV(SDNode *N);
00217     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
00218     SDValue ReduceLoadWidth(SDNode *N);
00219     
00220     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
00221     
00222     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
00223     /// looking for aliasing nodes and adding them to the Aliases vector.
00224     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
00225                           SmallVector<SDValue, 8> &Aliases);
00226 
00227     /// isAlias - Return true if there is any possibility that the two addresses
00228     /// overlap.
00229     bool isAlias(SDValue Ptr1, int64_t Size1,
00230                  const Value *SrcValue1, int SrcValueOffset1,
00231                  SDValue Ptr2, int64_t Size2,
00232                  const Value *SrcValue2, int SrcValueOffset2) const;
00233                  
00234     /// FindAliasInfo - Extracts the relevant alias information from the memory
00235     /// node.  Returns true if the operand was a load.
00236     bool FindAliasInfo(SDNode *N,
00237                        SDValue &Ptr, int64_t &Size,
00238                        const Value *&SrcValue, int &SrcValueOffset) const;
00239                        
00240     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
00241     /// looking for a better chain (aliasing node.)
00242     SDValue FindBetterChain(SDNode *N, SDValue Chain);
00243 
00244     /// getShiftAmountTy - Returns a type large enough to hold any valid
00245     /// shift amount - before type legalization these can be huge.
00246     MVT getShiftAmountTy() {
00247       return LegalTypes ?  TLI.getShiftAmountTy() : TLI.getPointerTy();
00248     }
00249 
00250 public:
00251     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, bool fast)
00252       : DAG(D),
00253         TLI(D.getTargetLoweringInfo()),
00254         Level(Unrestricted),
00255         LegalOperations(false),
00256         LegalTypes(false),
00257         Fast(fast),
00258         AA(A) {}
00259     
00260     /// Run - runs the dag combiner on all nodes in the work list
00261     void Run(CombineLevel AtLevel);
00262   };
00263 }
00264 
00265 
00266 namespace {
00267 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
00268 /// nodes from the worklist.
00269 class VISIBILITY_HIDDEN WorkListRemover : 
00270   public SelectionDAG::DAGUpdateListener {
00271   DAGCombiner &DC;
00272 public:
00273   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
00274   
00275   virtual void NodeDeleted(SDNode *N, SDNode *E) {
00276     DC.removeFromWorkList(N);
00277   }
00278   
00279   virtual void NodeUpdated(SDNode *N) {
00280     // Ignore updates.
00281   }
00282 };
00283 }
00284 
00285 //===----------------------------------------------------------------------===//
00286 //  TargetLowering::DAGCombinerInfo implementation
00287 //===----------------------------------------------------------------------===//
00288 
00289 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
00290   ((DAGCombiner*)DC)->AddToWorkList(N);
00291 }
00292 
00293 SDValue TargetLowering::DAGCombinerInfo::
00294 CombineTo(SDNode *N, const std::vector<SDValue> &To) {
00295   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size());
00296 }
00297 
00298 SDValue TargetLowering::DAGCombinerInfo::
00299 CombineTo(SDNode *N, SDValue Res) {
00300   return ((DAGCombiner*)DC)->CombineTo(N, Res);
00301 }
00302 
00303 
00304 SDValue TargetLowering::DAGCombinerInfo::
00305 CombineTo(SDNode *N, SDValue Res0, SDValue Res1) {
00306   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1);
00307 }
00308 
00309 void TargetLowering::DAGCombinerInfo::
00310 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
00311   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
00312 }
00313 
00314 //===----------------------------------------------------------------------===//
00315 // Helper Functions
00316 //===----------------------------------------------------------------------===//
00317 
00318 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
00319 /// specified expression for the same cost as the expression itself, or 2 if we
00320 /// can compute the negated form more cheaply than the expression itself.
00321 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
00322                                unsigned Depth = 0) {
00323   // No compile time optimizations on this type.
00324   if (Op.getValueType() == MVT::ppcf128)
00325     return 0;
00326 
00327   // fneg is removable even if it has multiple uses.
00328   if (Op.getOpcode() == ISD::FNEG) return 2;
00329   
00330   // Don't allow anything with multiple uses.
00331   if (!Op.hasOneUse()) return 0;
00332   
00333   // Don't recurse exponentially.
00334   if (Depth > 6) return 0;
00335   
00336   switch (Op.getOpcode()) {
00337   default: return false;
00338   case ISD::ConstantFP:
00339     // Don't invert constant FP values after legalize.  The negated constant
00340     // isn't necessarily legal.
00341     return LegalOperations ? 0 : 1;
00342   case ISD::FADD:
00343     // FIXME: determine better conditions for this xform.
00344     if (!UnsafeFPMath) return 0;
00345     
00346     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
00347     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00348       return V;
00349     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00350     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
00351   case ISD::FSUB:
00352     // We can't turn -(A-B) into B-A when we honor signed zeros. 
00353     if (!UnsafeFPMath) return 0;
00354     
00355     // fold (fneg (fsub A, B)) -> (fsub B, A)
00356     return 1;
00357     
00358   case ISD::FMUL:
00359   case ISD::FDIV:
00360     if (HonorSignDependentRoundingFPMath()) return 0;
00361     
00362     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
00363     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00364       return V;
00365       
00366     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
00367     
00368   case ISD::FP_EXTEND:
00369   case ISD::FP_ROUND:
00370   case ISD::FSIN:
00371     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
00372   }
00373 }
00374 
00375 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
00376 /// returns the newly negated expression.
00377 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
00378                                     bool LegalOperations, unsigned Depth = 0) {
00379   // fneg is removable even if it has multiple uses.
00380   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
00381   
00382   // Don't allow anything with multiple uses.
00383   assert(Op.hasOneUse() && "Unknown reuse!");
00384   
00385   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
00386   switch (Op.getOpcode()) {
00387   default: assert(0 && "Unknown code");
00388   case ISD::ConstantFP: {
00389     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
00390     V.changeSign();
00391     return DAG.getConstantFP(V, Op.getValueType());
00392   }
00393   case ISD::FADD:
00394     // FIXME: determine better conditions for this xform.
00395     assert(UnsafeFPMath);
00396     
00397     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
00398     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00399       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00400                          GetNegatedExpression(Op.getOperand(0), DAG, 
00401                                               LegalOperations, Depth+1),
00402                          Op.getOperand(1));
00403     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00404     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00405                        GetNegatedExpression(Op.getOperand(1), DAG, 
00406                                             LegalOperations, Depth+1),
00407                        Op.getOperand(0));
00408   case ISD::FSUB:
00409     // We can't turn -(A-B) into B-A when we honor signed zeros. 
00410     assert(UnsafeFPMath);
00411 
00412     // fold (fneg (fsub 0, B)) -> B
00413     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
00414       if (N0CFP->getValueAPF().isZero())
00415         return Op.getOperand(1);
00416     
00417     // fold (fneg (fsub A, B)) -> (fsub B, A)
00418     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
00419                        Op.getOperand(1), Op.getOperand(0));
00420     
00421   case ISD::FMUL:
00422   case ISD::FDIV:
00423     assert(!HonorSignDependentRoundingFPMath());
00424     
00425     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
00426     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
00427       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00428                          GetNegatedExpression(Op.getOperand(0), DAG, 
00429                                               LegalOperations, Depth+1),
00430                          Op.getOperand(1));
00431       
00432     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
00433     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00434                        Op.getOperand(0),
00435                        GetNegatedExpression(Op.getOperand(1), DAG,
00436                                             LegalOperations, Depth+1));
00437     
00438   case ISD::FP_EXTEND:
00439   case ISD::FSIN:
00440     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
00441                        GetNegatedExpression(Op.getOperand(0), DAG, 
00442                                             LegalOperations, Depth+1));
00443   case ISD::FP_ROUND:
00444       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
00445                          GetNegatedExpression(Op.getOperand(0), DAG, 
00446                                               LegalOperations, Depth+1),
00447                          Op.getOperand(1));
00448   }
00449 }
00450 
00451 
00452 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
00453 // that selects between the values 1 and 0, making it equivalent to a setcc.
00454 // Also, set the incoming LHS, RHS, and CC references to the appropriate 
00455 // nodes based on the type of node we are checking.  This simplifies life a
00456 // bit for the callers.
00457 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
00458                               SDValue &CC) {
00459   if (N.getOpcode() == ISD::SETCC) {
00460     LHS = N.getOperand(0);
00461     RHS = N.getOperand(1);
00462     CC  = N.getOperand(2);
00463     return true;
00464   }
00465   if (N.getOpcode() == ISD::SELECT_CC && 
00466       N.getOperand(2).getOpcode() == ISD::Constant &&
00467       N.getOperand(3).getOpcode() == ISD::Constant &&
00468       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
00469       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
00470     LHS = N.getOperand(0);
00471     RHS = N.getOperand(1);
00472     CC  = N.getOperand(4);
00473     return true;
00474   }
00475   return false;
00476 }
00477 
00478 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
00479 // one use.  If this is true, it allows the users to invert the operation for
00480 // free when it is profitable to do so.
00481 static bool isOneUseSetCC(SDValue N) {
00482   SDValue N0, N1, N2;
00483   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
00484     return true;
00485   return false;
00486 }
00487 
00488 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
00489                                     SDValue N0, SDValue N1) {
00490   MVT VT = N0.getValueType();
00491   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
00492     if (isa<ConstantSDNode>(N1)) {
00493       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
00494       SDValue OpNode =
00495         DAG.FoldConstantArithmetic(Opc, VT,
00496                                    cast<ConstantSDNode>(N0.getOperand(1)),
00497                                    cast<ConstantSDNode>(N1));
00498       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
00499     } else if (N0.hasOneUse()) {
00500       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
00501       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
00502                                    N0.getOperand(0), N1);
00503       AddToWorkList(OpNode.getNode());
00504       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
00505     }
00506   }
00507 
00508   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
00509     if (isa<ConstantSDNode>(N0)) {
00510       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
00511       SDValue OpNode =
00512         DAG.FoldConstantArithmetic(Opc, VT,
00513                                    cast<ConstantSDNode>(N1.getOperand(1)),
00514                                    cast<ConstantSDNode>(N0));
00515       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
00516     } else if (N1.hasOneUse()) {
00517       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
00518       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
00519                                    N1.getOperand(0), N0);
00520       AddToWorkList(OpNode.getNode());
00521       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
00522     }
00523   }
00524 
00525   return SDValue();
00526 }
00527 
00528 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00529                                bool AddTo) {
00530   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
00531   ++NodesCombined;
00532   DOUT << "\nReplacing.1 "; DEBUG(N->dump(&DAG));
00533   DOUT << "\nWith: "; DEBUG(To[0].getNode()->dump(&DAG));
00534   DOUT << " and " << NumTo-1 << " other values\n";
00535   DEBUG(for (unsigned i = 0, e = NumTo; i != e; ++i)
00536           assert(N->getValueType(i) == To[i].getValueType() &&
00537                  "Cannot combine value to value of different type!"));
00538   WorkListRemover DeadNodes(*this);
00539   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
00540   
00541   if (AddTo) {
00542     // Push the new nodes and any users onto the worklist
00543     for (unsigned i = 0, e = NumTo; i != e; ++i) {
00544       AddToWorkList(To[i].getNode());
00545       AddUsersToWorkList(To[i].getNode());
00546     }
00547   }
00548   
00549   // Finally, if the node is now dead, remove it from the graph.  The node
00550   // may not be dead if the replacement process recursively simplified to
00551   // something else needing this node.
00552   if (N->use_empty()) {
00553     // Nodes can be reintroduced into the worklist.  Make sure we do not
00554     // process a node that has been replaced.
00555     removeFromWorkList(N);
00556   
00557     // Finally, since the node is now dead, remove it from the graph.
00558     DAG.DeleteNode(N);
00559   }
00560   return SDValue(N, 0);
00561 }
00562 
00563 void
00564 DAGCombiner::CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &
00565                                                                           TLO) {
00566   // Replace all uses.  If any nodes become isomorphic to other nodes and 
00567   // are deleted, make sure to remove them from our worklist.
00568   WorkListRemover DeadNodes(*this);
00569   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
00570 
00571   // Push the new node and any (possibly new) users onto the worklist.
00572   AddToWorkList(TLO.New.getNode());
00573   AddUsersToWorkList(TLO.New.getNode());
00574   
00575   // Finally, if the node is now dead, remove it from the graph.  The node
00576   // may not be dead if the replacement process recursively simplified to
00577   // something else needing this node.
00578   if (TLO.Old.getNode()->use_empty()) {
00579     removeFromWorkList(TLO.Old.getNode());
00580     
00581     // If the operands of this node are only used by the node, they will now
00582     // be dead.  Make sure to visit them first to delete dead nodes early.
00583     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
00584       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
00585         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
00586     
00587     DAG.DeleteNode(TLO.Old.getNode());
00588   }
00589 }
00590 
00591 /// SimplifyDemandedBits - Check the specified integer node value to see if
00592 /// it can be simplified or if things it uses can be simplified by bit
00593 /// propagation.  If so, return true.
00594 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
00595   TargetLowering::TargetLoweringOpt TLO(DAG);
00596   APInt KnownZero, KnownOne;
00597   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
00598     return false;
00599   
00600   // Revisit the node.
00601   AddToWorkList(Op.getNode());
00602   
00603   // Replace the old value with the new one.
00604   ++NodesCombined;
00605   DOUT << "\nReplacing.2 "; DEBUG(TLO.Old.getNode()->dump(&DAG));
00606   DOUT << "\nWith: "; DEBUG(TLO.New.getNode()->dump(&DAG));
00607   DOUT << '\n';
00608   
00609   CommitTargetLoweringOpt(TLO);
00610   return true;
00611 }
00612 
00613 //===----------------------------------------------------------------------===//
00614 //  Main DAG Combiner implementation
00615 //===----------------------------------------------------------------------===//
00616 
00617 void DAGCombiner::Run(CombineLevel AtLevel) {
00618   // set the instance variables, so that the various visit routines may use it.
00619   Level = AtLevel;
00620   LegalOperations = Level >= NoIllegalOperations;
00621   LegalTypes = Level >= NoIllegalTypes;
00622 
00623   // Add all the dag nodes to the worklist.
00624   WorkList.reserve(DAG.allnodes_size());
00625   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
00626        E = DAG.allnodes_end(); I != E; ++I)
00627     WorkList.push_back(I);
00628 
00629   // Create a dummy node (which is not added to allnodes), that adds a reference
00630   // to the root node, preventing it from being deleted, and tracking any
00631   // changes of the root.
00632   HandleSDNode Dummy(DAG.getRoot());
00633   
00634   // The root of the dag may dangle to deleted nodes until the dag combiner is
00635   // done.  Set it to null to avoid confusion.
00636   DAG.setRoot(SDValue());
00637   
00638   // while the worklist isn't empty, inspect the node on the end of it and
00639   // try and combine it.
00640   while (!WorkList.empty()) {
00641     SDNode *N = WorkList.back();
00642     WorkList.pop_back();
00643     
00644     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
00645     // N is deleted from the DAG, since they too may now be dead or may have a
00646     // reduced number of uses, allowing other xforms.
00647     if (N->use_empty() && N != &Dummy) {
00648       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00649         AddToWorkList(N->getOperand(i).getNode());
00650       
00651       DAG.DeleteNode(N);
00652       continue;
00653     }
00654     
00655     SDValue RV = combine(N);
00656     
00657     if (RV.getNode() == 0)
00658       continue;
00659     
00660     ++NodesCombined;
00661     
00662     // If we get back the same node we passed in, rather than a new node or
00663     // zero, we know that the node must have defined multiple values and
00664     // CombineTo was used.  Since CombineTo takes care of the worklist 
00665     // mechanics for us, we have no work to do in this case.
00666     if (RV.getNode() == N)
00667       continue;
00668     
00669     assert(N->getOpcode() != ISD::DELETED_NODE &&
00670            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
00671            "Node was deleted but visit returned new node!");
00672 
00673     DOUT << "\nReplacing.3 "; DEBUG(N->dump(&DAG));
00674     DOUT << "\nWith: "; DEBUG(RV.getNode()->dump(&DAG));
00675     DOUT << '\n';
00676     WorkListRemover DeadNodes(*this);
00677     if (N->getNumValues() == RV.getNode()->getNumValues())
00678       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
00679     else {
00680       assert(N->getValueType(0) == RV.getValueType() &&
00681              N->getNumValues() == 1 && "Type mismatch");
00682       SDValue OpV = RV;
00683       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
00684     }
00685       
00686     // Push the new node and any users onto the worklist
00687     AddToWorkList(RV.getNode());
00688     AddUsersToWorkList(RV.getNode());
00689     
00690     // Add any uses of the old node to the worklist in case this node is the
00691     // last one that uses them.  They may become dead after this node is
00692     // deleted.
00693     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00694       AddToWorkList(N->getOperand(i).getNode());
00695       
00696     // Finally, if the node is now dead, remove it from the graph.  The node
00697     // may not be dead if the replacement process recursively simplified to
00698     // something else needing this node.
00699     if (N->use_empty()) {
00700       // Nodes can be reintroduced into the worklist.  Make sure we do not
00701       // process a node that has been replaced.
00702       removeFromWorkList(N);
00703     
00704       // Finally, since the node is now dead, remove it from the graph.
00705       DAG.DeleteNode(N);
00706     }
00707   }
00708   
00709   // If the root changed (e.g. it was a dead load, update the root).
00710   DAG.setRoot(Dummy.getValue());
00711 }
00712 
00713 SDValue DAGCombiner::visit(SDNode *N) {
00714   switch(N->getOpcode()) {
00715   default: break;
00716   case ISD::TokenFactor:        return visitTokenFactor(N);
00717   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
00718   case ISD::ADD:                return visitADD(N);
00719   case ISD::SUB:                return visitSUB(N);
00720   case ISD::ADDC:               return visitADDC(N);
00721   case ISD::ADDE:               return visitADDE(N);
00722   case ISD::MUL:                return visitMUL(N);
00723   case ISD::SDIV:               return visitSDIV(N);
00724   case ISD::UDIV:               return visitUDIV(N);
00725   case ISD::SREM:               return visitSREM(N);
00726   case ISD::UREM:               return visitUREM(N);
00727   case ISD::MULHU:              return visitMULHU(N);
00728   case ISD::MULHS:              return visitMULHS(N);
00729   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
00730   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
00731   case ISD::SDIVREM:            return visitSDIVREM(N);
00732   case ISD::UDIVREM:            return visitUDIVREM(N);
00733   case ISD::AND:                return visitAND(N);
00734   case ISD::OR:                 return visitOR(N);
00735   case ISD::XOR:                return visitXOR(N);
00736   case ISD::SHL:                return visitSHL(N);
00737   case ISD::SRA:                return visitSRA(N);
00738   case ISD::SRL:                return visitSRL(N);
00739   case ISD::CTLZ:               return visitCTLZ(N);
00740   case ISD::CTTZ:               return visitCTTZ(N);
00741   case ISD::CTPOP:              return visitCTPOP(N);
00742   case ISD::SELECT:             return visitSELECT(N);
00743   case ISD::SELECT_CC:          return visitSELECT_CC(N);
00744   case ISD::SETCC:              return visitSETCC(N);
00745   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
00746   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
00747   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
00748   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
00749   case ISD::TRUNCATE:           return visitTRUNCATE(N);
00750   case ISD::BIT_CONVERT:        return visitBIT_CONVERT(N);
00751   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
00752   case ISD::FADD:               return visitFADD(N);
00753   case ISD::FSUB:               return visitFSUB(N);
00754   case ISD::FMUL:               return visitFMUL(N);
00755   case ISD::FDIV:               return visitFDIV(N);
00756   case ISD::FREM:               return visitFREM(N);
00757   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
00758   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
00759   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
00760   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
00761   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
00762   case ISD::FP_ROUND:           return visitFP_ROUND(N);
00763   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
00764   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
00765   case ISD::FNEG:               return visitFNEG(N);
00766   case ISD::FABS:               return visitFABS(N);
00767   case ISD::BRCOND:             return visitBRCOND(N);
00768   case ISD::BR_CC:              return visitBR_CC(N);
00769   case ISD::LOAD:               return visitLOAD(N);
00770   case ISD::STORE:              return visitSTORE(N);
00771   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
00772   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
00773   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
00774   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
00775   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
00776   }
00777   return SDValue();
00778 }
00779 
00780 SDValue DAGCombiner::combine(SDNode *N) {
00781   SDValue RV = visit(N);
00782 
00783   // If nothing happened, try a target-specific DAG combine.
00784   if (RV.getNode() == 0) {
00785     assert(N->getOpcode() != ISD::DELETED_NODE &&
00786            "Node was deleted but visit returned NULL!");
00787 
00788     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
00789         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
00790 
00791       // Expose the DAG combiner to the target combiner impls.
00792       TargetLowering::DAGCombinerInfo 
00793         DagCombineInfo(DAG, Level == Unrestricted, false, this);
00794 
00795       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
00796     }
00797   }
00798 
00799   // If N is a commutative binary node, try commuting it to enable more 
00800   // sdisel CSE.
00801   if (RV.getNode() == 0 && 
00802       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
00803       N->getNumValues() == 1) {
00804     SDValue N0 = N->getOperand(0);
00805     SDValue N1 = N->getOperand(1);
00806 
00807     // Constant operands are canonicalized to RHS.
00808     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
00809       SDValue Ops[] = { N1, N0 };
00810       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
00811                                             Ops, 2);
00812       if (CSENode)
00813         return SDValue(CSENode, 0);
00814     }
00815   }
00816 
00817   return RV;
00818 } 
00819 
00820 /// getInputChainForNode - Given a node, return its input chain if it has one,
00821 /// otherwise return a null sd operand.
00822 static SDValue getInputChainForNode(SDNode *N) {
00823   if (unsigned NumOps = N->getNumOperands()) {
00824     if (N->getOperand(0).getValueType() == MVT::Other)
00825       return N->getOperand(0);
00826     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
00827       return N->getOperand(NumOps-1);
00828     for (unsigned i = 1; i < NumOps-1; ++i)
00829       if (N->getOperand(i).getValueType() == MVT::Other)
00830         return N->getOperand(i);
00831   }
00832   return SDValue();
00833 }
00834 
00835 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
00836   // If N has two operands, where one has an input chain equal to the other,
00837   // the 'other' chain is redundant.
00838   if (N->getNumOperands() == 2) {
00839     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
00840       return N->getOperand(0);
00841     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
00842       return N->getOperand(1);
00843   }
00844   
00845   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
00846   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
00847   SmallPtrSet<SDNode*, 16> SeenOps; 
00848   bool Changed = false;             // If we should replace this token factor.
00849   
00850   // Start out with this token factor.
00851   TFs.push_back(N);
00852   
00853   // Iterate through token factors.  The TFs grows when new token factors are
00854   // encountered.
00855   for (unsigned i = 0; i < TFs.size(); ++i) {
00856     SDNode *TF = TFs[i];
00857     
00858     // Check each of the operands.
00859     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
00860       SDValue Op = TF->getOperand(i);
00861       
00862       switch (Op.getOpcode()) {
00863       case ISD::EntryToken:
00864         // Entry tokens don't need to be added to the list. They are
00865         // rededundant.
00866         Changed = true;
00867         break;
00868         
00869       case ISD::TokenFactor:
00870         if ((CombinerAA || Op.hasOneUse()) &&
00871             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
00872           // Queue up for processing.
00873           TFs.push_back(Op.getNode());
00874           // Clean up in case the token factor is removed.
00875           AddToWorkList(Op.getNode());
00876           Changed = true;
00877           break;
00878         }
00879         // Fall thru
00880         
00881       default:
00882         // Only add if it isn't already in the list.
00883         if (SeenOps.insert(Op.getNode()))
00884           Ops.push_back(Op);
00885         else
00886           Changed = true;
00887         break;
00888       }
00889     }
00890   }
00891 
00892   SDValue Result;
00893 
00894   // If we've change things around then replace token factor.
00895   if (Changed) {
00896     if (Ops.empty()) {
00897       // The entry token is the only possible outcome.
00898       Result = DAG.getEntryNode();
00899     } else {
00900       // New and improved token factor.
00901       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
00902                            MVT::Other, &Ops[0], Ops.size());
00903     }
00904 
00905     // Don't add users to work list.
00906     return CombineTo(N, Result, false);
00907   }
00908   
00909   return Result;
00910 }
00911 
00912 /// MERGE_VALUES can always be eliminated.
00913 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
00914   WorkListRemover DeadNodes(*this);
00915   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
00916     DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
00917                                   &DeadNodes);
00918   removeFromWorkList(N);
00919   DAG.DeleteNode(N);
00920   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
00921 }
00922 
00923 static
00924 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
00925                               SelectionDAG &DAG) {
00926   MVT VT = N0.getValueType();
00927   SDValue N00 = N0.getOperand(0);
00928   SDValue N01 = N0.getOperand(1);
00929   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
00930 
00931   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
00932       isa<ConstantSDNode>(N00.getOperand(1))) {
00933     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
00934     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
00935                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
00936                                  N00.getOperand(0), N01),
00937                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
00938                                  N00.getOperand(1), N01));
00939     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
00940   }
00941 
00942   return SDValue();
00943 }
00944 
00945 static
00946 SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
00947                             SelectionDAG &DAG, const TargetLowering &TLI,
00948                             bool LegalOperations) {
00949   MVT VT = N->getValueType(0);
00950   unsigned Opc = N->getOpcode();
00951   bool isSlctCC = Slct.getOpcode() == ISD::SELECT_CC;
00952   SDValue LHS = isSlctCC ? Slct.getOperand(2) : Slct.getOperand(1);
00953   SDValue RHS = isSlctCC ? Slct.getOperand(3) : Slct.getOperand(2);
00954   ISD::CondCode CC = ISD::SETCC_INVALID;
00955 
00956   if (isSlctCC) {
00957     CC = cast<CondCodeSDNode>(Slct.getOperand(4))->get();
00958   } else {
00959     SDValue CCOp = Slct.getOperand(0);
00960     if (CCOp.getOpcode() == ISD::SETCC)
00961       CC = cast<CondCodeSDNode>(CCOp.getOperand(2))->get();
00962   }
00963 
00964   bool DoXform = false;
00965   bool InvCC = false;
00966   assert ((Opc == ISD::ADD || (Opc == ISD::SUB && Slct == N->getOperand(1))) &&
00967           "Bad input!");
00968 
00969   if (LHS.getOpcode() == ISD::Constant &&
00970       cast<ConstantSDNode>(LHS)->isNullValue()) {
00971     DoXform = true;
00972   } else if (CC != ISD::SETCC_INVALID &&
00973              RHS.getOpcode() == ISD::Constant &&
00974              cast<ConstantSDNode>(RHS)->isNullValue()) {
00975     std::swap(LHS, RHS);
00976     SDValue Op0 = Slct.getOperand(0);
00977     MVT OpVT = isSlctCC ? Op0.getValueType() :
00978                           Op0.getOperand(0).getValueType();
00979     bool isInt = OpVT.isInteger();
00980     CC = ISD::getSetCCInverse(CC, isInt);
00981 
00982     if (LegalOperations && !TLI.isCondCodeLegal(CC, OpVT))
00983       return SDValue();         // Inverse operator isn't legal.
00984 
00985     DoXform = true;
00986     InvCC = true;
00987   }
00988 
00989   if (DoXform) {
00990     SDValue Result = DAG.getNode(Opc, RHS.getDebugLoc(), VT, OtherOp, RHS);
00991     if (isSlctCC)
00992       return DAG.getSelectCC(N->getDebugLoc(), OtherOp, Result,
00993                              Slct.getOperand(0), Slct.getOperand(1), CC);
00994     SDValue CCOp = Slct.getOperand(0);
00995     if (InvCC)
00996       CCOp = DAG.getSetCC(Slct.getDebugLoc(), CCOp.getValueType(),
00997                           CCOp.getOperand(0), CCOp.getOperand(1), CC);
00998     return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
00999                        CCOp, OtherOp, Result);
01000   }
01001   return SDValue();
01002 }
01003 
01004 SDValue DAGCombiner::visitADD(SDNode *N) {
01005   SDValue N0 = N->getOperand(0);
01006   SDValue N1 = N->getOperand(1);
01007   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01008   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01009   MVT VT = N0.getValueType();
01010 
01011   // fold vector ops
01012   if (VT.isVector()) {
01013     SDValue FoldedVOp = SimplifyVBinOp(N);
01014     if (FoldedVOp.getNode()) return FoldedVOp;
01015   }
01016 
01017   // fold (add x, undef) -> undef
01018   if (N0.getOpcode() == ISD::UNDEF)
01019     return N0;
01020   if (N1.getOpcode() == ISD::UNDEF)
01021     return N1;
01022   // fold (add c1, c2) -> c1+c2
01023   if (N0C && N1C)
01024     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
01025   // canonicalize constant to RHS
01026   if (N0C && !N1C)
01027     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
01028   // fold (add x, 0) -> x
01029   if (N1C && N1C->isNullValue())
01030     return N0;
01031   // fold (add Sym, c) -> Sym+c
01032   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
01033     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
01034         GA->getOpcode() == ISD::GlobalAddress)
01035       return DAG.getGlobalAddress(GA->getGlobal(), VT,
01036                                   GA->getOffset() +
01037                                     (uint64_t)N1C->getSExtValue());
01038   // fold ((c1-A)+c2) -> (c1+c2)-A
01039   if (N1C && N0.getOpcode() == ISD::SUB)
01040     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
01041       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01042                          DAG.getConstant(N1C->getAPIntValue()+
01043                                          N0C->getAPIntValue(), VT),
01044                          N0.getOperand(1));
01045   // reassociate add
01046   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
01047   if (RADD.getNode() != 0)
01048     return RADD;
01049   // fold ((0-A) + B) -> B-A
01050   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
01051       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
01052     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
01053   // fold (A + (0-B)) -> A-B
01054   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
01055       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
01056     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
01057   // fold (A+(B-A)) -> B
01058   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
01059     return N1.getOperand(0);
01060   // fold ((B-A)+A) -> B
01061   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
01062     return N0.getOperand(0);
01063   // fold (A+(B-(A+C))) to (B-C)
01064   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01065       N0 == N1.getOperand(1).getOperand(0))
01066     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
01067                        N1.getOperand(1).getOperand(1));
01068   // fold (A+(B-(C+A))) to (B-C)
01069   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01070       N0 == N1.getOperand(1).getOperand(1))
01071     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
01072                        N1.getOperand(1).getOperand(0));
01073   // fold (A+((B-A)+or-C)) to (B+or-C)
01074   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
01075       N1.getOperand(0).getOpcode() == ISD::SUB &&
01076       N0 == N1.getOperand(0).getOperand(1))
01077     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
01078                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
01079 
01080   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
01081   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
01082     SDValue N00 = N0.getOperand(0);
01083     SDValue N01 = N0.getOperand(1);
01084     SDValue N10 = N1.getOperand(0);
01085     SDValue N11 = N1.getOperand(1);
01086 
01087     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
01088       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01089                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
01090                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
01091   }
01092 
01093   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
01094     return SDValue(N, 0);
01095   
01096   // fold (a+b) -> (a|b) iff a and b share no bits.
01097   if (VT.isInteger() && !VT.isVector()) {
01098     APInt LHSZero, LHSOne;
01099     APInt RHSZero, RHSOne;
01100     APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
01101     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
01102 
01103     if (LHSZero.getBoolValue()) {
01104       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
01105       
01106       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01107       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01108       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
01109           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
01110         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
01111     }
01112   }
01113 
01114   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
01115   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
01116     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
01117     if (Result.getNode()) return Result;
01118   }
01119   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
01120     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
01121     if (Result.getNode()) return Result;
01122   }
01123 
01124   // fold (add (select cc, 0, c), x) -> (select cc, x, (add, x, c))
01125   if (N0.getOpcode() == ISD::SELECT && N0.getNode()->hasOneUse()) {
01126     SDValue Result = combineSelectAndUse(N, N0, N1, DAG, TLI, LegalOperations);
01127     if (Result.getNode()) return Result;
01128   }
01129   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
01130     SDValue Result = combineSelectAndUse(N, N1, N0, DAG, TLI, LegalOperations);
01131     if (Result.getNode()) return Result;
01132   }
01133 
01134   return SDValue();
01135 }
01136 
01137 SDValue DAGCombiner::visitADDC(SDNode *N) {
01138   SDValue N0 = N->getOperand(0);
01139   SDValue N1 = N->getOperand(1);
01140   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01141   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01142   MVT VT = N0.getValueType();
01143   
01144   // If the flag result is dead, turn this into an ADD.
01145   if (N->hasNUsesOfValue(0, 1))
01146     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
01147                      DAG.getNode(ISD::CARRY_FALSE,
01148                                  N->getDebugLoc(), MVT::Flag));
01149   
01150   // canonicalize constant to RHS.
01151   if (N0C && !N1C)
01152     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
01153   
01154   // fold (addc x, 0) -> x + no carry out
01155   if (N1C && N1C->isNullValue())
01156     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
01157                                         N->getDebugLoc(), MVT::Flag));
01158   
01159   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
01160   APInt LHSZero, LHSOne;
01161   APInt RHSZero, RHSOne;
01162   APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
01163   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
01164 
01165   if (LHSZero.getBoolValue()) {
01166     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
01167     
01168     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01169     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01170     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
01171         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
01172       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
01173                        DAG.getNode(ISD::CARRY_FALSE,
01174                                    N->getDebugLoc(), MVT::Flag));
01175   }
01176   
01177   return SDValue();
01178 }
01179 
01180 SDValue DAGCombiner::visitADDE(SDNode *N) {
01181   SDValue N0 = N->getOperand(0);
01182   SDValue N1 = N->getOperand(1);
01183   SDValue CarryIn = N->getOperand(2);
01184   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01185   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01186   
01187   // canonicalize constant to RHS
01188   if (N0C && !N1C)
01189     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
01190                        N1, N0, CarryIn);
01191   
01192   // fold (adde x, y, false) -> (addc x, y)
01193   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
01194     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
01195   
01196   return SDValue();
01197 }
01198 
01199 SDValue DAGCombiner::visitSUB(SDNode *N) {
01200   SDValue N0 = N->getOperand(0);
01201   SDValue N1 = N->getOperand(1);
01202   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01203   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01204   MVT VT = N0.getValueType();
01205   
01206   // fold vector ops
01207   if (VT.isVector()) {
01208     SDValue FoldedVOp = SimplifyVBinOp(N);
01209     if (FoldedVOp.getNode()) return FoldedVOp;
01210   }
01211 
01212   // fold (sub x, x) -> 0
01213   if (N0 == N1)
01214     return DAG.getConstant(0, N->getValueType(0));
01215   // fold (sub c1, c2) -> c1-c2
01216   if (N0C && N1C)
01217     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
01218   // fold (sub x, c) -> (add x, -c)
01219   if (N1C)
01220     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
01221                        DAG.getConstant(-N1C->getAPIntValue(), VT));
01222   // fold (A+B)-A -> B
01223   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
01224     return N0.getOperand(1);
01225   // fold (A+B)-B -> A
01226   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
01227     return N0.getOperand(0); 
01228   // fold ((A+(B+or-C))-B) -> A+or-C
01229   if (N0.getOpcode() == ISD::ADD &&
01230       (N0.getOperand(1).getOpcode() == ISD::SUB ||
01231        N0.getOperand(1).getOpcode() == ISD::ADD) &&
01232       N0.getOperand(1).getOperand(0) == N1)
01233     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
01234                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
01235   // fold ((A+(C+B))-B) -> A+C
01236   if (N0.getOpcode() == ISD::ADD &&
01237       N0.getOperand(1).getOpcode() == ISD::ADD &&
01238       N0.getOperand(1).getOperand(1) == N1)
01239     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
01240                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01241   // fold ((A-(B-C))-C) -> A-B
01242   if (N0.getOpcode() == ISD::SUB &&
01243       N0.getOperand(1).getOpcode() == ISD::SUB &&
01244       N0.getOperand(1).getOperand(1) == N1)
01245     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01246                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01247   // fold (sub x, (select cc, 0, c)) -> (select cc, x, (sub, x, c))
01248   if (N1.getOpcode() == ISD::SELECT && N1.getNode()->hasOneUse()) {
01249     SDValue Result = combineSelectAndUse(N, N1, N0, DAG, TLI, LegalOperations);
01250     if (Result.getNode()) return Result;
01251   }
01252 
01253   // If either operand of a sub is undef, the result is undef
01254   if (N0.getOpcode() == ISD::UNDEF)
01255     return N0;
01256   if (N1.getOpcode() == ISD::UNDEF)
01257     return N1;
01258 
01259   // If the relocation model supports it, consider symbol offsets.
01260   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
01261     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
01262       // fold (sub Sym, c) -> Sym-c
01263       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
01264         return DAG.getGlobalAddress(GA->getGlobal(), VT,
01265                                     GA->getOffset() -
01266                                       (uint64_t)N1C->getSExtValue());
01267       // fold (sub Sym+c1, Sym+c2) -> c1-c2
01268       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
01269         if (GA->getGlobal() == GB->getGlobal())
01270           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
01271                                  VT);
01272     }
01273 
01274   return SDValue();
01275 }
01276 
01277 SDValue DAGCombiner::visitMUL(SDNode *N) {
01278   SDValue N0 = N->getOperand(0);
01279   SDValue N1 = N->getOperand(1);
01280   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01281   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01282   MVT VT = N0.getValueType();
01283   
01284   // fold vector ops
01285   if (VT.isVector()) {
01286     SDValue FoldedVOp = SimplifyVBinOp(N);
01287     if (FoldedVOp.getNode()) return FoldedVOp;
01288   }
01289   
01290   // fold (mul x, undef) -> 0
01291   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01292     return DAG.getConstant(0, VT);
01293   // fold (mul c1, c2) -> c1*c2
01294   if (N0C && N1C)
01295     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
01296   // canonicalize constant to RHS
01297   if (N0C && !N1C)
01298     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
01299   // fold (mul x, 0) -> 0
01300   if (N1C && N1C->isNullValue())
01301     return N1;
01302   // fold (mul x, -1) -> 0-x
01303   if (N1C && N1C->isAllOnesValue())
01304     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01305                        DAG.getConstant(0, VT), N0);
01306   // fold (mul x, (1 << c)) -> x << c
01307   if (N1C && N1C->getAPIntValue().isPowerOf2())
01308     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
01309                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
01310                                        getShiftAmountTy()));
01311   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
01312   if (N1C && isPowerOf2_64(-N1C->getSExtValue()))
01313     // FIXME: If the input is something that is easily negated (e.g. a 
01314     // single-use add), we should put the negate there.
01315     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01316                        DAG.getConstant(0, VT),
01317                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
01318                             DAG.getConstant(Log2_64(-N1C->getSExtValue()),
01319                                             getShiftAmountTy())));
01320   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
01321   if (N1C && N0.getOpcode() == ISD::SHL &&
01322       isa<ConstantSDNode>(N0.getOperand(1))) {
01323     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
01324                              N1, N0.getOperand(1));
01325     AddToWorkList(C3.getNode());
01326     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01327                        N0.getOperand(0), C3);
01328   }
01329   
01330   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
01331   // use.
01332   {
01333     SDValue Sh(0,0), Y(0,0);
01334     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
01335     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
01336         N0.getNode()->hasOneUse()) {
01337       Sh = N0; Y = N1;
01338     } else if (N1.getOpcode() == ISD::SHL && 
01339                isa<ConstantSDNode>(N1.getOperand(1)) &&
01340                N1.getNode()->hasOneUse()) {
01341       Sh = N1; Y = N0;
01342     }
01343 
01344     if (Sh.getNode()) {
01345       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01346                                 Sh.getOperand(0), Y);
01347       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
01348                          Mul, Sh.getOperand(1));
01349     }
01350   }
01351 
01352   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
01353   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() && 
01354       isa<ConstantSDNode>(N0.getOperand(1)))
01355     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
01356                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
01357                                    N0.getOperand(0), N1),
01358                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
01359                                    N0.getOperand(1), N1));
01360   
01361   // reassociate mul
01362   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
01363   if (RMUL.getNode() != 0)
01364     return RMUL;
01365 
01366   return SDValue();
01367 }
01368 
01369 SDValue DAGCombiner::visitSDIV(SDNode *N) {
01370   SDValue N0 = N->getOperand(0);
01371   SDValue N1 = N->getOperand(1);
01372   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01373   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01374   MVT VT = N->getValueType(0);
01375 
01376   // fold vector ops
01377   if (VT.isVector()) {
01378     SDValue FoldedVOp = SimplifyVBinOp(N);
01379     if (FoldedVOp.getNode()) return FoldedVOp;
01380   }
01381   
01382   // fold (sdiv c1, c2) -> c1/c2
01383   if (N0C && N1C && !N1C->isNullValue())
01384     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
01385   // fold (sdiv X, 1) -> X
01386   if (N1C && N1C->getSExtValue() == 1LL)
01387     return N0;
01388   // fold (sdiv X, -1) -> 0-X
01389   if (N1C && N1C->isAllOnesValue())
01390     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01391                        DAG.getConstant(0, VT), N0);
01392   // If we know the sign bits of both operands are zero, strength reduce to a
01393   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
01394   if (!VT.isVector()) {
01395     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
01396       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
01397                          N0, N1);
01398   }
01399   // fold (sdiv X, pow2) -> simple ops after legalize
01400   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
01401       (isPowerOf2_64(N1C->getSExtValue()) || 
01402        isPowerOf2_64(-N1C->getSExtValue()))) {
01403     // If dividing by powers of two is cheap, then don't perform the following
01404     // fold.
01405     if (TLI.isPow2DivCheap())
01406       return SDValue();
01407 
01408     int64_t pow2 = N1C->getSExtValue();
01409     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
01410     unsigned lg2 = Log2_64(abs2);
01411 
01412     // Splat the sign bit into the register
01413     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
01414                               DAG.getConstant(VT.getSizeInBits()-1,
01415                                               getShiftAmountTy()));
01416     AddToWorkList(SGN.getNode());
01417 
01418     // Add (N0 < 0) ? abs2 - 1 : 0;
01419     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
01420                               DAG.getConstant(VT.getSizeInBits() - lg2,
01421                                               getShiftAmountTy()));
01422     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
01423     AddToWorkList(SRL.getNode());
01424     AddToWorkList(ADD.getNode());    // Divide by pow2
01425     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
01426                               DAG.getConstant(lg2, getShiftAmountTy()));
01427 
01428     // If we're dividing by a positive value, we're done.  Otherwise, we must
01429     // negate the result.
01430     if (pow2 > 0)
01431       return SRA;
01432 
01433     AddToWorkList(SRA.getNode());
01434     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
01435                        DAG.getConstant(0, VT), SRA);
01436   }
01437 
01438   // if integer divide is expensive and we satisfy the requirements, emit an
01439   // alternate sequence.
01440   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) && 
01441       !TLI.isIntDivCheap()) {
01442     SDValue Op = BuildSDIV(N);
01443     if (Op.getNode()) return Op;
01444   }
01445 
01446   // undef / X -> 0
01447   if (N0.getOpcode() == ISD::UNDEF)
01448     return DAG.getConstant(0, VT);
01449   // X / undef -> undef
01450   if (N1.getOpcode() == ISD::UNDEF)
01451     return N1;
01452 
01453   return SDValue();
01454 }
01455 
01456 SDValue DAGCombiner::visitUDIV(SDNode *N) {
01457   SDValue N0 = N->getOperand(0);
01458   SDValue N1 = N->getOperand(1);
01459   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01460   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01461   MVT VT = N->getValueType(0);
01462   
01463   // fold vector ops
01464   if (VT.isVector()) {
01465     SDValue FoldedVOp = SimplifyVBinOp(N);
01466     if (FoldedVOp.getNode()) return FoldedVOp;
01467   }
01468   
01469   // fold (udiv c1, c2) -> c1/c2
01470   if (N0C && N1C && !N1C->isNullValue())
01471     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
01472   // fold (udiv x, (1 << c)) -> x >>u c
01473   if (N1C && N1C->getAPIntValue().isPowerOf2())
01474     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, 
01475                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
01476                                        getShiftAmountTy()));
01477   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
01478   if (N1.getOpcode() == ISD::SHL) {
01479     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
01480       if (SHC->getAPIntValue().isPowerOf2()) {
01481         MVT ADDVT = N1.getOperand(1).getValueType();
01482         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
01483                                   N1.getOperand(1),
01484                                   DAG.getConstant(SHC->getAPIntValue()
01485                                                                   .logBase2(),
01486                                                   ADDVT));
01487         AddToWorkList(Add.getNode());
01488         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
01489       }
01490     }
01491   }
01492   // fold (udiv x, c) -> alternate
01493   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
01494     SDValue Op = BuildUDIV(N);
01495     if (Op.getNode()) return Op;
01496   }
01497 
01498   // undef / X -> 0
01499   if (N0.getOpcode() == ISD::UNDEF)
01500     return DAG.getConstant(0, VT);
01501   // X / undef -> undef
01502   if (N1.getOpcode() == ISD::UNDEF)
01503     return N1;
01504 
01505   return SDValue();
01506 }
01507 
01508 SDValue DAGCombiner::visitSREM(SDNode *N) {
01509   SDValue N0 = N->getOperand(0);
01510   SDValue N1 = N->getOperand(1);
01511   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01512   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01513   MVT VT = N->getValueType(0);
01514   
01515   // fold (srem c1, c2) -> c1%c2
01516   if (N0C && N1C && !N1C->isNullValue())
01517     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
01518   // If we know the sign bits of both operands are zero, strength reduce to a
01519   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
01520   if (!VT.isVector()) {
01521     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
01522       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
01523   }
01524   
01525   // If X/C can be simplified by the division-by-constant logic, lower
01526   // X%C to the equivalent of X-X/C*C.
01527   if (N1C && !N1C->isNullValue()) {
01528     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
01529     AddToWorkList(Div.getNode());
01530     SDValue OptimizedDiv = combine(Div.getNode());
01531     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
01532       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01533                                 OptimizedDiv, N1);
01534       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
01535       AddToWorkList(Mul.getNode());
01536       return Sub;
01537     }
01538   }
01539   
01540   // undef % X -> 0
01541   if (N0.getOpcode() == ISD::UNDEF)
01542     return DAG.getConstant(0, VT);
01543   // X % undef -> undef
01544   if (N1.getOpcode() == ISD::UNDEF)
01545     return N1;
01546 
01547   return SDValue();
01548 }
01549 
01550 SDValue DAGCombiner::visitUREM(SDNode *N) {
01551   SDValue N0 = N->getOperand(0);
01552   SDValue N1 = N->getOperand(1);
01553   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01554   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01555   MVT VT = N->getValueType(0);
01556   
01557   // fold (urem c1, c2) -> c1%c2
01558   if (N0C && N1C && !N1C->isNullValue())
01559     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
01560   // fold (urem x, pow2) -> (and x, pow2-1)
01561   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
01562     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
01563                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
01564   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
01565   if (N1.getOpcode() == ISD::SHL) {
01566     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
01567       if (SHC->getAPIntValue().isPowerOf2()) {
01568         SDValue Add =
01569           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
01570                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
01571                                  VT));
01572         AddToWorkList(Add.getNode());
01573         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
01574       }
01575     }
01576   }
01577   
01578   // If X/C can be simplified by the division-by-constant logic, lower
01579   // X%C to the equivalent of X-X/C*C.
01580   if (N1C && !N1C->isNullValue()) {
01581     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
01582     AddToWorkList(Div.getNode());
01583     SDValue OptimizedDiv = combine(Div.getNode());
01584     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
01585       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
01586                                 OptimizedDiv, N1);
01587       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
01588       AddToWorkList(Mul.getNode());
01589       return Sub;
01590     }
01591   }
01592   
01593   // undef % X -> 0
01594   if (N0.getOpcode() == ISD::UNDEF)
01595     return DAG.getConstant(0, VT);
01596   // X % undef -> undef
01597   if (N1.getOpcode() == ISD::UNDEF)
01598     return N1;
01599 
01600   return SDValue();
01601 }
01602 
01603 SDValue DAGCombiner::visitMULHS(SDNode *N) {
01604   SDValue N0 = N->getOperand(0);
01605   SDValue N1 = N->getOperand(1);
01606   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01607   MVT VT = N->getValueType(0);
01608   
01609   // fold (mulhs x, 0) -> 0
01610   if (N1C && N1C->isNullValue())
01611     return N1;
01612   // fold (mulhs x, 1) -> (sra x, size(x)-1)
01613   if (N1C && N1C->getAPIntValue() == 1)
01614     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
01615                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
01616                                        getShiftAmountTy()));
01617   // fold (mulhs x, undef) -> 0
01618   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01619     return DAG.getConstant(0, VT);
01620 
01621   return SDValue();
01622 }
01623 
01624 SDValue DAGCombiner::visitMULHU(SDNode *N) {
01625   SDValue N0 = N->getOperand(0);
01626   SDValue N1 = N->getOperand(1);
01627   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01628   MVT VT = N->getValueType(0);
01629   
01630   // fold (mulhu x, 0) -> 0
01631   if (N1C && N1C->isNullValue())
01632     return N1;
01633   // fold (mulhu x, 1) -> 0
01634   if (N1C && N1C->getAPIntValue() == 1)
01635     return DAG.getConstant(0, N0.getValueType());
01636   // fold (mulhu x, undef) -> 0
01637   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01638     return DAG.getConstant(0, VT);
01639 
01640   return SDValue();
01641 }
01642 
01643 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
01644 /// compute two values. LoOp and HiOp give the opcodes for the two computations
01645 /// that are being performed. Return true if a simplification was made.
01646 ///
01647 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp, 
01648                                                 unsigned HiOp) {
01649   // If the high half is not needed, just compute the low half.
01650   bool HiExists = N->hasAnyUseOfValue(1);
01651   if (!HiExists &&
01652       (!LegalOperations ||
01653        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
01654     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
01655                               N->op_begin(), N->getNumOperands());
01656     return CombineTo(N, Res, Res);
01657   }
01658 
01659   // If the low half is not needed, just compute the high half.
01660   bool LoExists = N->hasAnyUseOfValue(0);
01661   if (!LoExists &&
01662       (!LegalOperations ||
01663        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
01664     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
01665                               N->op_begin(), N->getNumOperands());
01666     return CombineTo(N, Res, Res);
01667   }
01668 
01669   // If both halves are used, return as it is.
01670   if (LoExists && HiExists)
01671     return SDValue();
01672 
01673   // If the two computed results can be simplified separately, separate them.
01674   if (LoExists) {
01675     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
01676                              N->op_begin(), N->getNumOperands());
01677     AddToWorkList(Lo.getNode());
01678     SDValue LoOpt = combine(Lo.getNode());
01679     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
01680         (!LegalOperations ||
01681          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
01682       return CombineTo(N, LoOpt, LoOpt);
01683   }
01684 
01685   if (HiExists) {
01686     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
01687                              N->op_begin(), N->getNumOperands());
01688     AddToWorkList(Hi.getNode());
01689     SDValue HiOpt = combine(Hi.getNode());
01690     if (HiOpt.getNode() && HiOpt != Hi &&
01691         (!LegalOperations ||
01692          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
01693       return CombineTo(N, HiOpt, HiOpt);
01694   }
01695 
01696   return SDValue();
01697 }
01698 
01699 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
01700   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
01701   if (Res.getNode()) return Res;
01702 
01703   return SDValue();
01704 }
01705 
01706 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
01707   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
01708   if (Res.getNode()) return Res;
01709 
01710   return SDValue();
01711 }
01712 
01713 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
01714   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
01715   if (Res.getNode()) return Res;
01716   
01717   return SDValue();
01718 }
01719 
01720 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
01721   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
01722   if (Res.getNode()) return Res;
01723   
01724   return SDValue();
01725 }
01726 
01727 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
01728 /// two operands of the same opcode, try to simplify it.
01729 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
01730   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
01731   MVT VT = N0.getValueType();
01732   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
01733   
01734   // For each of OP in AND/OR/XOR:
01735   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
01736   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
01737   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
01738   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y))
01739   if ((N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND||
01740        N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::TRUNCATE) &&
01741       N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()) {
01742     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
01743                                  N0.getOperand(0).getValueType(),
01744                                  N0.getOperand(0), N1.getOperand(0));
01745     AddToWorkList(ORNode.getNode());
01746     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
01747   }
01748   
01749   // For each of OP in SHL/SRL/SRA/AND...
01750   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
01751   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
01752   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
01753   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
01754        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
01755       N0.getOperand(1) == N1.getOperand(1)) {
01756     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
01757                                  N0.getOperand(0).getValueType(),
01758                                  N0.getOperand(0), N1.getOperand(0));
01759     AddToWorkList(ORNode.getNode());
01760     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
01761                        ORNode, N0.getOperand(1));
01762   }
01763   
01764   return SDValue();
01765 }
01766 
01767 SDValue DAGCombiner::visitAND(SDNode *N) {
01768   SDValue N0 = N->getOperand(0);
01769   SDValue N1 = N->getOperand(1);
01770   SDValue LL, LR, RL, RR, CC0, CC1;
01771   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01772   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01773   MVT VT = N1.getValueType();
01774   unsigned BitWidth = VT.getSizeInBits();
01775   
01776   // fold vector ops
01777   if (VT.isVector()) {
01778     SDValue FoldedVOp = SimplifyVBinOp(N);
01779     if (FoldedVOp.getNode()) return FoldedVOp;
01780   }
01781   
01782   // fold (and x, undef) -> 0
01783   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01784     return DAG.getConstant(0, VT);
01785   // fold (and c1, c2) -> c1&c2
01786   if (N0C && N1C)
01787     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
01788   // canonicalize constant to RHS
01789   if (N0C && !N1C)
01790     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
01791   // fold (and x, -1) -> x
01792   if (N1C && N1C->isAllOnesValue())
01793     return N0;
01794   // if (and x, c) is known to be zero, return 0
01795   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
01796                                    APInt::getAllOnesValue(BitWidth)))
01797     return DAG.getConstant(0, VT);
01798   // reassociate and
01799   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
01800   if (RAND.getNode() != 0)
01801     return RAND;
01802   // fold (and (or x, 0xFFFF), 0xFF) -> 0xFF
01803   if (N1C && N0.getOpcode() == ISD::OR)
01804     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
01805       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
01806         return N1;
01807   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
01808   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
01809     SDValue N0Op0 = N0.getOperand(0);
01810     APInt Mask = ~N1C->getAPIntValue();
01811     Mask.trunc(N0Op0.getValueSizeInBits());
01812     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
01813       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
01814                                  N0.getValueType(), N0Op0);
01815       
01816       // Replace uses of the AND with uses of the Zero extend node.
01817       CombineTo(N, Zext);
01818       
01819       // We actually want to replace all uses of the any_extend with the
01820       // zero_extend, to avoid duplicating things.  This will later cause this
01821       // AND to be folded.
01822       CombineTo(N0.getNode(), Zext);
01823       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01824     }
01825   }
01826   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
01827   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
01828     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
01829     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
01830     
01831     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
01832         LL.getValueType().isInteger()) {
01833       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
01834       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
01835         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
01836                                      LR.getValueType(), LL, RL);
01837         AddToWorkList(ORNode.getNode());
01838         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
01839       }
01840       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
01841       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
01842         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
01843                                       LR.getValueType(), LL, RL);
01844         AddToWorkList(ANDNode.getNode());
01845         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
01846       }
01847       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
01848       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
01849         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
01850                                      LR.getValueType(), LL, RL);
01851         AddToWorkList(ORNode.getNode());
01852         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
01853       }
01854     }
01855     // canonicalize equivalent to ll == rl
01856     if (LL == RR && LR == RL) {
01857       Op1 = ISD::getSetCCSwappedOperands(Op1);
01858       std::swap(RL, RR);
01859     }
01860     if (LL == RL && LR == RR) {
01861       bool isInteger = LL.getValueType().isInteger();
01862       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
01863       if (Result != ISD::SETCC_INVALID &&
01864           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
01865         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
01866                             LL, LR, Result);
01867     }
01868   }
01869 
01870   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
01871   if (N0.getOpcode() == N1.getOpcode()) {
01872     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
01873     if (Tmp.getNode()) return Tmp;
01874   }
01875   
01876   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
01877   // fold (and (sra)) -> (and (srl)) when possible.
01878   if (!VT.isVector() &&
01879       SimplifyDemandedBits(SDValue(N, 0)))
01880     return SDValue(N, 0);
01881   // fold (zext_inreg (extload x)) -> (zextload x)
01882   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
01883     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01884     MVT EVT = LN0->getMemoryVT();
01885     // If we zero all the possible extended bits, then we can turn this into
01886     // a zextload if we are running before legalize or the operation is legal.
01887     unsigned BitWidth = N1.getValueSizeInBits();
01888     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
01889                                      BitWidth - EVT.getSizeInBits())) &&
01890         ((!LegalOperations && !LN0->isVolatile()) ||
01891          TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
01892       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
01893                                        LN0->getChain(), LN0->getBasePtr(),
01894                                        LN0->getSrcValue(),
01895                                        LN0->getSrcValueOffset(), EVT,
01896                                        LN0->isVolatile(), LN0->getAlignment());
01897       AddToWorkList(N);
01898       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
01899       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01900     }
01901   }
01902   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
01903   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
01904       N0.hasOneUse()) {
01905     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01906     MVT EVT = LN0->getMemoryVT();
01907     // If we zero all the possible extended bits, then we can turn this into
01908     // a zextload if we are running before legalize or the operation is legal.
01909     unsigned BitWidth = N1.getValueSizeInBits();
01910     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
01911                                      BitWidth - EVT.getSizeInBits())) &&
01912         ((!LegalOperations && !LN0->isVolatile()) ||
01913          TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
01914       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
01915                                        LN0->getChain(),
01916                                        LN0->getBasePtr(), LN0->getSrcValue(),
01917                                        LN0->getSrcValueOffset(), EVT,
01918                                        LN0->isVolatile(), LN0->getAlignment());
01919       AddToWorkList(N);
01920       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
01921       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01922     }
01923   }
01924   
01925   // fold (and (load x), 255) -> (zextload x, i8)
01926   // fold (and (extload x, i16), 255) -> (zextload x, i8)
01927   if (N1C && N0.getOpcode() == ISD::LOAD) {
01928     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
01929     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
01930         LN0->isUnindexed() && N0.hasOneUse() &&
01931         // Do not change the width of a volatile load.
01932         !LN0->isVolatile()) {
01933       MVT EVT = MVT::Other;
01934       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
01935       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue()))
01936         EVT = MVT::getIntegerVT(ActiveBits);
01937 
01938       MVT LoadedVT = LN0->getMemoryVT();
01939 
01940       // Do not generate loads of non-round integer types since these can
01941       // be expensive (and would be wrong if the type is not byte sized).
01942       if (EVT != MVT::Other && LoadedVT.bitsGT(EVT) && EVT.isRound() &&
01943           (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT))) {
01944         MVT PtrType = N0.getOperand(1).getValueType();
01945 
01946         // For big endian targets, we need to add an offset to the pointer to
01947         // load the correct bytes.  For little endian systems, we merely need to
01948         // read fewer bytes from the same pointer.
01949         unsigned LVTStoreBytes = LoadedVT.getStoreSizeInBits()/8;
01950         unsigned EVTStoreBytes = EVT.getStoreSizeInBits()/8;
01951         unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
01952         unsigned Alignment = LN0->getAlignment();
01953         SDValue NewPtr = LN0->getBasePtr();
01954 
01955         if (TLI.isBigEndian()) {
01956           NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
01957                                NewPtr, DAG.getConstant(PtrOff, PtrType));
01958           Alignment = MinAlign(Alignment, PtrOff);
01959         }
01960 
01961         AddToWorkList(NewPtr.getNode());
01962         SDValue Load =
01963           DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT, LN0->getChain(),
01964                          NewPtr, LN0->getSrcValue(), LN0->getSrcValueOffset(),
01965                          EVT, LN0->isVolatile(), Alignment);
01966         AddToWorkList(N);
01967         CombineTo(N0.getNode(), Load, Load.getValue(1));
01968         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01969       }
01970     }
01971   }
01972   
01973   return SDValue();
01974 }
01975 
01976 SDValue DAGCombiner::visitOR(SDNode *N) {
01977   SDValue N0 = N->getOperand(0);
01978   SDValue N1 = N->getOperand(1);
01979   SDValue LL, LR, RL, RR, CC0, CC1;
01980   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01981   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01982   MVT VT = N1.getValueType();
01983   
01984   // fold vector ops
01985   if (VT.isVector()) {
01986     SDValue FoldedVOp = SimplifyVBinOp(N);
01987     if (FoldedVOp.getNode()) return FoldedVOp;
01988   }
01989   
01990   // fold (or x, undef) -> -1
01991   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01992     return DAG.getConstant(~0ULL, VT);
01993   // fold (or c1, c2) -> c1|c2
01994   if (N0C && N1C)
01995     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
01996   // canonicalize constant to RHS
01997   if (N0C && !N1C)
01998     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
01999   // fold (or x, 0) -> x
02000   if (N1C && N1C->isNullValue())
02001     return N0;
02002   // fold (or x, -1) -> -1
02003   if (N1C && N1C->isAllOnesValue())
02004     return N1;
02005   // fold (or x, c) -> c iff (x & ~c) == 0
02006   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
02007     return N1;
02008   // reassociate or
02009   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
02010   if (ROR.getNode() != 0)
02011     return ROR;
02012   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
02013   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
02014              isa<ConstantSDNode>(N0.getOperand(1))) {
02015     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
02016     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
02017                        DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
02018                                    N0.getOperand(0), N1),
02019                        DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
02020   }
02021   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
02022   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
02023     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
02024     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
02025     
02026     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
02027         LL.getValueType().isInteger()) {
02028       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
02029       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
02030       if (cast<ConstantSDNode>(LR)->isNullValue() && 
02031           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
02032         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
02033                                      LR.getValueType(), LL, RL);
02034         AddToWorkList(ORNode.getNode());
02035         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
02036       }
02037       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
02038       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
02039       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && 
02040           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
02041         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
02042                                       LR.getValueType(), LL, RL);
02043         AddToWorkList(ANDNode.getNode());
02044         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
02045       }
02046     }
02047     // canonicalize equivalent to ll == rl
02048     if (LL == RR && LR == RL) {
02049       Op1 = ISD::getSetCCSwappedOperands(Op1);
02050       std::swap(RL, RR);
02051     }
02052     if (LL == RL && LR == RR) {
02053       bool isInteger = LL.getValueType().isInteger();
02054       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
02055       if (Result != ISD::SETCC_INVALID &&
02056           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
02057         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
02058                             LL, LR, Result);
02059     }
02060   }
02061   
02062   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
02063   if (N0.getOpcode() == N1.getOpcode()) {
02064     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
02065     if (Tmp.getNode()) return Tmp;
02066   }
02067   
02068   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
02069   if (N0.getOpcode() == ISD::AND &&
02070       N1.getOpcode() == ISD::AND &&
02071       N0.getOperand(1).getOpcode() == ISD::Constant &&
02072       N1.getOperand(1).getOpcode() == ISD::Constant &&
02073       // Don't increase # computations.
02074       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
02075     // We can only do this xform if we know that bits from X that are set in C2
02076     // but not in C1 are already zero.  Likewise for Y.
02077     const APInt &LHSMask =
02078       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
02079     const APInt &RHSMask =
02080       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
02081     
02082     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
02083         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
02084       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
02085                               N0.getOperand(0), N1.getOperand(0));
02086       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
02087                          DAG.getConstant(LHSMask | RHSMask, VT));
02088     }
02089   }
02090   
02091   // See if this is some rotate idiom.
02092   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
02093     return SDValue(Rot, 0);
02094 
02095   return SDValue();
02096 }
02097 
02098 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
02099 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
02100   if (Op.getOpcode() == ISD::AND) {
02101     if (isa<ConstantSDNode>(Op.getOperand(1))) {
02102       Mask = Op.getOperand(1);
02103       Op = Op.getOperand(0);
02104     } else {
02105       return false;
02106     }
02107   }
02108   
02109   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
02110     Shift = Op;
02111     return true;
02112   }
02113 
02114   return false;  
02115 }
02116 
02117 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
02118 // idioms for rotate, and if the target supports rotation instructions, generate
02119 // a rot[lr].
02120 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
02121   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
02122   MVT VT = LHS.getValueType();
02123   if (!TLI.isTypeLegal(VT)) return 0;
02124 
02125   // The target must have at least one rotate flavor.
02126   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
02127   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
02128   if (!HasROTL && !HasROTR) return 0;
02129 
02130   // Match "(X shl/srl V1) & V2" where V2 may not be present.
02131   SDValue LHSShift;   // The shift.
02132   SDValue LHSMask;    // AND value if any.
02133   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
02134     return 0; // Not part of a rotate.
02135 
02136   SDValue RHSShift;   // The shift.
02137   SDValue RHSMask;    // AND value if any.
02138   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
02139     return 0; // Not part of a rotate.
02140   
02141   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
02142     return 0;   // Not shifting the same value.
02143 
02144   if (LHSShift.getOpcode() == RHSShift.getOpcode())
02145     return 0;   // Shifts must disagree.
02146     
02147   // Canonicalize shl to left side in a shl/srl pair.
02148   if (RHSShift.getOpcode() == ISD::SHL) {
02149     std::swap(LHS, RHS);
02150     std::swap(LHSShift, RHSShift);
02151     std::swap(LHSMask , RHSMask );
02152   }
02153 
02154   unsigned OpSizeInBits = VT.getSizeInBits();
02155   SDValue LHSShiftArg = LHSShift.getOperand(0);
02156   SDValue LHSShiftAmt = LHSShift.getOperand(1);
02157   SDValue RHSShiftAmt = RHSShift.getOperand(1);
02158 
02159   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
02160   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
02161   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
02162       RHSShiftAmt.getOpcode() == ISD::Constant) {
02163     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
02164     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
02165     if ((LShVal + RShVal) != OpSizeInBits)
02166       return 0;
02167 
02168     SDValue Rot;
02169     if (HasROTL)
02170       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
02171     else
02172       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
02173     
02174     // If there is an AND of either shifted operand, apply it to the result.
02175     if (LHSMask.getNode() || RHSMask.getNode()) {
02176       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
02177       
02178       if (LHSMask.getNode()) {
02179         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
02180         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
02181       }
02182       if (RHSMask.getNode()) {
02183         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
02184         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
02185       }
02186         
02187       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
02188     }
02189     
02190     return Rot.getNode();
02191   }
02192   
02193   // If there is a mask here, and we have a variable shift, we can't be sure
02194   // that we're masking out the right stuff.
02195   if (LHSMask.getNode() || RHSMask.getNode())
02196     return 0;
02197   
02198   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
02199   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
02200   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
02201       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
02202     if (ConstantSDNode *SUBC = 
02203           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
02204       if (SUBC->getAPIntValue() == OpSizeInBits) {
02205         if (HasROTL)
02206           return DAG.getNode(ISD::ROTL, DL, VT,
02207                              LHSShiftArg, LHSShiftAmt).getNode();
02208         else
02209           return DAG.getNode(ISD::ROTR, DL, VT,
02210                              LHSShiftArg, RHSShiftAmt).getNode();
02211       }
02212     }
02213   }
02214   
02215   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
02216   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
02217   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
02218       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
02219     if (ConstantSDNode *SUBC = 
02220           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
02221       if (SUBC->getAPIntValue() == OpSizeInBits) {
02222         if (HasROTR)
02223           return DAG.getNode(ISD::ROTR, DL, VT,
02224                              LHSShiftArg, RHSShiftAmt).getNode();
02225         else
02226           return DAG.getNode(ISD::ROTL, DL, VT,
02227                              LHSShiftArg, LHSShiftAmt).getNode();
02228       }
02229     }
02230   }
02231 
02232   // Look for sign/zext/any-extended or truncate cases:
02233   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
02234        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
02235        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
02236        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
02237       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
02238        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
02239        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
02240        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
02241     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
02242     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
02243     if (RExtOp0.getOpcode() == ISD::SUB &&
02244         RExtOp0.getOperand(1) == LExtOp0) {
02245       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
02246       //   (rotl x, y)
02247       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
02248       //   (rotr x, (sub 32, y))
02249       if (ConstantSDNode *SUBC =
02250             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
02251         if (SUBC->getAPIntValue() == OpSizeInBits) {
02252           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
02253                              LHSShiftArg,
02254                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
02255         }
02256       }
02257     } else if (LExtOp0.getOpcode() == ISD::SUB &&
02258                RExtOp0 == LExtOp0.getOperand(1)) {
02259       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) -> 
02260       //   (rotr x, y)
02261       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
02262       //   (rotl x, (sub 32, y))
02263       if (ConstantSDNode *SUBC =
02264             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
02265         if (SUBC->getAPIntValue() == OpSizeInBits) {
02266           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
02267                              LHSShiftArg,
02268                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
02269         }
02270       }
02271     }
02272   }
02273   
02274   return 0;
02275 }
02276 
02277 SDValue DAGCombiner::visitXOR(SDNode *N) {
02278   SDValue N0 = N->getOperand(0);
02279   SDValue N1 = N->getOperand(1);
02280   SDValue LHS, RHS, CC;
02281   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02282   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02283   MVT VT = N0.getValueType();
02284   
02285   // fold vector ops
02286   if (VT.isVector()) {
02287     SDValue FoldedVOp = SimplifyVBinOp(N);
02288     if (FoldedVOp.getNode()) return FoldedVOp;
02289   }
02290   
02291   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
02292   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
02293     return DAG.getConstant(0, VT);
02294   // fold (xor x, undef) -> undef
02295   if (N0.getOpcode() == ISD::UNDEF)
02296     return N0;
02297   if (N1.getOpcode() == ISD::UNDEF)
02298     return N1;
02299   // fold (xor c1, c2) -> c1^c2
02300   if (N0C && N1C)
02301     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
02302   // canonicalize constant to RHS
02303   if (N0C && !N1C)
02304     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
02305   // fold (xor x, 0) -> x
02306   if (N1C && N1C->isNullValue())
02307     return N0;
02308   // reassociate xor
02309   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
02310   if (RXOR.getNode() != 0)
02311     return RXOR;
02312 
02313   // fold !(x cc y) -> (x !cc y)
02314   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
02315     bool isInt = LHS.getValueType().isInteger();
02316     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
02317                                                isInt);
02318 
02319     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
02320       switch (N0.getOpcode()) {
02321       default:
02322         assert(0 && "Unhandled SetCC Equivalent!");
02323         abort();
02324       case ISD::SETCC:
02325         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
02326       case ISD::SELECT_CC:
02327         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
02328                                N0.getOperand(3), NotCC);
02329       }
02330     }
02331   }
02332 
02333   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
02334   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
02335       N0.getNode()->hasOneUse() &&
02336       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
02337     SDValue V = N0.getOperand(0);
02338     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V, 
02339                     DAG.getConstant(1, V.getValueType()));
02340     AddToWorkList(V.getNode());
02341     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
02342   }
02343   
02344   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
02345   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
02346       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
02347     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
02348     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
02349       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
02350       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
02351       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
02352       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
02353       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
02354     }
02355   }
02356   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
02357   if (N1C && N1C->isAllOnesValue() && 
02358       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
02359     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
02360     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
02361       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
02362       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
02363       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
02364       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
02365       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
02366     }
02367   }
02368   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
02369   if (N1C && N0.getOpcode() == ISD::XOR) {
02370     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
02371     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02372     if (N00C)
02373       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
02374                          DAG.getConstant(N1C->getAPIntValue() ^
02375                                          N00C->getAPIntValue(), VT));
02376     if (N01C)
02377       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
02378                          DAG.getConstant(N1C->getAPIntValue() ^
02379                                          N01C->getAPIntValue(), VT));
02380   }
02381   // fold (xor x, x) -> 0
02382   if (N0 == N1) {
02383     if (!VT.isVector()) {
02384       return DAG.getConstant(0, VT);
02385     } else if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)){
02386       // Produce a vector of zeros.
02387       SDValue El = DAG.getConstant(0, VT.getVectorElementType());
02388       std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
02389       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
02390                          &Ops[0], Ops.size());
02391     }
02392   }
02393   
02394   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
02395   if (N0.getOpcode() == N1.getOpcode()) {
02396     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
02397     if (Tmp.getNode()) return Tmp;
02398   }
02399   
02400   // Simplify the expression using non-local knowledge.
02401   if (!VT.isVector() &&
02402       SimplifyDemandedBits(SDValue(N, 0)))
02403     return SDValue(N, 0);
02404   
02405   return SDValue();
02406 }
02407 
02408 /// visitShiftByConstant - Handle transforms common to the three shifts, when
02409 /// the shift amount is a constant.
02410 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
02411   SDNode *LHS = N->getOperand(0).getNode();
02412   if (!LHS->hasOneUse()) return SDValue();
02413   
02414   // We want to pull some binops through shifts, so that we have (and (shift))
02415   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
02416   // thing happens with address calculations, so it's important to canonicalize
02417   // it.
02418   bool HighBitSet = false;  // Can we transform this if the high bit is set?
02419   
02420   switch (LHS->getOpcode()) {
02421   default: return SDValue();
02422   case ISD::OR:
02423   case ISD::XOR:
02424     HighBitSet = false; // We can only transform sra if the high bit is clear.
02425     break;
02426   case ISD::AND:
02427     HighBitSet = true;  // We can only transform sra if the high bit is set.
02428     break;
02429   case ISD::ADD:
02430     if (N->getOpcode() != ISD::SHL) 
02431       return SDValue(); // only shl(add) not sr[al](add).
02432     HighBitSet = false; // We can only transform sra if the high bit is clear.
02433     break;
02434   }
02435   
02436   // We require the RHS of the binop to be a constant as well.
02437   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
02438   if (!BinOpCst) return SDValue();
02439 
02440   // FIXME: disable this unless the input to the binop is a shift by a constant.
02441   // If it is not a shift, it pessimizes some common cases like:
02442   //
02443   //    void foo(int *X, int i) { X[i & 1235] = 1; }
02444   //    int bar(int *X, int i) { return X[i & 255]; }
02445   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
02446   if ((BinOpLHSVal->getOpcode() != ISD::SHL && 
02447        BinOpLHSVal->getOpcode() != ISD::SRA &&
02448        BinOpLHSVal->getOpcode() != ISD::SRL) ||
02449       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
02450     return SDValue();
02451   
02452   MVT VT = N->getValueType(0);
02453   
02454   // If this is a signed shift right, and the high bit is modified by the
02455   // logical operation, do not perform the transformation. The highBitSet
02456   // boolean indicates the value of the high bit of the constant which would
02457   // cause it to be modified for this operation.
02458   if (N->getOpcode() == ISD::SRA) {
02459     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
02460     if (BinOpRHSSignSet != HighBitSet)
02461       return SDValue();
02462   }
02463   
02464   // Fold the constants, shifting the binop RHS by the shift amount.
02465   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
02466                                N->getValueType(0),
02467                                LHS->getOperand(1), N->getOperand(1));
02468 
02469   // Create the new shift.
02470   SDValue NewShift = DAG.getNode(N->getOpcode(), LHS->getOperand(0).getDebugLoc(),
02471                                  VT, LHS->getOperand(0), N->getOperand(1));
02472 
02473   // Create the new binop.
02474   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
02475 }
02476 
02477 SDValue DAGCombiner::visitSHL(SDNode *N) {
02478   SDValue N0 = N->getOperand(0);
02479   SDValue N1 = N->getOperand(1);
02480   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02481   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02482   MVT VT = N0.getValueType();
02483   unsigned OpSizeInBits = VT.getSizeInBits();
02484   
02485   // fold (shl c1, c2) -> c1<<c2
02486   if (N0C && N1C)
02487     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
02488   // fold (shl 0, x) -> 0
02489   if (N0C && N0C->isNullValue())
02490     return N0;
02491   // fold (shl x, c >= size(x)) -> undef
02492   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
02493     return DAG.getNode(ISD::UNDEF, N->getDebugLoc(), VT);
02494   // fold (shl x, 0) -> x
02495   if (N1C && N1C->isNullValue())
02496     return N0;
02497   // if (shl x, c) is known to be zero, return 0
02498   if (DAG.MaskedValueIsZero(SDValue(N, 0),
02499                             APInt::getAllOnesValue(VT.getSizeInBits())))
02500     return DAG.getConstant(0, VT);
02501   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
02502   if (N1.getOpcode() == ISD::TRUNCATE &&
02503       N1.getOperand(0).getOpcode() == ISD::AND &&
02504       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02505     SDValue N101 = N1.getOperand(0).getOperand(1);
02506     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02507       MVT TruncVT = N1.getValueType();
02508       SDValue N100 = N1.getOperand(0).getOperand(0);
02509       APInt TruncC = N101C->getAPIntValue();
02510       TruncC.trunc(TruncVT.getSizeInBits());
02511       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
02512                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
02513                                      DAG.getNode(ISD::TRUNCATE,
02514                                                  N->getDebugLoc(),
02515                                                  TruncVT, N100),
02516                                      DAG.getConstant(TruncC, TruncVT)));
02517     }
02518   }
02519 
02520   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02521     return SDValue(N, 0);
02522 
02523   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
02524   if (N1C && N0.getOpcode() == ISD::SHL && 
02525       N0.getOperand(1).getOpcode() == ISD::Constant) {
02526     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02527     uint64_t c2 = N1C->getZExtValue();
02528     if (c1 + c2 > OpSizeInBits)
02529       return DAG.getConstant(0, VT);
02530     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
02531                        DAG.getConstant(c1 + c2, N1.getValueType()));
02532   }
02533   // fold (shl (srl x, c1), c2) -> (shl (and x, (shl -1, c1)), (sub c2, c1)) or
02534   //                               (srl (and x, (shl -1, c1)), (sub c1, c2))
02535   if (N1C && N0.getOpcode() == ISD::SRL && 
02536       N0.getOperand(1).getOpcode() == ISD::Constant) {
02537     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02538     uint64_t c2 = N1C->getZExtValue();
02539     SDValue Mask = DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, N0.getOperand(0),
02540                                DAG.getConstant(~0ULL << c1, VT));
02541     if (c2 > c1)
02542       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, Mask,
02543                          DAG.getConstant(c2-c1, N1.getValueType()));
02544     else
02545       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Mask,
02546                          DAG.getConstant(c1-c2, N1.getValueType()));
02547   }
02548   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
02549   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1))
02550     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
02551                        DAG.getConstant(~0ULL << N1C->getZExtValue(), VT));
02552   
02553   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02554 }
02555 
02556 SDValue DAGCombiner::visitSRA(SDNode *N) {
02557   SDValue N0 = N->getOperand(0);
02558   SDValue N1 = N->getOperand(1);
02559   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02560   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02561   MVT VT = N0.getValueType();
02562   
02563   // fold (sra c1, c2) -> (sra c1, c2)
02564   if (N0C && N1C)
02565     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
02566   // fold (sra 0, x) -> 0
02567   if (N0C && N0C->isNullValue())
02568     return N0;
02569   // fold (sra -1, x) -> -1
02570   if (N0C && N0C->isAllOnesValue())
02571     return N0;
02572   // fold (sra x, (setge c, size(x))) -> undef
02573   if (N1C && N1C->getZExtValue() >= VT.getSizeInBits())
02574     return DAG.getNode(ISD::UNDEF, N->getDebugLoc(), VT);
02575   // fold (sra x, 0) -> x
02576   if (N1C && N1C->isNullValue())
02577     return N0;
02578   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
02579   // sext_inreg.
02580   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
02581     unsigned LowBits = VT.getSizeInBits() - (unsigned)N1C->getZExtValue();
02582     MVT EVT = MVT::getIntegerVT(LowBits);
02583     if ((!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, EVT)))
02584       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
02585                          N0.getOperand(0), DAG.getValueType(EVT));
02586   }
02587 
02588   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
02589   if (N1C && N0.getOpcode() == ISD::SRA) {
02590     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
02591       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
02592       if (Sum >= VT.getSizeInBits()) Sum = VT.getSizeInBits()-1;
02593       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
02594                          DAG.getConstant(Sum, N1C->getValueType(0)));
02595     }
02596   }
02597 
02598   // fold (sra (shl X, m), (sub result_size, n))
02599   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
02600   // result_size - n != m. 
02601   // If truncate is free for the target sext(shl) is likely to result in better 
02602   // code.
02603   if (N0.getOpcode() == ISD::SHL) {
02604     // Get the two constanst of the shifts, CN0 = m, CN = n.
02605     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
02606     if (N01C && N1C) {
02607       // Determine what the truncate's result bitsize and type would be.
02608       unsigned VTValSize = VT.getSizeInBits();
02609       MVT TruncVT =
02610         MVT::getIntegerVT(VTValSize - N1C->getZExtValue());
02611       // Determine the residual right-shift amount.
02612       unsigned ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
02613 
02614       // If the shift is not a no-op (in which case this should be just a sign 
02615       // extend already), the truncated to type is legal, sign_extend is legal 
02616       // on that type, and the the truncate to that type is both legal and free,
02617       // perform the transform.
02618       if (ShiftAmt &&
02619           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
02620           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
02621           TLI.isTruncateFree(VT, TruncVT)) {
02622 
02623           SDValue Amt = DAG.getConstant(ShiftAmt, getShiftAmountTy());
02624           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
02625                                       N0.getOperand(0), Amt);
02626           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
02627                                       Shift);
02628           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
02629                              N->getValueType(0), Trunc);
02630       }
02631     }
02632   }
02633   
02634   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
02635   if (N1.getOpcode() == ISD::TRUNCATE &&
02636       N1.getOperand(0).getOpcode() == ISD::AND &&
02637       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02638     SDValue N101 = N1.getOperand(0).getOperand(1);
02639     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02640       MVT TruncVT = N1.getValueType();
02641       SDValue N100 = N1.getOperand(0).getOperand(0);
02642       APInt TruncC = N101C->getAPIntValue();
02643       TruncC.trunc(TruncVT.getSizeInBits());
02644       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
02645                          DAG.getNode(ISD::AND, N->getDebugLoc(),
02646                                      TruncVT,
02647                                      DAG.getNode(ISD::TRUNCATE,
02648                                                  N->getDebugLoc(),
02649                                                  TruncVT, N100),
02650                                      DAG.getConstant(TruncC, TruncVT)));
02651     }
02652   }
02653 
02654   // Simplify, based on bits shifted out of the LHS. 
02655   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02656     return SDValue(N, 0);
02657   
02658   
02659   // If the sign bit is known to be zero, switch this to a SRL.
02660   if (DAG.SignBitIsZero(N0))
02661     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
02662 
02663   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02664 }
02665 
02666 SDValue DAGCombiner::visitSRL(SDNode *N) {
02667   SDValue N0 = N->getOperand(0);
02668   SDValue N1 = N->getOperand(1);
02669   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02670   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02671   MVT VT = N0.getValueType();
02672   unsigned OpSizeInBits = VT.getSizeInBits();
02673   
02674   // fold (srl c1, c2) -> c1 >>u c2
02675   if (N0C && N1C)
02676     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
02677   // fold (srl 0, x) -> 0
02678   if (N0C && N0C->isNullValue())
02679     return N0;
02680   // fold (srl x, c >= size(x)) -> undef
02681   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
02682     return DAG.getNode(ISD::UNDEF, N->getDebugLoc(), VT);
02683   // fold (srl x, 0) -> x
02684   if (N1C && N1C->isNullValue())
02685     return N0;
02686   // if (srl x, c) is known to be zero, return 0
02687   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
02688                                    APInt::getAllOnesValue(OpSizeInBits)))
02689     return DAG.getConstant(0, VT);
02690   
02691   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
02692   if (N1C && N0.getOpcode() == ISD::SRL && 
02693       N0.getOperand(1).getOpcode() == ISD::Constant) {
02694     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
02695     uint64_t c2 = N1C->getZExtValue();
02696     if (c1 + c2 > OpSizeInBits)
02697       return DAG.getConstant(0, VT);
02698     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
02699                        DAG.getConstant(c1 + c2, N1.getValueType()));
02700   }
02701   
02702   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
02703   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
02704     // Shifting in all undef bits?
02705     MVT SmallVT = N0.getOperand(0).getValueType();
02706     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
02707       return DAG.getNode(ISD::UNDEF, N->getDebugLoc(), VT);
02708 
02709     SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
02710                                      N0.getOperand(0), N1);
02711     AddToWorkList(SmallShift.getNode());
02712     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
02713   }
02714   
02715   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
02716   // bit, which is unmodified by sra.
02717   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
02718     if (N0.getOpcode() == ISD::SRA)
02719       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
02720   }
02721   
02722   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
02723   if (N1C && N0.getOpcode() == ISD::CTLZ && 
02724       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
02725     APInt KnownZero, KnownOne;
02726     APInt Mask = APInt::getAllOnesValue(VT.getSizeInBits());
02727     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
02728     
02729     // If any of the input bits are KnownOne, then the input couldn't be all
02730     // zeros, thus the result of the srl will always be zero.
02731     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
02732     
02733     // If all of the bits input the to ctlz node are known to be zero, then
02734     // the result of the ctlz is "32" and the result of the shift is one.
02735     APInt UnknownBits = ~KnownZero & Mask;
02736     if (UnknownBits == 0) return DAG.getConstant(1, VT);
02737     
02738     // Otherwise, check to see if there is exactly one bit input to the ctlz.
02739     if ((UnknownBits & (UnknownBits - 1)) == 0) {
02740       // Okay, we know that only that the single bit specified by UnknownBits
02741       // could be set on input to the CTLZ node. If this bit is set, the SRL
02742       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
02743       // to an SRL/XOR pair, which is likely to simplify more.
02744       unsigned ShAmt = UnknownBits.countTrailingZeros();
02745       SDValue Op = N0.getOperand(0);
02746 
02747       if (ShAmt) {
02748         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
02749                          DAG.getConstant(ShAmt, getShiftAmountTy()));
02750         AddToWorkList(Op.getNode());
02751       }
02752 
02753       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
02754                          Op, DAG.getConstant(1, VT));
02755     }
02756   }
02757 
02758   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
02759   if (N1.getOpcode() == ISD::TRUNCATE &&
02760       N1.getOperand(0).getOpcode() == ISD::AND &&
02761       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
02762     SDValue N101 = N1.getOperand(0).getOperand(1);
02763     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
02764       MVT TruncVT = N1.getValueType();
02765       SDValue N100 = N1.getOperand(0).getOperand(0);
02766       APInt TruncC = N101C->getAPIntValue();
02767       TruncC.trunc(TruncVT.getSizeInBits());
02768       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
02769                          DAG.getNode(ISD::AND, N->getDebugLoc(),
02770                                      TruncVT,
02771                                      DAG.getNode(ISD::TRUNCATE,
02772                                                  N->getDebugLoc(),
02773                                                  TruncVT, N100),
02774                                      DAG.getConstant(TruncC, TruncVT)));
02775     }
02776   }
02777   
02778   // fold operands of srl based on knowledge that the low bits are not
02779   // demanded.
02780   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
02781     return SDValue(N, 0);
02782   
02783   return N1C ? visitShiftByConstant(N, N1C->getZExtValue()) : SDValue();
02784 }
02785 
02786 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
02787   SDValue N0 = N->getOperand(0);
02788   MVT VT = N->getValueType(0);
02789 
02790   // fold (ctlz c1) -> c2
02791   if (isa<ConstantSDNode>(N0))
02792     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
02793   return SDValue();
02794 }
02795 
02796 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
02797   SDValue N0 = N->getOperand(0);
02798   MVT VT = N->getValueType(0);
02799   
02800   // fold (cttz c1) -> c2
02801   if (isa<ConstantSDNode>(N0))
02802     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
02803   return SDValue();
02804 }
02805 
02806 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
02807   SDValue N0 = N->getOperand(0);
02808   MVT VT = N->getValueType(0);
02809   
02810   // fold (ctpop c1) -> c2
02811   if (isa<ConstantSDNode>(N0))
02812     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
02813   return SDValue();
02814 }
02815 
02816 SDValue DAGCombiner::visitSELECT(SDNode *N) {
02817   SDValue N0 = N->getOperand(0);
02818   SDValue N1 = N->getOperand(1);
02819   SDValue N2 = N->getOperand(2);
02820   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02821   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02822   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
02823   MVT VT = N->getValueType(0);
02824   MVT VT0 = N0.getValueType();
02825 
02826   // fold (select C, X, X) -> X
02827   if (N1 == N2)
02828     return N1;
02829   // fold (select true, X, Y) -> X
02830   if (N0C && !N0C->isNullValue())
02831     return N1;
02832   // fold (select false, X, Y) -> Y
02833   if (N0C && N0C->isNullValue())
02834     return N2;
02835   // fold (select C, 1, X) -> (or C, X)
02836   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
02837     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
02838   // fold (select C, 0, 1) -> (xor C, 1)
02839   if (VT.isInteger() &&
02840       (VT0 == MVT::i1 ||
02841        (VT0.isInteger() &&
02842         TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent)) &&
02843       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
02844     SDValue XORNode;
02845     if (VT == VT0)
02846       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
02847                          N0, DAG.getConstant(1, VT0));
02848     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
02849                           N0, DAG.getConstant(1, VT0));
02850     AddToWorkList(XORNode.getNode());
02851     if (VT.bitsGT(VT0))
02852       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
02853     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
02854   }
02855   // fold (select C, 0, X) -> (and (not C), X)
02856   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
02857     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
02858     AddToWorkList(NOTNode.getNode());
02859     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
02860   }
02861   // fold (select C, X, 1) -> (or (not C), X)
02862   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
02863     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
02864     AddToWorkList(NOTNode.getNode());
02865     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
02866   }
02867   // fold (select C, X, 0) -> (and C, X)
02868   if (VT == MVT::i1 && N2C && N2C->isNullValue())
02869     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
02870   // fold (select X, X, Y) -> (or X, Y)
02871   // fold (select X, 1, Y) -> (or X, Y)
02872   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
02873     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
02874   // fold (select X, Y, X) -> (and X, Y)
02875   // fold (select X, Y, 0) -> (and X, Y)
02876   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
02877     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
02878   
02879   // If we can fold this based on the true/false value, do so.
02880   if (SimplifySelectOps(N, N1, N2))
02881     return SDValue(N, 0);  // Don't revisit N.
02882 
02883   // fold selects based on a setcc into other things, such as min/max/abs
02884   if (N0.getOpcode() == ISD::SETCC) {
02885     // FIXME:
02886     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
02887     // having to say they don't support SELECT_CC on every type the DAG knows
02888     // about, since there is no way to mark an opcode illegal at all value types
02889     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other))
02890       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
02891                          N0.getOperand(0), N0.getOperand(1),
02892                          N1, N2, N0.getOperand(2));
02893     else
02894       return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
02895   }
02896 
02897   return SDValue();
02898 }
02899 
02900 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
02901   SDValue N0 = N->getOperand(0);
02902   SDValue N1 = N->getOperand(1);
02903   SDValue N2 = N->getOperand(2);
02904   SDValue N3 = N->getOperand(3);
02905   SDValue N4 = N->getOperand(4);
02906   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
02907   
02908   // fold select_cc lhs, rhs, x, x, cc -> x
02909   if (N2 == N3)
02910     return N2;
02911   
02912   // Determine if the condition we're dealing with is constant
02913   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
02914                               N0, N1, CC, N->getDebugLoc(), false);
02915   if (SCC.getNode()) AddToWorkList(SCC.getNode());
02916 
02917   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
02918     if (!SCCC->isNullValue())
02919       return N2;    // cond always true -> true val
02920     else
02921       return N3;    // cond always false -> false val
02922   }
02923   
02924   // Fold to a simpler select_cc
02925   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
02926     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(), 
02927                        SCC.getOperand(0), SCC.getOperand(1), N2, N3, 
02928                        SCC.getOperand(2));
02929   
02930   // If we can fold this based on the true/false value, do so.
02931   if (SimplifySelectOps(N, N2, N3))
02932     return SDValue(N, 0);  // Don't revisit N.
02933   
02934   // fold select_cc into other things, such as min/max/abs
02935   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
02936 }
02937 
02938 SDValue DAGCombiner::visitSETCC(SDNode *N) {
02939   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
02940                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
02941                        N->getDebugLoc());
02942 }
02943 
02944 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
02945 // "fold ({s|z}ext (load x)) -> ({s|z}ext (truncate ({s|z}extload x)))"
02946 // transformation. Returns true if extension are possible and the above
02947 // mentioned transformation is profitable. 
02948 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
02949                                     unsigned ExtOpc,
02950                                     SmallVector<SDNode*, 4> &ExtendNodes,
02951                                     const TargetLowering &TLI) {
02952   bool HasCopyToRegUses = false;
02953   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
02954   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
02955                             UE = N0.getNode()->use_end();
02956        UI != UE; ++UI) {
02957     SDNode *User = *UI;
02958     if (User == N)
02959       continue;
02960     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
02961     if (User->getOpcode() == ISD::SETCC) {
02962       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
02963       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
02964         // Sign bits will be lost after a zext.
02965         return false;
02966       bool Add = false;
02967       for (unsigned i = 0; i != 2; ++i) {
02968         SDValue UseOp = User->getOperand(i);
02969         if (UseOp == N0)
02970           continue;
02971         if (!isa<ConstantSDNode>(UseOp))
02972           return false;
02973         Add = true;
02974       }
02975       if (Add)
02976         ExtendNodes.push_back(User);
02977     } else {
02978       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
02979         SDValue UseOp = User->getOperand(i);
02980         if (UseOp == N0) {
02981           // If truncate from extended type to original load type is free
02982           // on this target, then it's ok to extend a CopyToReg.
02983           if (isTruncFree && User->getOpcode() == ISD::CopyToReg)
02984             HasCopyToRegUses = true;
02985           else
02986             return false;
02987         }
02988       }
02989     }
02990   }
02991 
02992   if (HasCopyToRegUses) {
02993     bool BothLiveOut = false;
02994     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
02995          UI != UE; ++UI) {
02996       SDNode *User = *UI;
02997       for (unsigned i = 0, e = User->getNumOperands(); i != e; ++i) {
02998         SDValue UseOp = User->getOperand(i);
02999         if (UseOp.getNode() == N && UseOp.getResNo() == 0) {
03000           BothLiveOut = true;
03001           break;
03002         }
03003       }
03004     }
03005     if (BothLiveOut)
03006       // Both unextended and extended values are live out. There had better be
03007       // good a reason for the transformation.
03008       return ExtendNodes.size();
03009   }
03010   return true;
03011 }
03012 
03013 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
03014   SDValue N0 = N->getOperand(0);
03015   MVT VT = N->getValueType(0);
03016 
03017   // fold (sext c1) -> c1
03018   if (isa<ConstantSDNode>(N0))
03019     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
03020   
03021   // fold (sext (sext x)) -> (sext x)
03022   // fold (sext (aext x)) -> (sext x)
03023   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
03024     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
03025                        N0.getOperand(0));
03026   
03027   if (N0.getOpcode() == ISD::TRUNCATE) {
03028     // fold (sext (truncate (load x))) -> (sext (smaller load x))
03029     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
03030     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
03031     if (NarrowLoad.getNode()) {
03032       if (NarrowLoad.getNode() != N0.getNode())
03033         CombineTo(N0.getNode(), NarrowLoad);
03034       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
03035     }
03036 
03037     // See if the value being truncated is already sign extended.  If so, just
03038     // eliminate the trunc/sext pair.
03039     SDValue Op = N0.getOperand(0);
03040     unsigned OpBits   = Op.getValueType().getSizeInBits();
03041     unsigned MidBits  = N0.getValueType().getSizeInBits();
03042     unsigned DestBits = VT.getSizeInBits();
03043     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
03044     
03045     if (OpBits == DestBits) {
03046       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
03047       // bits, it is already ready.
03048       if (NumSignBits > DestBits-MidBits)
03049         return Op;
03050     } else if (OpBits < DestBits) {
03051       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
03052       // bits, just sext from i32.
03053       if (NumSignBits > OpBits-MidBits)
03054         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
03055     } else {
03056       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
03057       // bits, just truncate to i32.
03058       if (NumSignBits > OpBits-MidBits)
03059         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
03060     }
03061     
03062     // fold (sext (truncate x)) -> (sextinreg x).
03063     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
03064                                                  N0.getValueType())) {
03065       if (Op.getValueType().bitsLT(VT))
03066         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
03067       else if (Op.getValueType().bitsGT(VT))
03068         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
03069       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
03070                          DAG.getValueType(N0.getValueType()));
03071     }
03072   }
03073   
03074   // fold (sext (load x)) -> (sext (truncate (sextload x)))
03075   if (ISD::isNON_EXTLoad(N0.getNode()) &&
03076       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03077        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
03078     bool DoXform = true;
03079     SmallVector<SDNode*, 4> SetCCs;
03080     if (!N0.hasOneUse())
03081       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
03082     if (DoXform) {
03083       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03084       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(),
03085                                        VT, LN0->getChain(),
03086                                        LN0->getBasePtr(), LN0->getSrcValue(),
03087                                        LN0->getSrcValueOffset(),
03088                                        N0.getValueType(),
03089                                        LN0->isVolatile(), LN0->getAlignment());
03090       CombineTo(N, ExtLoad);
03091       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03092                                   N0.getValueType(), ExtLoad);
03093       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
03094 
03095       // Extend SetCC uses if necessary.
03096       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
03097         SDNode *SetCC = SetCCs[i];
03098         SmallVector<SDValue, 4> Ops;
03099 
03100         for (unsigned j = 0; j != 2; ++j) {
03101           SDValue SOp = SetCC->getOperand(j);
03102           if (SOp == Trunc)
03103             Ops.push_back(ExtLoad);
03104           else
03105             Ops.push_back(DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
03106                                       VT, SOp));
03107         }
03108 
03109         Ops.push_back(SetCC->getOperand(2));
03110         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
03111                                      SetCC->getValueType(0),
03112                                      &Ops[0], Ops.size()));
03113       }
03114 
03115       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03116     }
03117   }
03118 
03119   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
03120   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
03121   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
03122       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
03123     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03124     MVT EVT = LN0->getMemoryVT();
03125     if ((!LegalOperations && !LN0->isVolatile()) ||
03126         TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT)) {
03127       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03128                                        LN0->getChain(),
03129                                        LN0->getBasePtr(), LN0->getSrcValue(),
03130                                        LN0->getSrcValueOffset(), EVT,
03131                                        LN0->isVolatile(), LN0->getAlignment());
03132       CombineTo(N, ExtLoad);
03133       CombineTo(N0.getNode(),
03134                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03135                             N0.getValueType(), ExtLoad),
03136                 ExtLoad.getValue(1));
03137       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03138     }
03139   }
03140   
03141   // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
03142   if (N0.getOpcode() == ISD::SETCC) {
03143     SDValue SCC = 
03144       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03145                        DAG.getConstant(~0ULL, VT), DAG.getConstant(0, VT),
03146                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03147     if (SCC.getNode()) return SCC;
03148   }
03149   
03150   // fold (sext x) -> (zext x) if the sign bit is known zero.
03151   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
03152       DAG.SignBitIsZero(N0))
03153     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
03154   
03155   return SDValue();
03156 }
03157 
03158 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
03159   SDValue N0 = N->getOperand(0);
03160   MVT VT = N->getValueType(0);
03161 
03162   // fold (zext c1) -> c1
03163   if (isa<ConstantSDNode>(N0))
03164     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
03165   // fold (zext (zext x)) -> (zext x)
03166   // fold (zext (aext x)) -> (zext x)
03167   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
03168     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
03169                        N0.getOperand(0));
03170 
03171   // fold (zext (truncate (load x))) -> (zext (smaller load x))
03172   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
03173   if (N0.getOpcode() == ISD::TRUNCATE) {
03174     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
03175     if (NarrowLoad.getNode()) {
03176       if (NarrowLoad.getNode() != N0.getNode())
03177         CombineTo(N0.getNode(), NarrowLoad);
03178       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
03179     }
03180   }
03181 
03182   // fold (zext (truncate x)) -> (and x, mask)
03183   if (N0.getOpcode() == ISD::TRUNCATE &&
03184       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
03185     SDValue Op = N0.getOperand(0);
03186     if (Op.getValueType().bitsLT(VT)) {
03187       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
03188     } else if (Op.getValueType().bitsGT(VT)) {
03189       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
03190     }
03191     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(), N0.getValueType());
03192   }
03193   
03194   // fold (zext (and (trunc x), cst)) -> (and x, cst).
03195   if (N0.getOpcode() == ISD::AND &&
03196       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
03197       N0.getOperand(1).getOpcode() == ISD::Constant) {
03198     SDValue X = N0.getOperand(0).getOperand(0);
03199     if (X.getValueType().bitsLT(VT)) {
03200       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
03201     } else if (X.getValueType().bitsGT(VT)) {
03202       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
03203     }
03204     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
03205     Mask.zext(VT.getSizeInBits());
03206     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03207                        X, DAG.getConstant(Mask, VT));
03208   }
03209   
03210   // fold (zext (load x)) -> (zext (truncate (zextload x)))
03211   if (ISD::isNON_EXTLoad(N0.getNode()) &&
03212       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03213        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
03214     bool DoXform = true;
03215     SmallVector<SDNode*, 4> SetCCs;
03216     if (!N0.hasOneUse())
03217       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
03218     if (DoXform) {
03219       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03220       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
03221                                        LN0->getChain(),
03222                                        LN0->getBasePtr(), LN0->getSrcValue(),
03223                                        LN0->getSrcValueOffset(),
03224                                        N0.getValueType(),
03225                                        LN0->isVolatile(), LN0->getAlignment());
03226       CombineTo(N, ExtLoad);
03227       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03228                                   N0.getValueType(), ExtLoad);
03229       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
03230 
03231       // Extend SetCC uses if necessary.
03232       for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
03233         SDNode *SetCC = SetCCs[i];
03234         SmallVector<SDValue, 4> Ops;
03235 
03236         for (unsigned j = 0; j != 2; ++j) {
03237           SDValue SOp = SetCC->getOperand(j);
03238           if (SOp == Trunc)
03239             Ops.push_back(ExtLoad);
03240           else
03241             Ops.push_back(DAG.getNode(ISD::ZERO_EXTEND,
03242                                       N->getDebugLoc(), VT, SOp));
03243         }
03244 
03245         Ops.push_back(SetCC->getOperand(2));
03246         CombineTo(SetCC, DAG.getNode(ISD::SETCC, N->getDebugLoc(),
03247                                      SetCC->getValueType(0),
03248                                      &Ops[0], Ops.size()));
03249       }
03250 
03251       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03252     }
03253   }
03254 
03255   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
03256   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
03257   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
03258       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
03259     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03260     MVT EVT = LN0->getMemoryVT();
03261     if ((!LegalOperations && !LN0->isVolatile()) ||
03262         TLI.isLoadExtLegal(ISD::ZEXTLOAD, EVT)) {
03263       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
03264                                        LN0->getChain(),
03265                                        LN0->getBasePtr(), LN0->getSrcValue(),
03266                                        LN0->getSrcValueOffset(), EVT,
03267                                        LN0->isVolatile(), LN0->getAlignment());
03268       CombineTo(N, ExtLoad);
03269       CombineTo(N0.getNode(),
03270                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
03271                             ExtLoad),
03272                 ExtLoad.getValue(1));
03273       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03274     }
03275   }
03276   
03277   // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
03278   if (N0.getOpcode() == ISD::SETCC) {
03279     SDValue SCC = 
03280       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03281                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
03282                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03283     if (SCC.getNode()) return SCC;
03284   }
03285   
03286   return SDValue();
03287 }
03288 
03289 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
03290   SDValue N0 = N->getOperand(0);
03291   MVT VT = N->getValueType(0);
03292   
03293   // fold (aext c1) -> c1
03294   if (isa<ConstantSDNode>(N0))
03295     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
03296   // fold (aext (aext x)) -> (aext x)
03297   // fold (aext (zext x)) -> (zext x)
03298   // fold (aext (sext x)) -> (sext x)
03299   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
03300       N0.getOpcode() == ISD::ZERO_EXTEND ||
03301       N0.getOpcode() == ISD::SIGN_EXTEND)
03302     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
03303   
03304   // fold (aext (truncate (load x))) -> (aext (smaller load x))
03305   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
03306   if (N0.getOpcode() == ISD::TRUNCATE) {
03307     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
03308     if (NarrowLoad.getNode()) {
03309       if (NarrowLoad.getNode() != N0.getNode())
03310         CombineTo(N0.getNode(), NarrowLoad);
03311       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, NarrowLoad);
03312     }
03313   }
03314 
03315   // fold (aext (truncate x))
03316   if (N0.getOpcode() == ISD::TRUNCATE) {
03317     SDValue TruncOp = N0.getOperand(0);
03318     if (TruncOp.getValueType() == VT)
03319       return TruncOp; // x iff x size == zext size.
03320     if (TruncOp.getValueType().bitsGT(VT))
03321       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
03322     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
03323   }
03324   
03325   // fold (aext (and (trunc x), cst)) -> (and x, cst).
03326   if (N0.getOpcode() == ISD::AND &&
03327       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
03328       N0.getOperand(1).getOpcode() == ISD::Constant) {
03329     SDValue X = N0.getOperand(0).getOperand(0);
03330     if (X.getValueType().bitsLT(VT)) {
03331       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
03332     } else if (X.getValueType().bitsGT(VT)) {
03333       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
03334     }
03335     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
03336     Mask.zext(VT.getSizeInBits());
03337     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03338                        X, DAG.getConstant(Mask, VT));
03339   }
03340   
03341   // fold (aext (load x)) -> (aext (truncate (extload x)))
03342   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
03343       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03344        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
03345     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03346     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
03347                                      LN0->getChain(),
03348                                      LN0->getBasePtr(), LN0->getSrcValue(),
03349                                      LN0->getSrcValueOffset(),
03350                                      N0.getValueType(),
03351                                      LN0->isVolatile(), LN0->getAlignment());
03352     CombineTo(N, ExtLoad);
03353     // Redirect any chain users to the new load.
03354     DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1),
03355                                   SDValue(ExtLoad.getNode(), 1));
03356     // If any node needs the original loaded value, recompute it.
03357     if (!LN0->use_empty())
03358       CombineTo(LN0, DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03359                                  N0.getValueType(), ExtLoad),
03360                 ExtLoad.getValue(1));
03361     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03362   }
03363   
03364   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
03365   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
03366   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
03367   if (N0.getOpcode() == ISD::LOAD &&
03368       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
03369       N0.hasOneUse()) {
03370     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03371     MVT EVT = LN0->getMemoryVT();
03372     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
03373                                      VT, LN0->getChain(), LN0->getBasePtr(),
03374                                      LN0->getSrcValue(),
03375                                      LN0->getSrcValueOffset(), EVT,
03376                                      LN0->isVolatile(), LN0->getAlignment());
03377     CombineTo(N, ExtLoad);
03378     CombineTo(N0.getNode(),
03379               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
03380                           N0.getValueType(), ExtLoad),
03381               ExtLoad.getValue(1));
03382     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03383   }
03384   
03385   // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
03386   if (N0.getOpcode() == ISD::SETCC) {
03387     SDValue SCC = 
03388       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
03389                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
03390                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
03391     if (SCC.getNode())
03392       return SCC;
03393   }
03394   
03395   return SDValue();
03396 }
03397 
03398 /// GetDemandedBits - See if the specified operand can be simplified with the
03399 /// knowledge that only the bits specified by Mask are used.  If so, return the
03400 /// simpler operand, otherwise return a null SDValue.
03401 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
03402   switch (V.getOpcode()) {
03403   default: break;
03404   case ISD::OR:
03405   case ISD::XOR:
03406     // If the LHS or RHS don't contribute bits to the or, drop them.
03407     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
03408       return V.getOperand(1);
03409     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
03410       return V.getOperand(0);
03411     break;
03412   case ISD::SRL:
03413     // Only look at single-use SRLs.
03414     if (!V.getNode()->hasOneUse())
03415       break;
03416     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
03417       // See if we can recursively simplify the LHS.
03418       unsigned Amt = RHSC->getZExtValue();
03419 
03420       // Watch out for shift count overflow though.
03421       if (Amt >= Mask.getBitWidth()) break;
03422       APInt NewMask = Mask << Amt;
03423       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
03424       if (SimplifyLHS.getNode())
03425         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(), 
03426                            SimplifyLHS, V.getOperand(1));
03427     }
03428   }
03429   return SDValue();
03430 }
03431 
03432 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
03433 /// bits and then truncated to a narrower type and where N is a multiple
03434 /// of number of bits of the narrower type, transform it to a narrower load
03435 /// from address + N / num of bits of new type. If the result is to be
03436 /// extended, also fold the extension to form a extending load.
03437 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
03438   unsigned Opc = N->getOpcode();
03439   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
03440   SDValue N0 = N->getOperand(0);
03441   MVT VT = N->getValueType(0);
03442   MVT EVT = VT;
03443 
03444   // This transformation isn't valid for vector loads.
03445   if (VT.isVector())
03446     return SDValue();
03447 
03448   // Special case: SIGN_EXTEND_INREG is basically truncating to EVT then
03449   // extended to VT.
03450   if (Opc == ISD::SIGN_EXTEND_INREG) {
03451     ExtType = ISD::SEXTLOAD;
03452     EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
03453     if (LegalOperations && !TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))
03454       return SDValue();
03455   }
03456 
03457   unsigned EVTBits = EVT.getSizeInBits();
03458   unsigned ShAmt = 0;
03459   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
03460     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
03461       ShAmt = N01->getZExtValue();
03462       // Is the shift amount a multiple of size of VT?
03463       if ((ShAmt & (EVTBits-1)) == 0) {
03464         N0 = N0.getOperand(0);
03465         if (N0.getValueType().getSizeInBits() <= EVTBits)
03466           return SDValue();
03467       }
03468     }
03469   }
03470 
03471   // Do not generate loads of non-round integer types since these can
03472   // be expensive (and would be wrong if the type is not byte sized).
03473   if (isa<LoadSDNode>(N0) && N0.hasOneUse() && EVT.isRound() &&
03474       cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() > EVTBits &&
03475       // Do not change the width of a volatile load.
03476       !cast<LoadSDNode>(N0)->isVolatile()) {
03477     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03478     MVT PtrType = N0.getOperand(1).getValueType();
03479 
03480     // For big endian targets, we need to adjust the offset to the pointer to
03481     // load the correct bytes.
03482     if (TLI.isBigEndian()) {
03483       unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
03484       unsigned EVTStoreBits = EVT.getStoreSizeInBits();
03485       ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
03486     }
03487 
03488     uint64_t PtrOff =  ShAmt / 8;
03489     unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
03490     SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
03491                                  PtrType, LN0->getBasePtr(),
03492                                  DAG.getConstant(PtrOff, PtrType));
03493     AddToWorkList(NewPtr.getNode());
03494 
03495     SDValue Load = (ExtType == ISD::NON_EXTLOAD)
03496       ? DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
03497                     LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
03498                     LN0->isVolatile(), NewAlign)
03499       : DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(), NewPtr,
03500                        LN0->getSrcValue(), LN0->getSrcValueOffset() + PtrOff,
03501                        EVT, LN0->isVolatile(), NewAlign);
03502 
03503     // Replace the old load's chain with the new load's chain.
03504     WorkListRemover DeadNodes(*this);
03505     DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
03506                                   &DeadNodes);
03507 
03508     // Return the new loaded value.
03509     return Load;
03510   }
03511 
03512   return SDValue();
03513 }
03514 
03515 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
03516   SDValue N0 = N->getOperand(0);
03517   SDValue N1 = N->getOperand(1);
03518   MVT VT = N->getValueType(0);
03519   MVT EVT = cast<VTSDNode>(N1)->getVT();
03520   unsigned VTBits = VT.getSizeInBits();
03521   unsigned EVTBits = EVT.getSizeInBits();
03522   
03523   // fold (sext_in_reg c1) -> c1
03524   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
03525     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
03526   
03527   // If the input is already sign extended, just drop the extension.
03528   if (DAG.ComputeNumSignBits(N0) >= VT.getSizeInBits()-EVTBits+1)
03529     return N0;
03530   
03531   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
03532   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
03533       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
03534     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
03535                        N0.getOperand(0), N1);
03536   }
03537 
03538   // fold (sext_in_reg (sext x)) -> (sext x)
03539   // fold (sext_in_reg (aext x)) -> (sext x)
03540   // if x is small enough.
03541   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
03542     SDValue N00 = N0.getOperand(0);
03543     if (N00.getValueType().getSizeInBits() < EVTBits)
03544       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
03545   }
03546 
03547   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
03548   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
03549     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
03550   
03551   // fold operands of sext_in_reg based on knowledge that the top bits are not
03552   // demanded.
03553   if (SimplifyDemandedBits(SDValue(N, 0)))
03554     return SDValue(N, 0);
03555   
03556   // fold (sext_in_reg (load x)) -> (smaller sextload x)
03557   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
03558   SDValue NarrowLoad = ReduceLoadWidth(N);
03559   if (NarrowLoad.getNode())
03560     return NarrowLoad;
03561 
03562   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
03563   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
03564   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
03565   if (N0.getOpcode() == ISD::SRL) {
03566     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
03567       if (ShAmt->getZExtValue()+EVTBits <= VT.getSizeInBits()) {
03568         // We can turn this into an SRA iff the input to the SRL is already sign
03569         // extended enough.
03570         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
03571         if (VT.getSizeInBits()-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
03572           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
03573                              N0.getOperand(0), N0.getOperand(1));
03574       }
03575   }
03576 
03577   // fold (sext_inreg (extload x)) -> (sextload x)
03578   if (ISD::isEXTLoad(N0.getNode()) && 
03579       ISD::isUNINDEXEDLoad(N0.getNode()) &&
03580       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
03581       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03582        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
03583     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03584     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03585                                      LN0->getChain(),
03586                                      LN0->getBasePtr(), LN0->getSrcValue(),
03587                                      LN0->getSrcValueOffset(), EVT,
03588                                      LN0->isVolatile(), LN0->getAlignment());
03589     CombineTo(N, ExtLoad);
03590     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
03591     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03592   }
03593   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
03594   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
03595       N0.hasOneUse() &&
03596       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
03597       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
03598        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
03599     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03600     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
03601                                      LN0->getChain(),
03602                                      LN0->getBasePtr(), LN0->getSrcValue(),
03603                                      LN0->getSrcValueOffset(), EVT,
03604                                      LN0->isVolatile(), LN0->getAlignment());
03605     CombineTo(N, ExtLoad);
03606     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
03607     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
03608   }
03609   return SDValue();
03610 }
03611 
03612 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
03613   SDValue N0 = N->getOperand(0);
03614   MVT VT = N->getValueType(0);
03615 
03616   // noop truncate
03617   if (N0.getValueType() == N->getValueType(0))
03618     return N0;
03619   // fold (truncate c1) -> c1
03620   if (isa<ConstantSDNode>(N0))
03621     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
03622   // fold (truncate (truncate x)) -> (truncate x)
03623   if (N0.getOpcode() == ISD::TRUNCATE)
03624     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
03625   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
03626   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::SIGN_EXTEND||
03627       N0.getOpcode() == ISD::ANY_EXTEND) {
03628     if (N0.getOperand(0).getValueType().bitsLT(VT))
03629       // if the source is smaller than the dest, we still need an extend
03630       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
03631                          N0.getOperand(0));
03632     else if (N0.getOperand(0).getValueType().bitsGT(VT))
03633       // if the source is larger than the dest, than we just need the truncate
03634       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
03635     else
03636       // if the source and dest are the same type, we can drop both the extend
03637       // and the truncate
03638       return N0.getOperand(0);
03639   }
03640 
03641   // See if we can simplify the input to this truncate through knowledge that
03642   // only the low bits are being used.  For example "trunc (or (shl x, 8), y)"
03643   // -> trunc y
03644   SDValue Shorter =
03645     GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
03646                                              VT.getSizeInBits()));
03647   if (Shorter.getNode())
03648     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
03649 
03650   // fold (truncate (load x)) -> (smaller load x)
03651   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
03652   return ReduceLoadWidth(N);
03653 }
03654 
03655 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
03656   SDValue Elt = N->getOperand(i);
03657   if (Elt.getOpcode() != ISD::MERGE_VALUES)
03658     return Elt.getNode();
03659   return Elt.getOperand(Elt.getResNo()).getNode();
03660 }
03661 
03662 /// CombineConsecutiveLoads - build_pair (load, load) -> load
03663 /// if load locations are consecutive. 
03664 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, MVT VT) {
03665   assert(N->getOpcode() == ISD::BUILD_PAIR);
03666 
03667   SDNode *LD1 = getBuildPairElt(N, 0);
03668   if (!ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse())
03669     return SDValue();
03670   MVT LD1VT = LD1->getValueType(0);
03671   SDNode *LD2 = getBuildPairElt(N, 1);
03672   const MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
03673 
03674   if (ISD::isNON_EXTLoad(LD2) &&
03675       LD2->hasOneUse() &&
03676       // If both are volatile this would reduce the number of volatile loads.
03677       // If one is volatile it might be ok, but play conservative and bail out.
03678       !cast<LoadSDNode>(LD1)->isVolatile() &&
03679       !cast<LoadSDNode>(LD2)->isVolatile() &&
03680       TLI.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1, MFI)) {
03681     LoadSDNode *LD = cast<LoadSDNode>(LD1);
03682     unsigned Align = LD->getAlignment();
03683     unsigned NewAlign = TLI.getTargetData()->
03684       getABITypeAlignment(VT.getTypeForMVT());
03685 
03686     if (NewAlign <= Align &&
03687         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
03688       return DAG.getLoad(VT, N->getDebugLoc(), LD->getChain(), LD->getBasePtr(),
03689                          LD->getSrcValue(), LD->getSrcValueOffset(),
03690                          false, Align);
03691   }
03692 
03693   return SDValue();
03694 }
03695 
03696 SDValue DAGCombiner::visitBIT_CONVERT(SDNode *N) {
03697   SDValue N0 = N->getOperand(0);
03698   MVT VT = N->getValueType(0);
03699 
03700   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
03701   // Only do this before legalize, since afterward the target may be depending
03702   // on the bitconvert.
03703   // First check to see if this is all constant.
03704   if (!LegalTypes &&
03705       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
03706       VT.isVector()) {
03707     bool isSimple = true;
03708     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
03709       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
03710           N0.getOperand(i).getOpcode() != ISD::Constant &&
03711           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
03712         isSimple = false; 
03713         break;
03714       }
03715         
03716     MVT DestEltVT = N->getValueType(0).getVectorElementType();
03717     assert(!DestEltVT.isVector() &&
03718            "Element type of vector ValueType must not be vector!");
03719     if (isSimple)
03720       return ConstantFoldBIT_CONVERTofBUILD_VECTOR(N0.getNode(), DestEltVT);
03721   }
03722   
03723   // If the input is a constant, let getNode fold it.
03724   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
03725     SDValue Res = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT, N0);
03726     if (Res.getNode() != N) return Res;
03727   }
03728   
03729   // (conv (conv x, t1), t2) -> (conv x, t2)
03730   if (N0.getOpcode() == ISD::BIT_CONVERT)
03731     return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(), VT,
03732                        N0.getOperand(0));
03733 
03734   // fold (conv (load x)) -> (load (conv*)x)
03735   // If the resultant load doesn't need a higher alignment than the original!
03736   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
03737       // Do not change the width of a volatile load.
03738       !cast<LoadSDNode>(N0)->isVolatile() &&
03739       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
03740     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
03741     unsigned Align = TLI.getTargetData()->
03742       getABITypeAlignment(VT.getTypeForMVT());
03743     unsigned OrigAlign = LN0->getAlignment();
03744 
03745     if (Align <= OrigAlign) {
03746       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
03747                                  LN0->getBasePtr(),
03748                                  LN0->getSrcValue(), LN0->getSrcValueOffset(),
03749                                  LN0->isVolatile(), OrigAlign);
03750       AddToWorkList(N);
03751       CombineTo(N0.getNode(),
03752                 DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03753                             N0.getValueType(), Load),
03754                 Load.getValue(1));
03755       return Load;
03756     }
03757   }
03758 
03759   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
03760   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
03761   // This often reduces constant pool loads.
03762   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
03763       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
03764     SDValue NewConv = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(), VT,
03765                                   N0.getOperand(0));
03766     AddToWorkList(NewConv.getNode());
03767     
03768     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
03769     if (N0.getOpcode() == ISD::FNEG)
03770       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
03771                          NewConv, DAG.getConstant(SignBit, VT));
03772     assert(N0.getOpcode() == ISD::FABS);
03773     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
03774                        NewConv, DAG.getConstant(~SignBit, VT));
03775   }
03776   
03777   // fold (bitconvert (fcopysign cst, x)) ->
03778   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
03779   // Note that we don't handle (copysign x, cst) because this can always be
03780   // folded to an fneg or fabs.
03781   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
03782       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
03783       VT.isInteger() && !VT.isVector()) {
03784     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
03785     MVT IntXVT = MVT::getIntegerVT(OrigXWidth);
03786     if (TLI.isTypeLegal(IntXVT) || !LegalTypes) {
03787       SDValue X = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03788                               IntXVT, N0.getOperand(1));
03789       AddToWorkList(X.getNode());
03790 
03791       // If X has a different width than the result/lhs, sext it or truncate it.
03792       unsigned VTWidth = VT.getSizeInBits();
03793       if (OrigXWidth < VTWidth) {
03794         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
03795         AddToWorkList(X.getNode());
03796       } else if (OrigXWidth > VTWidth) {
03797         // To get the sign bit in the right place, we have to shift it right
03798         // before truncating.
03799         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
03800                         X.getValueType(), X,
03801                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
03802         AddToWorkList(X.getNode());
03803         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
03804         AddToWorkList(X.getNode());
03805       }
03806     
03807       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
03808       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
03809                       X, DAG.getConstant(SignBit, VT));
03810       AddToWorkList(X.getNode());
03811 
03812       SDValue Cst = DAG.getNode(ISD::BIT_CONVERT, N0.getDebugLoc(),
03813                                 VT, N0.getOperand(0));
03814       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
03815                         Cst, DAG.getConstant(~SignBit, VT));
03816       AddToWorkList(Cst.getNode());
03817 
03818       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
03819     }
03820   }
03821 
03822   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive. 
03823   if (N0.getOpcode() == ISD::BUILD_PAIR) {
03824     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
03825     if (CombineLD.getNode())
03826       return CombineLD;
03827   }
03828   
03829   return SDValue();
03830 }
03831 
03832 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
03833   MVT VT = N->getValueType(0);
03834   return CombineConsecutiveLoads(N, VT);
03835 }
03836 
03837 /// ConstantFoldBIT_CONVERTofBUILD_VECTOR - We know that BV is a build_vector
03838 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the 
03839 /// destination element value type.
03840 SDValue DAGCombiner::
03841 ConstantFoldBIT_CONVERTofBUILD_VECTOR(SDNode *BV, MVT DstEltVT) {
03842   MVT SrcEltVT = BV->getOperand(0).getValueType();
03843   
03844   // If this is already the right type, we're done.
03845   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
03846   
03847   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
03848   unsigned DstBitSize = DstEltVT.getSizeInBits();
03849   
03850   // If this is a conversion of N elements of one type to N elements of another
03851   // type, convert each element.  This handles FP<->INT cases.
03852   if (SrcBitSize == DstBitSize) {
03853     SmallVector<SDValue, 8> Ops;
03854     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
03855       Ops.push_back(DAG.getNode(ISD::BIT_CONVERT, BV->getDebugLoc(),
03856                                 DstEltVT, BV->getOperand(i)));
03857       AddToWorkList(Ops.back().getNode());
03858     }
03859     MVT VT = MVT::getVectorVT(DstEltVT,
03860                               BV->getValueType(0).getVectorNumElements());
03861     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03862                        &Ops[0], Ops.size());
03863   }
03864   
03865   // Otherwise, we're growing or shrinking the elements.  To avoid having to
03866   // handle annoying details of growing/shrinking FP values, we convert them to
03867   // int first.
03868   if (SrcEltVT.isFloatingPoint()) {
03869     // Convert the input float vector to a int vector where the elements are the
03870     // same sizes.
03871     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
03872     MVT IntVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits());
03873     BV = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, IntVT).getNode();
03874     SrcEltVT = IntVT;
03875   }
03876   
03877   // Now we know the input is an integer vector.  If the output is a FP type,
03878   // convert to integer first, then to FP of the right size.
03879   if (DstEltVT.isFloatingPoint()) {
03880     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
03881     MVT TmpVT = MVT::getIntegerVT(DstEltVT.getSizeInBits());
03882     SDNode *Tmp = ConstantFoldBIT_CONVERTofBUILD_VECTOR(BV, TmpVT).getNode();
03883     
03884     // Next, convert to FP elements of the same size.
03885     return ConstantFoldBIT_CONVERTofBUILD_VECTOR(Tmp, DstEltVT);
03886   }
03887   
03888   // Okay, we know the src/dst types are both integers of differing types.
03889   // Handling growing first.
03890   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
03891   if (SrcBitSize < DstBitSize) {
03892     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
03893     
03894     SmallVector<SDValue, 8> Ops;
03895     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
03896          i += NumInputsPerOutput) {
03897       bool isLE = TLI.isLittleEndian();
03898       APInt NewBits = APInt(DstBitSize, 0);
03899       bool EltIsUndef = true;
03900       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
03901         // Shift the previously computed bits over.
03902         NewBits <<= SrcBitSize;
03903         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
03904         if (Op.getOpcode() == ISD::UNDEF) continue;
03905         EltIsUndef = false;
03906         
03907         NewBits |=
03908           APInt(cast<ConstantSDNode>(Op)->getAPIntValue()).zext(DstBitSize);
03909       }
03910       
03911       if (EltIsUndef)
03912         Ops.push_back(DAG.getNode(ISD::UNDEF, BV->getDebugLoc(), DstEltVT));
03913       else
03914         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
03915     }
03916 
03917     MVT VT = MVT::getVectorVT(DstEltVT, Ops.size());
03918     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03919                        &Ops[0], Ops.size());
03920   }
03921   
03922   // Finally, this must be the case where we are shrinking elements: each input
03923   // turns into multiple outputs.
03924   bool isS2V = ISD::isScalarToVector(BV);
03925   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
03926   MVT VT = MVT::getVectorVT(DstEltVT, NumOutputsPerInput*BV->getNumOperands());
03927   SmallVector<SDValue, 8> Ops;
03928 
03929   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
03930     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
03931       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
03932         Ops.push_back(DAG.getNode(ISD::UNDEF, BV->getDebugLoc(), DstEltVT));
03933       continue;
03934     }
03935 
03936     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->getAPIntValue();
03937 
03938     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
03939       APInt ThisVal = APInt(OpVal).trunc(DstBitSize);
03940       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
03941       if (isS2V && i == 0 && j == 0 && APInt(ThisVal).zext(SrcBitSize) == OpVal)
03942         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
03943         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
03944                            Ops[0]);
03945       OpVal = OpVal.lshr(DstBitSize);
03946     }
03947 
03948     // For big endian targets, swap the order of the pieces of each element.
03949     if (TLI.isBigEndian())
03950       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
03951   }
03952 
03953   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
03954                      &Ops[0], Ops.size());
03955 }
03956 
03957 SDValue DAGCombiner::visitFADD(SDNode *N) {
03958   SDValue N0 = N->getOperand(0);
03959   SDValue N1 = N->getOperand(1);
03960   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
03961   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
03962   MVT VT = N->getValueType(0);
03963   
03964   // fold vector ops
03965   if (VT.isVector()) {
03966     SDValue FoldedVOp = SimplifyVBinOp(N);
03967     if (FoldedVOp.getNode()) return FoldedVOp;
03968   }
03969   
03970   // fold (fadd c1, c2) -> (fadd c1, c2)
03971   if (N0CFP && N1CFP && VT != MVT::ppcf128)
03972     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
03973   // canonicalize constant to RHS
03974   if (N0CFP && !N1CFP)
03975     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
03976   // fold (fadd A, 0) -> A
03977   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
03978     return N0;
03979   // fold (fadd A, (fneg B)) -> (fsub A, B)
03980   if (isNegatibleForFree(N1, LegalOperations) == 2)
03981     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
03982                        GetNegatedExpression(N1, DAG, LegalOperations));
03983   // fold (fadd (fneg A), B) -> (fsub B, A)
03984   if (isNegatibleForFree(N0, LegalOperations) == 2)
03985     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
03986                        GetNegatedExpression(N0, DAG, LegalOperations));
03987   
03988   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
03989   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
03990       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
03991     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
03992                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
03993                                    N0.getOperand(1), N1));
03994   
03995   return SDValue();
03996 }
03997 
03998 SDValue DAGCombiner::visitFSUB(SDNode *N) {
03999   SDValue N0 = N->getOperand(0);
04000   SDValue N1 = N->getOperand(1);
04001   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04002   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04003   MVT VT = N->getValueType(0);
04004   
04005   // fold vector ops
04006   if (VT.isVector()) {
04007     SDValue FoldedVOp = SimplifyVBinOp(N);
04008     if (FoldedVOp.getNode()) return FoldedVOp;
04009   }
04010   
04011   // fold (fsub c1, c2) -> c1-c2
04012   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04013     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
04014   // fold (fsub A, 0) -> A
04015   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
04016     return N0;
04017   // fold (fsub 0, B) -> -B
04018   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
04019     if (isNegatibleForFree(N1, LegalOperations))
04020       return GetNegatedExpression(N1, DAG, LegalOperations);
04021     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04022       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
04023   }
04024   // fold (fsub A, (fneg B)) -> (fadd A, B)
04025   if (isNegatibleForFree(N1, LegalOperations))
04026     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
04027                        GetNegatedExpression(N1, DAG, LegalOperations));
04028   
04029   return SDValue();
04030 }
04031 
04032 SDValue DAGCombiner::visitFMUL(SDNode *N) {
04033   SDValue N0 = N->getOperand(0);
04034   SDValue N1 = N->getOperand(1);
04035   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04036   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04037   MVT VT = N->getValueType(0);
04038 
04039   // fold vector ops
04040   if (VT.isVector()) {
04041     SDValue FoldedVOp = SimplifyVBinOp(N);
04042     if (FoldedVOp.getNode()) return FoldedVOp;
04043   }
04044   
04045   // fold (fmul c1, c2) -> c1*c2
04046   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04047     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
04048   // canonicalize constant to RHS
04049   if (N0CFP && !N1CFP)
04050     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
04051   // fold (fmul A, 0) -> 0
04052   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
04053     return N1;
04054   // fold (fmul X, 2.0) -> (fadd X, X)
04055   if (N1CFP && N1CFP->isExactlyValue(+2.0))
04056     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
04057   // fold (fmul X, (fneg 1.0)) -> (fneg X)
04058   if (N1CFP && N1CFP->isExactlyValue(-1.0))
04059     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04060       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
04061   
04062   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
04063   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
04064     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
04065       // Both can be negated for free, check to see if at least one is cheaper
04066       // negated.
04067       if (LHSNeg == 2 || RHSNeg == 2)
04068         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
04069                            GetNegatedExpression(N0, DAG, LegalOperations),
04070                            GetNegatedExpression(N1, DAG, LegalOperations));
04071     }
04072   }
04073   
04074   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
04075   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
04076       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
04077     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
04078                        DAG.getNode(ISD::FMUL, VT, N0.getOperand(1), N1));
04079   
04080   return SDValue();
04081 }
04082 
04083 SDValue DAGCombiner::visitFDIV(SDNode *N) {
04084   SDValue N0 = N->getOperand(0);
04085   SDValue N1 = N->getOperand(1);
04086   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04087   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04088   MVT VT = N->getValueType(0);
04089 
04090   // fold vector ops
04091   if (VT.isVector()) {
04092     SDValue FoldedVOp = SimplifyVBinOp(N);
04093     if (FoldedVOp.getNode()) return FoldedVOp;
04094   }
04095   
04096   // fold (fdiv c1, c2) -> c1/c2
04097   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04098     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
04099   
04100   
04101   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
04102   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
04103     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
04104       // Both can be negated for free, check to see if at least one is cheaper
04105       // negated.
04106       if (LHSNeg == 2 || RHSNeg == 2)
04107         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, 
04108                            GetNegatedExpression(N0, DAG, LegalOperations),
04109                            GetNegatedExpression(N1, DAG, LegalOperations));
04110     }
04111   }
04112   
04113   return SDValue();
04114 }
04115 
04116 SDValue DAGCombiner::visitFREM(SDNode *N) {
04117   SDValue N0 = N->getOperand(0);
04118   SDValue N1 = N->getOperand(1);
04119   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04120   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04121   MVT VT = N->getValueType(0);
04122 
04123   // fold (frem c1, c2) -> fmod(c1,c2)
04124   if (N0CFP && N1CFP && VT != MVT::ppcf128)
04125     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
04126 
04127   return SDValue();
04128 }
04129 
04130 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
04131   SDValue N0 = N->getOperand(0);
04132   SDValue N1 = N->getOperand(1);
04133   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04134   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
04135   MVT VT = N->getValueType(0);
04136 
04137   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
04138     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
04139   
04140   if (N1CFP) {
04141     const APFloat& V = N1CFP->getValueAPF();
04142     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
04143     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
04144     if (!V.isNegative()) {
04145       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
04146         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04147     } else {
04148       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
04149         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
04150                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
04151     }
04152   }
04153   
04154   // copysign(fabs(x), y) -> copysign(x, y)
04155   // copysign(fneg(x), y) -> copysign(x, y)
04156   // copysign(copysign(x,z), y) -> copysign(x, y)
04157   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
04158       N0.getOpcode() == ISD::FCOPYSIGN)
04159     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04160                        N0.getOperand(0), N1);
04161 
04162   // copysign(x, abs(y)) -> abs(x)
04163   if (N1.getOpcode() == ISD::FABS)
04164     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04165   
04166   // copysign(x, copysign(y,z)) -> copysign(x, z)
04167   if (N1.getOpcode() == ISD::FCOPYSIGN)
04168     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04169                        N0, N1.getOperand(1));
04170   
04171   // copysign(x, fp_extend(y)) -> copysign(x, y)
04172   // copysign(x, fp_round(y)) -> copysign(x, y)
04173   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
04174     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04175                        N0, N1.getOperand(0));
04176   
04177   return SDValue();
04178 }
04179 
04180 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
04181   SDValue N0 = N->getOperand(0);
04182   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04183   MVT VT = N->getValueType(0);
04184   MVT OpVT = N0.getValueType();
04185 
04186   // fold (sint_to_fp c1) -> c1fp
04187   if (N0C && OpVT != MVT::ppcf128)
04188     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
04189   
04190   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
04191   // but UINT_TO_FP is legal on this target, try to convert.
04192   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
04193       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
04194     // If the sign bit is known to be zero, we can change this to UINT_TO_FP. 
04195     if (DAG.SignBitIsZero(N0))
04196       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
04197   }
04198 
04199   return SDValue();
04200 }
04201 
04202 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
04203   SDValue N0 = N->getOperand(0);
04204   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04205   MVT VT = N->getValueType(0);
04206   MVT OpVT = N0.getValueType();
04207 
04208   // fold (uint_to_fp c1) -> c1fp
04209   if (N0C && OpVT != MVT::ppcf128)
04210     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
04211   
04212   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
04213   // but SINT_TO_FP is legal on this target, try to convert.
04214   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
04215       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
04216     // If the sign bit is known to be zero, we can change this to SINT_TO_FP. 
04217     if (DAG.SignBitIsZero(N0))
04218       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
04219   }
04220   
04221   return SDValue();
04222 }
04223 
04224 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
04225   SDValue N0 = N->getOperand(0);
04226   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04227   MVT VT = N->getValueType(0);
04228   
04229   // fold (fp_to_sint c1fp) -> c1
04230   if (N0CFP)
04231     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
04232 
04233   return SDValue();
04234 }
04235 
04236 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
04237   SDValue N0 = N->getOperand(0);
04238   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04239   MVT VT = N->getValueType(0);
04240   
04241   // fold (fp_to_uint c1fp) -> c1
04242   if (N0CFP && VT != MVT::ppcf128)
04243     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
04244 
04245   return SDValue();
04246 }
04247 
04248 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
04249   SDValue N0 = N->getOperand(0);
04250   SDValue N1 = N->getOperand(1);
04251   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04252   MVT VT = N->getValueType(0);
04253   
04254   // fold (fp_round c1fp) -> c1fp
04255   if (N0CFP && N0.getValueType() != MVT::ppcf128)
04256     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
04257   
04258   // fold (fp_round (fp_extend x)) -> x
04259   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
04260     return N0.getOperand(0);
04261   
04262   // fold (fp_round (fp_round x)) -> (fp_round x)
04263   if (N0.getOpcode() == ISD::FP_ROUND) {
04264     // This is a value preserving truncation if both round's are.
04265     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
04266                    N0.getNode()->getConstantOperandVal(1) == 1;
04267     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
04268                        DAG.getIntPtrConstant(IsTrunc));
04269   }
04270   
04271   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
04272   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
04273     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
04274                               N0.getOperand(0), N1);
04275     AddToWorkList(Tmp.getNode());
04276     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
04277                        Tmp, N0.getOperand(1));
04278   }
04279   
04280   return SDValue();
04281 }
04282 
04283 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
04284   SDValue N0 = N->getOperand(0);
04285   MVT VT = N->getValueType(0);
04286   MVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
04287   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04288   
04289   // fold (fp_round_inreg c1fp) -> c1fp
04290   if (N0CFP && (TLI.isTypeLegal(EVT) || !LegalTypes)) {
04291     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
04292     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
04293   }
04294 
04295   return SDValue();
04296 }
04297 
04298 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
04299   SDValue N0 = N->getOperand(0);
04300   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04301   MVT VT = N->getValueType(0);
04302   
04303   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
04304   if (N->hasOneUse() && 
04305       N->use_begin()->getOpcode() == ISD::FP_ROUND)
04306     return SDValue();
04307 
04308   // fold (fp_extend c1fp) -> c1fp
04309   if (N0CFP && VT != MVT::ppcf128)
04310     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
04311 
04312   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
04313   // value of X.
04314   if (N0.getOpcode() == ISD::FP_ROUND
04315       && N0.getNode()->getConstantOperandVal(1) == 1) {
04316     SDValue In = N0.getOperand(0);
04317     if (In.getValueType() == VT) return In;
04318     if (VT.bitsLT(In.getValueType()))
04319       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
04320                          In, N0.getOperand(1));
04321     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
04322   }
04323       
04324   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
04325   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
04326       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
04327        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
04328     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
04329     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
04330                                      LN0->getChain(),
04331                                      LN0->getBasePtr(), LN0->getSrcValue(),
04332                                      LN0->getSrcValueOffset(),
04333                                      N0.getValueType(),
04334                                      LN0->isVolatile(), LN0->getAlignment());
04335     CombineTo(N, ExtLoad);
04336     CombineTo(N0.getNode(),
04337               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
04338                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
04339               ExtLoad.getValue(1));
04340     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04341   }
04342 
04343   return SDValue();
04344 }
04345 
04346 SDValue DAGCombiner::visitFNEG(SDNode *N) {
04347   SDValue N0 = N->getOperand(0);
04348 
04349   if (isNegatibleForFree(N0, LegalOperations))
04350     return GetNegatedExpression(N0, DAG, LegalOperations);
04351 
04352   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
04353   // constant pool values.
04354   if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
04355       N0.getOperand(0).getValueType().isInteger() &&
04356       !N0.getOperand(0).getValueType().isVector()) {
04357     SDValue Int = N0.getOperand(0);
04358     MVT IntVT = Int.getValueType();
04359     if (IntVT.isInteger() && !IntVT.isVector()) {
04360       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
04361               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
04362       AddToWorkList(Int.getNode());
04363       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
04364                          N->getValueType(0), Int);
04365     }
04366   }
04367   
04368   return SDValue();
04369 }
04370 
04371 SDValue DAGCombiner::visitFABS(SDNode *N) {
04372   SDValue N0 = N->getOperand(0);
04373   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
04374   MVT VT = N->getValueType(0);
04375   
04376   // fold (fabs c1) -> fabs(c1)
04377   if (N0CFP && VT != MVT::ppcf128)
04378     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
04379   // fold (fabs (fabs x)) -> (fabs x)
04380   if (N0.getOpcode() == ISD::FABS)
04381     return N->getOperand(0);
04382   // fold (fabs (fneg x)) -> (fabs x)
04383   // fold (fabs (fcopysign x, y)) -> (fabs x)
04384   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
04385     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
04386   
04387   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
04388   // constant pool values.
04389   if (N0.getOpcode() == ISD::BIT_CONVERT && N0.getNode()->hasOneUse() &&
04390       N0.getOperand(0).getValueType().isInteger() &&
04391       !N0.getOperand(0).getValueType().isVector()) {
04392     SDValue Int = N0.getOperand(0);
04393     MVT IntVT = Int.getValueType();
04394     if (IntVT.isInteger() && !IntVT.isVector()) {
04395       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int, 
04396              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
04397       AddToWorkList(Int.getNode());
04398       return DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
04399                          N->getValueType(0), Int);
04400     }
04401   }
04402   
04403   return SDValue();
04404 }
04405 
04406 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
04407   SDValue Chain = N->getOperand(0);
04408   SDValue N1 = N->getOperand(1);
04409   SDValue N2 = N->getOperand(2);
04410   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04411   
04412   // never taken branch, fold to chain
04413   if (N1C && N1C->isNullValue())
04414     return Chain;
04415   // unconditional branch
04416   if (N1C && N1C->getAPIntValue() == 1)
04417     return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other, Chain, N2);
04418   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
04419   // on the target.
04420   if (N1.getOpcode() == ISD::SETCC && 
04421       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
04422     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
04423                        Chain, N1.getOperand(2),
04424                        N1.getOperand(0), N1.getOperand(1), N2);
04425   }
04426 
04427   return SDValue();
04428 }
04429 
04430 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
04431 //
04432 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
04433   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
04434   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
04435   
04436   // Use SimplifySetCC to simplify SETCC's.
04437   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
04438                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
04439                                false);
04440   if (Simp.getNode()) AddToWorkList(Simp.getNode());
04441 
04442   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(Simp.getNode());
04443 
04444   // fold br_cc true, dest -> br dest (unconditional branch)
04445   if (SCCC && !SCCC->isNullValue())
04446     return DAG.getNode(ISD::BR, N->getDebugLoc(), MVT::Other,
04447                        N->getOperand(0), N->getOperand(4));
04448   // fold br_cc false, dest -> unconditional fall through
04449   if (SCCC && SCCC->isNullValue())
04450     return N->getOperand(0);
04451 
04452   // fold to a simpler setcc
04453   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
04454     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
04455                        N->getOperand(0), Simp.getOperand(2),
04456                        Simp.getOperand(0), Simp.getOperand(1),
04457                        N->getOperand(4));
04458 
04459   return SDValue();
04460 }
04461 
04462 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
04463 /// pre-indexed load / store when the base pointer is an add or subtract
04464 /// and it has other uses besides the load / store. After the
04465 /// transformation, the new indexed load / store has effectively folded
04466 /// the add / subtract in and all of its other uses are redirected to the
04467 /// new load / store.
04468 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
04469   if (!LegalOperations)
04470     return false;
04471 
04472   bool isLoad = true;
04473   SDValue Ptr;
04474   MVT VT;
04475   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
04476     if (LD->isIndexed())
04477       return false;
04478     VT = LD->getMemoryVT();
04479     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
04480         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
04481       return false;
04482     Ptr = LD->getBasePtr();
04483   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
04484     if (ST->isIndexed())
04485       return false;
04486     VT = ST->getMemoryVT();
04487     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
04488         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
04489       return false;
04490     Ptr = ST->getBasePtr();
04491     isLoad = false;
04492   } else {
04493     return false;
04494   }
04495 
04496   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
04497   // out.  There is no reason to make this a preinc/predec.
04498   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
04499       Ptr.getNode()->hasOneUse())
04500     return false;
04501 
04502   // Ask the target to do addressing mode selection.
04503   SDValue BasePtr;
04504   SDValue Offset;
04505   ISD::MemIndexedMode AM = ISD::UNINDEXED;
04506   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
04507     return false;
04508   // Don't create a indexed load / store with zero offset.
04509   if (isa<ConstantSDNode>(Offset) &&
04510       cast<ConstantSDNode>(Offset)->isNullValue())
04511     return false;
04512   
04513   // Try turning it into a pre-indexed load / store except when:
04514   // 1) The new base ptr is a frame index.
04515   // 2) If N is a store and the new base ptr is either the same as or is a
04516   //    predecessor of the value being stored.
04517   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
04518   //    that would create a cycle.
04519   // 4) All uses are load / store ops that use it as old base ptr.
04520 
04521   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
04522   // (plus the implicit offset) to a register to preinc anyway.
04523   if (isa<FrameIndexSDNode>(BasePtr))
04524     return false;
04525   
04526   // Check #2.
04527   if (!isLoad) {
04528     SDValue Val = cast<StoreSDNode>(N)->getValue();
04529     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
04530       return false;
04531   }
04532 
04533   // Now check for #3 and #4.
04534   bool RealUse = false;
04535   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
04536          E = Ptr.getNode()->use_end(); I != E; ++I) {
04537     SDNode *Use = *I;
04538     if (Use == N)
04539       continue;
04540     if (Use->isPredecessorOf(N))
04541       return false;
04542 
04543     if (!((Use->getOpcode() == ISD::LOAD &&
04544            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
04545           (Use->getOpcode() == ISD::STORE &&
04546            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
04547       RealUse = true;
04548   }
04549 
04550   if (!RealUse)
04551     return false;
04552 
04553   SDValue Result;
04554   if (isLoad)
04555     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
04556                                 BasePtr, Offset, AM);
04557   else
04558     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
04559                                  BasePtr, Offset, AM);
04560   ++PreIndexedNodes;
04561   ++NodesCombined;
04562   DOUT << "\nReplacing.4 "; DEBUG(N->dump(&DAG));
04563   DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
04564   DOUT << '\n';
04565   WorkListRemover DeadNodes(*this);
04566   if (isLoad) {
04567     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
04568                                   &DeadNodes);
04569     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
04570                                   &DeadNodes);
04571   } else {
04572     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
04573                                   &DeadNodes);
04574   }
04575 
04576   // Finally, since the node is now dead, remove it from the graph.
04577   DAG.DeleteNode(N);
04578 
04579   // Replace the uses of Ptr with uses of the updated base value.
04580   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
04581                                 &DeadNodes);
04582   removeFromWorkList(Ptr.getNode());
04583   DAG.DeleteNode(Ptr.getNode());
04584 
04585   return true;
04586 }
04587 
04588 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
04589 /// add / sub of the base pointer node into a post-indexed load / store.
04590 /// The transformation folded the add / subtract into the new indexed
04591 /// load / store effectively and all of its uses are redirected to the
04592 /// new load / store.
04593 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
04594   if (!LegalOperations)
04595     return false;
04596 
04597   bool isLoad = true;
04598   SDValue Ptr;
04599   MVT VT;
04600   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
04601     if (LD->isIndexed())
04602       return false;
04603     VT = LD->getMemoryVT();
04604     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
04605         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
04606       return false;
04607     Ptr = LD->getBasePtr();
04608   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
04609     if (ST->isIndexed())
04610       return false;
04611     VT = ST->getMemoryVT();
04612     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
04613         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
04614       return false;
04615     Ptr = ST->getBasePtr();
04616     isLoad = false;
04617   } else {
04618     return false;
04619   }
04620 
04621   if (Ptr.getNode()->hasOneUse())
04622     return false;
04623   
04624   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
04625          E = Ptr.getNode()->use_end(); I != E; ++I) {
04626     SDNode *Op = *I;
04627     if (Op == N ||
04628         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
04629       continue;
04630 
04631     SDValue BasePtr;
04632     SDValue Offset;
04633     ISD::MemIndexedMode AM = ISD::UNINDEXED;
04634     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
04635       if (Ptr == Offset)
04636         std::swap(BasePtr, Offset);
04637       if (Ptr != BasePtr)
04638         continue;
04639       // Don't create a indexed load / store with zero offset.
04640       if (isa<ConstantSDNode>(Offset) &&
04641           cast<ConstantSDNode>(Offset)->isNullValue())
04642         continue;
04643 
04644       // Try turning it into a post-indexed load / store except when
04645       // 1) All uses are load / store ops that use it as base ptr.
04646       // 2) Op must be independent of N, i.e. Op is neither a predecessor
04647       //    nor a successor of N. Otherwise, if Op is folded that would
04648       //    create a cycle.
04649 
04650       // Check for #1.
04651       bool TryNext = false;
04652       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
04653              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
04654         SDNode *Use = *II;
04655         if (Use == Ptr.getNode())
04656           continue;
04657 
04658         // If all the uses are load / store addresses, then don't do the
04659         // transformation.
04660         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
04661           bool RealUse = false;
04662           for (SDNode::use_iterator III = Use->use_begin(),
04663                  EEE = Use->use_end(); III != EEE; ++III) {
04664             SDNode *UseUse = *III;
04665             if (!((UseUse->getOpcode() == ISD::LOAD &&
04666                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
04667                   (UseUse->getOpcode() == ISD::STORE &&
04668                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
04669               RealUse = true;
04670           }
04671 
04672           if (!RealUse) {
04673             TryNext = true;
04674             break;
04675           }
04676         }
04677       }
04678 
04679       if (TryNext)
04680         continue;
04681 
04682       // Check for #2
04683       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
04684         SDValue Result = isLoad
04685           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
04686                                BasePtr, Offset, AM)
04687           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
04688                                 BasePtr, Offset, AM);
04689         ++PostIndexedNodes;
04690         ++NodesCombined;
04691         DOUT << "\nReplacing.5 "; DEBUG(N->dump(&DAG));
04692         DOUT << "\nWith: "; DEBUG(Result.getNode()->dump(&DAG));
04693         DOUT << '\n';
04694         WorkListRemover DeadNodes(*this);
04695         if (isLoad) {
04696           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
04697                                         &DeadNodes);
04698           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
04699                                         &DeadNodes);
04700         } else {
04701           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
04702                                         &DeadNodes);
04703         }
04704 
04705         // Finally, since the node is now dead, remove it from the graph.
04706         DAG.DeleteNode(N);
04707 
04708         // Replace the uses of Use with uses of the updated base value.
04709         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
04710                                       Result.getValue(isLoad ? 1 : 0),
04711                                       &DeadNodes);
04712         removeFromWorkList(Op);
04713         DAG.DeleteNode(Op);
04714         return true;
04715       }
04716     }
04717   }
04718 
04719   return false;
04720 }
04721 
04722 /// InferAlignment - If we can infer some alignment information from this
04723 /// pointer, return it.
04724 static unsigned InferAlignment(SDValue Ptr, SelectionDAG &DAG) {
04725   // If this is a direct reference to a stack slot, use information about the
04726   // stack slot's alignment.
04727   int FrameIdx = 1 << 31;
04728   int64_t FrameOffset = 0;
04729   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
04730     FrameIdx = FI->getIndex();
04731   } else if (Ptr.getOpcode() == ISD::ADD && 
04732              isa<ConstantSDNode>(Ptr.getOperand(1)) &&
04733              isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
04734     FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
04735     FrameOffset = Ptr.getConstantOperandVal(1);
04736   }
04737              
04738   if (FrameIdx != (1 << 31)) {
04739     // FIXME: Handle FI+CST.
04740     const MachineFrameInfo &MFI = *DAG.getMachineFunction().getFrameInfo();
04741     if (MFI.isFixedObjectIndex(FrameIdx)) {
04742       int64_t ObjectOffset = MFI.getObjectOffset(FrameIdx) + FrameOffset;
04743 
04744       // The alignment of the frame index can be determined from its offset from
04745       // the incoming frame position.  If the frame object is at offset 32 and
04746       // the stack is guaranteed to be 16-byte aligned, then we know that the
04747       // object is 16-byte aligned.
04748       unsigned StackAlign = DAG.getTarget().getFrameInfo()->getStackAlignment();
04749       unsigned Align = MinAlign(ObjectOffset, StackAlign);
04750       
04751       // Finally, the frame object itself may have a known alignment.  Factor
04752       // the alignment + offset into a new alignment.  For example, if we know
04753       // the  FI is 8 byte aligned, but the pointer is 4 off, we really have a
04754       // 4-byte alignment of the resultant pointer.  Likewise align 4 + 4-byte
04755       // offset = 4-byte alignment, align 4 + 1-byte offset = align 1, etc.
04756       unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx), 
04757                                       FrameOffset);
04758       return std::max(Align, FIInfoAlign);
04759     }
04760   }
04761   
04762   return 0;
04763 }
04764 
04765 SDValue DAGCombiner::visitLOAD(SDNode *N) {
04766   LoadSDNode *LD  = cast<LoadSDNode>(N);
04767   SDValue Chain = LD->getChain();
04768   SDValue Ptr   = LD->getBasePtr();
04769   
04770   // Try to infer better alignment information than the load already has.
04771   if (!Fast && LD->isUnindexed()) {
04772     if (unsigned Align = InferAlignment(Ptr, DAG)) {
04773       if (Align > LD->getAlignment())
04774         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
04775                               LD->getValueType(0),
04776                               Chain, Ptr, LD->getSrcValue(),
04777                               LD->getSrcValueOffset(), LD->getMemoryVT(),
04778                               LD->isVolatile(), Align);
04779     }
04780   }
04781 
04782   // If load is not volatile and there are no uses of the loaded value (and
04783   // the updated indexed value in case of indexed loads), change uses of the
04784   // chain value into uses of the chain input (i.e. delete the dead load).
04785   if (!LD->isVolatile()) {
04786     if (N->getValueType(1) == MVT::Other) {
04787       // Unindexed loads.
04788       if (N->hasNUsesOfValue(0, 0)) {
04789         // It's not safe to use the two value CombineTo variant here. e.g.
04790         // v1, chain2 = load chain1, loc
04791         // v2, chain3 = load chain2, loc
04792         // v3         = add v2, c
04793         // Now we replace use of chain2 with chain1.  This makes the second load
04794         // isomorphic to the one we are deleting, and thus makes this load live.
04795         DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
04796         DOUT << "\nWith chain: "; DEBUG(Chain.getNode()->dump(&DAG));
04797         DOUT << "\n";
04798         WorkListRemover DeadNodes(*this);
04799         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
04800 
04801         if (N->use_empty()) {
04802           removeFromWorkList(N);
04803           DAG.DeleteNode(N);
04804         }
04805 
04806         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04807       }
04808     } else {
04809       // Indexed loads.
04810       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
04811       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
04812         SDValue Undef = DAG.getNode(ISD::UNDEF, N->getDebugLoc(),
04813                                     N->getValueType(0));
04814         DOUT << "\nReplacing.6 "; DEBUG(N->dump(&DAG));
04815         DOUT << "\nWith: "; DEBUG(Undef.getNode()->dump(&DAG));
04816         DOUT << " and 2 other values\n";
04817         WorkListRemover DeadNodes(*this);
04818         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
04819         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
04820                                       DAG.getNode(ISD::UNDEF, N->getDebugLoc(),
04821                                                   N->getValueType(1)),
04822                                       &DeadNodes);
04823         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
04824         removeFromWorkList(N);
04825         DAG.DeleteNode(N);
04826         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
04827       }
04828     }
04829   }
04830   
04831   // If this load is directly stored, replace the load value with the stored
04832   // value.
04833   // TODO: Handle store large -> read small portion.
04834   // TODO: Handle TRUNCSTORE/LOADEXT
04835   if (LD->getExtensionType() == ISD::NON_EXTLOAD &&
04836       !LD->isVolatile()) {
04837     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
04838       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
04839       if (PrevST->getBasePtr() == Ptr &&
04840           PrevST->getValue().getValueType() == N->getValueType(0))
04841       return CombineTo(N, Chain.getOperand(1), Chain);
04842     }
04843   }
04844     
04845   if (CombinerAA) {
04846     // Walk up chain skipping non-aliasing memory nodes.
04847     SDValue BetterChain = FindBetterChain(N, Chain);
04848     
04849     // If there is a better chain.
04850     if (Chain != BetterChain) {
04851       SDValue ReplLoad;
04852 
04853       // Replace the chain to void dependency.
04854       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
04855         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
04856                                BetterChain, Ptr,
04857                                LD->getSrcValue(), LD->getSrcValueOffset(),
04858                                LD->isVolatile(), LD->getAlignment());
04859       } else {
04860         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
04861                                   LD->getValueType(0),
04862                                   BetterChain, Ptr, LD->getSrcValue(),
04863                                   LD->getSrcValueOffset(),
04864                                   LD->getMemoryVT(),
04865                                   LD->isVolatile(), 
04866                                   LD->getAlignment());
04867       }
04868 
04869       // Create token factor to keep old chain connected.
04870       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
04871                                   MVT::Other, Chain, ReplLoad.getValue(1));
04872       
04873       // Replace uses with load result and token factor. Don't add users
04874       // to work list.
04875       return CombineTo(N, ReplLoad.getValue(0), Token, false);
04876     }
04877   }
04878 
04879   // Try transforming N to an indexed load.
04880   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
04881     return SDValue(N, 0);
04882 
04883   return SDValue();
04884 }
04885 
04886 SDValue DAGCombiner::visitSTORE(SDNode *N) {
04887   StoreSDNode *ST  = cast<StoreSDNode>(N);
04888   SDValue Chain = ST->getChain();
04889   SDValue Value = ST->getValue();
04890   SDValue Ptr   = ST->getBasePtr();
04891   
04892   // Try to infer better alignment information than the store already has.
04893   if (!Fast && ST->isUnindexed()) {
04894     if (unsigned Align = InferAlignment(Ptr, DAG)) {
04895       if (Align > ST->getAlignment())
04896         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
04897                                  Ptr, ST->getSrcValue(),
04898                                  ST->getSrcValueOffset(), ST->getMemoryVT(),
04899                                  ST->isVolatile(), Align);
04900     }
04901   }
04902 
04903   // If this is a store of a bit convert, store the input value if the
04904   // resultant store does not need a higher alignment than the original.
04905   if (Value.getOpcode() == ISD::BIT_CONVERT && !ST->isTruncatingStore() &&
04906       ST->isUnindexed()) {
04907     unsigned Align = ST->getAlignment();
04908     MVT SVT = Value.getOperand(0).getValueType();
04909     unsigned OrigAlign = TLI.getTargetData()->
04910       getABITypeAlignment(SVT.getTypeForMVT());
04911     if (Align <= OrigAlign &&
04912         ((!LegalOperations && !ST->isVolatile()) ||
04913          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
04914       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
04915                           Ptr, ST->getSrcValue(),
04916                           ST->getSrcValueOffset(), ST->isVolatile(), OrigAlign);
04917   }
04918 
04919   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
04920   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
04921     // NOTE: If the original store is volatile, this transform must not increase
04922     // the number of stores.  For example, on x86-32 an f64 can be stored in one
04923     // processor operation but an i64 (which is not legal) requires two.  So the
04924     // transform should not be done in this case.
04925     if (Value.getOpcode() != ISD::TargetConstantFP) {
04926       SDValue Tmp;
04927       switch (CFP->getValueType(0).getSimpleVT()) {
04928       default: assert(0 && "Unknown FP type");
04929       case MVT::f80:    // We don't do this for these yet.
04930       case MVT::f128:
04931       case MVT::ppcf128:
04932         break;
04933       case MVT::f32:
04934         if (((TLI.isTypeLegal(MVT::i32) || !LegalTypes) && !LegalOperations &&
04935              !ST->isVolatile()) ||
04936             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
04937           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
04938                               bitcastToAPInt().getZExtValue(), MVT::i32);
04939           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
04940                               Ptr, ST->getSrcValue(),
04941                               ST->getSrcValueOffset(), ST->isVolatile(),
04942                               ST->getAlignment());
04943         }
04944         break;
04945       case MVT::f64:
04946         if (((TLI.isTypeLegal(MVT::i64) || !LegalTypes) && !LegalOperations &&
04947              !ST->isVolatile()) ||
04948             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
04949           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
04950                                 getZExtValue(), MVT::i64);
04951           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
04952                               Ptr, ST->getSrcValue(),
04953                               ST->getSrcValueOffset(), ST->isVolatile(),
04954                               ST->getAlignment());
04955         } else if (!ST->isVolatile() &&
04956                    TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
04957           // Many FP stores are not made apparent until after legalize, e.g. for
04958           // argument passing.  Since this is so common, custom legalize the
04959           // 64-bit integer store into two 32-bit stores.
04960           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
04961           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
04962           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
04963           if (TLI.isBigEndian()) std::swap(Lo, Hi);
04964 
04965           int SVOffset = ST->getSrcValueOffset();
04966           unsigned Alignment = ST->getAlignment();
04967           bool isVolatile = ST->isVolatile();
04968 
04969           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
04970                                      Ptr, ST->getSrcValue(),
04971                                      ST->getSrcValueOffset(),
04972                                      isVolatile, ST->getAlignment());
04973           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
04974                             DAG.getConstant(4, Ptr.getValueType()));
04975           SVOffset += 4;
04976           Alignment = MinAlign(Alignment, 4U);
04977           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
04978                                      Ptr, ST->getSrcValue(),
04979                                      SVOffset, isVolatile, Alignment);
04980           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
04981                              St0, St1);
04982         }
04983 
04984         break;
04985       }
04986     }
04987   }
04988 
04989   if (CombinerAA) { 
04990     // Walk up chain skipping non-aliasing memory nodes.
04991     SDValue BetterChain = FindBetterChain(N, Chain);
04992     
04993     // If there is a better chain.
04994     if (Chain != BetterChain) {
04995       // Replace the chain to avoid dependency.
04996       SDValue ReplStore;
04997       if (ST->isTruncatingStore()) {
04998         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
04999                                       ST->getSrcValue(),ST->getSrcValueOffset(),
05000                                       ST->getMemoryVT(),
05001                                       ST->isVolatile(), ST->getAlignment());
05002       } else {
05003         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
05004                                  ST->getSrcValue(), ST->getSrcValueOffset(),
05005                                  ST->isVolatile(), ST->getAlignment());
05006       }
05007       
05008       // Create token to keep both nodes around.
05009       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
05010                                   MVT::Other, Chain, ReplStore);
05011 
05012       // Don't add users to work list.
05013       return CombineTo(N, Token, false);
05014     }
05015   }
05016   
05017   // Try transforming N to an indexed store.
05018   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
05019     return SDValue(N, 0);
05020 
05021   // FIXME: is there such a thing as a truncating indexed store?
05022   if (ST->isTruncatingStore() && ST->isUnindexed() &&
05023       Value.getValueType().isInteger()) {
05024     // See if we can simplify the input to this truncstore with knowledge that
05025     // only the low bits are being used.  For example:
05026     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
05027     SDValue Shorter = 
05028       GetDemandedBits(Value,
05029                       APInt::getLowBitsSet(Value.getValueSizeInBits(),
05030                                            ST->getMemoryVT().getSizeInBits()));
05031     AddToWorkList(Value.getNode());
05032     if (Shorter.getNode())
05033       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
05034                                Ptr, ST->getSrcValue(),
05035                                ST->getSrcValueOffset(), ST->getMemoryVT(),
05036                                ST->isVolatile(), ST->getAlignment());
05037     
05038     // Otherwise, see if we can simplify the operation with
05039     // SimplifyDemandedBits, which only works if the value has a single use.
05040     if (SimplifyDemandedBits(Value,
05041                              APInt::getLowBitsSet(
05042                                Value.getValueSizeInBits(),
05043                                ST->getMemoryVT().getSizeInBits())))
05044       return SDValue(N, 0);
05045   }
05046   
05047   // If this is a load followed by a store to the same location, then the store
05048   // is dead/noop.
05049   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
05050     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
05051         ST->isUnindexed() && !ST->isVolatile() &&
05052         // There can't be any side effects between the load and store, such as
05053         // a call or store.
05054         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
05055       // The store is dead, remove it.
05056       return Chain;
05057     }
05058   }
05059 
05060   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
05061   // truncating store.  We can do this even if this is already a truncstore.
05062   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
05063       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
05064       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
05065                             ST->getMemoryVT())) {
05066     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
05067                              Ptr, ST->getSrcValue(),
05068                              ST->getSrcValueOffset(), ST->getMemoryVT(),
05069                              ST->isVolatile(), ST->getAlignment());
05070   }
05071 
05072   return SDValue();
05073 }
05074 
05075 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
05076   SDValue InVec = N->getOperand(0);
05077   SDValue InVal = N->getOperand(1);
05078   SDValue EltNo = N->getOperand(2);
05079   
05080   // If the invec is a BUILD_VECTOR and if EltNo is a constant, build a new
05081   // vector with the inserted element.
05082   if (InVec.getOpcode() == ISD::BUILD_VECTOR && isa<ConstantSDNode>(EltNo)) {
05083     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
05084     SmallVector<SDValue, 8> Ops(InVec.getNode()->op_begin(),
05085                                 InVec.getNode()->op_end());
05086     if (Elt < Ops.size())
05087       Ops[Elt] = InVal;
05088     return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05089                        InVec.getValueType(), &Ops[0], Ops.size());
05090   }
05091   
05092   return SDValue();
05093 }
05094 
05095 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
05096   // (vextract (scalar_to_vector val, 0) -> val
05097   SDValue InVec = N->getOperand(0);
05098 
05099  if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR)
05100    return InVec.getOperand(0);
05101 
05102   // Perform only after legalization to ensure build_vector / vector_shuffle
05103   // optimizations have already been done.
05104   if (!LegalOperations) return SDValue();
05105 
05106   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
05107   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
05108   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
05109   SDValue EltNo = N->getOperand(1);
05110 
05111   if (isa<ConstantSDNode>(EltNo)) {
05112     unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
05113     bool NewLoad = false;
05114     bool BCNumEltsChanged = false;
05115     MVT VT = InVec.getValueType();
05116     MVT EVT = VT.getVectorElementType();
05117     MVT LVT = EVT;
05118 
05119     if (InVec.getOpcode() == ISD::BIT_CONVERT) {
05120       MVT BCVT = InVec.getOperand(0).getValueType();
05121       if (!BCVT.isVector() || EVT.bitsGT(BCVT.getVectorElementType()))
05122         return SDValue();
05123       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
05124         BCNumEltsChanged = true;
05125       InVec = InVec.getOperand(0);
05126       EVT = BCVT.getVectorElementType();
05127       NewLoad = true;
05128     }
05129 
05130     LoadSDNode *LN0 = NULL;
05131     if (ISD::isNormalLoad(InVec.getNode())) {
05132       LN0 = cast<LoadSDNode>(InVec);
05133     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
05134                InVec.getOperand(0).getValueType() == EVT &&
05135                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
05136       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
05137     } else if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE) {
05138       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
05139       // =>
05140       // (load $addr+1*size)
05141       
05142       // If the bit convert changed the number of elements, it is unsafe
05143       // to examine the mask.
05144       if (BCNumEltsChanged)
05145         return SDValue();
05146       unsigned Idx = cast<ConstantSDNode>(InVec.getOperand(2).
05147                                           getOperand(Elt))->getZExtValue();
05148       unsigned NumElems = InVec.getOperand(2).getNumOperands();
05149       InVec = (Idx < NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
05150       if (InVec.getOpcode() == ISD::BIT_CONVERT)
05151         InVec = InVec.getOperand(0);
05152       if (ISD::isNormalLoad(InVec.getNode())) {
05153         LN0 = cast<LoadSDNode>(InVec);
05154         Elt = (Idx < NumElems) ? Idx : Idx - NumElems;
05155       }
05156     }
05157 
05158     if (!LN0 || !LN0->hasOneUse() || LN0->isVolatile())
05159       return SDValue();
05160 
05161     unsigned Align = LN0->getAlignment();
05162     if (NewLoad) {
05163       // Check the resultant load doesn't need a higher alignment than the
05164       // original load.
05165       unsigned NewAlign =
05166         TLI.getTargetData()->getABITypeAlignment(LVT.getTypeForMVT());
05167 
05168       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
05169         return SDValue();
05170 
05171       Align = NewAlign;
05172     }
05173 
05174     SDValue NewPtr = LN0->getBasePtr();
05175     if (Elt) {
05176       unsigned PtrOff = LVT.getSizeInBits() * Elt / 8;
05177       MVT PtrType = NewPtr.getValueType();
05178       if (TLI.isBigEndian())
05179         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
05180       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
05181                            DAG.getConstant(PtrOff, PtrType));
05182     }
05183 
05184     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
05185                        LN0->getSrcValue(), LN0->getSrcValueOffset(),
05186                        LN0->isVolatile(), Align);
05187   }
05188 
05189   return SDValue();
05190 }
05191 
05192 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
05193   unsigned NumInScalars = N->getNumOperands();
05194   MVT VT = N->getValueType(0);
05195   unsigned NumElts = VT.getVectorNumElements();
05196   MVT EltType = VT.getVectorElementType();
05197 
05198   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
05199   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
05200   // at most two distinct vectors, turn this into a shuffle node.
05201   SDValue VecIn1, VecIn2;
05202   for (unsigned i = 0; i != NumInScalars; ++i) {
05203     // Ignore undef inputs.
05204     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
05205     
05206     // If this input is something other than a EXTRACT_VECTOR_ELT with a
05207     // constant index, bail out.
05208     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
05209         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
05210       VecIn1 = VecIn2 = SDValue(0, 0);
05211       break;
05212     }
05213     
05214     // If the input vector type disagrees with the result of the build_vector,
05215     // we can't make a shuffle.
05216     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
05217     if (ExtractedFromVec.getValueType() != VT) {
05218       VecIn1 = VecIn2 = SDValue(0, 0);
05219       break;
05220     }
05221     
05222     // Otherwise, remember this.  We allow up to two distinct input vectors.
05223     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
05224       continue;
05225     
05226     if (VecIn1.getNode() == 0) {
05227       VecIn1 = ExtractedFromVec;
05228     } else if (VecIn2.getNode() == 0) {
05229       VecIn2 = ExtractedFromVec;
05230     } else {
05231       // Too many inputs.
05232       VecIn1 = VecIn2 = SDValue(0, 0);
05233       break;
05234     }
05235   }
05236   
05237   // If everything is good, we can make a shuffle operation.
05238   if (VecIn1.getNode()) {
05239     SmallVector<SDValue, 8> BuildVecIndices;
05240     for (unsigned i = 0; i != NumInScalars; ++i) {
05241       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
05242         BuildVecIndices.push_back(DAG.getNode(ISD::UNDEF,
05243                                               N->getDebugLoc(),
05244                                               TLI.getPointerTy()));
05245         continue;
05246       }
05247       
05248       SDValue Extract = N->getOperand(i);
05249       
05250       // If extracting from the first vector, just use the index directly.
05251       if (Extract.getOperand(0) == VecIn1) {
05252         BuildVecIndices.push_back(Extract.getOperand(1));
05253         continue;
05254       }
05255 
05256       // Otherwise, use InIdx + VecSize
05257       unsigned Idx =
05258         cast<ConstantSDNode>(Extract.getOperand(1))->getZExtValue();
05259       BuildVecIndices.push_back(DAG.getIntPtrConstant(Idx+NumInScalars));
05260     }
05261     
05262     // Add count and size info.
05263     MVT BuildVecVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
05264     if (!TLI.isTypeLegal(BuildVecVT) && LegalTypes)
05265       return SDValue();
05266 
05267     // Return the new VECTOR_SHUFFLE node.
05268     SDValue Ops[5];
05269     Ops[0] = VecIn1;
05270     if (VecIn2.getNode()) {
05271       Ops[1] = VecIn2;
05272     } else {
05273       // Use an undef build_vector as input for the second operand.
05274       std::vector<SDValue> UnOps(NumInScalars,
05275                                  DAG.getNode(ISD::UNDEF, N->getDebugLoc(),
05276                                              EltType));
05277       Ops[1] = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
05278                            &UnOps[0], UnOps.size());
05279       AddToWorkList(Ops[1].getNode());
05280     }
05281 
05282     Ops[2] = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), BuildVecVT,
05283                          &BuildVecIndices[0], BuildVecIndices.size());
05284     return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getDebugLoc(), VT, Ops, 3);
05285   }
05286   
05287   return SDValue();
05288 }
05289 
05290 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
05291   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
05292   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
05293   // inputs come from at most two distinct vectors, turn this into a shuffle
05294   // node.
05295 
05296   // If we only have one input vector, we don't need to do any concatenation.
05297   if (N->getNumOperands() == 1)
05298     return N->getOperand(0);
05299 
05300   return SDValue();
05301 }
05302 
05303 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
05304   SDValue ShufMask = N->getOperand(2);
05305   unsigned NumElts = ShufMask.getNumOperands();
05306 
05307   SDValue N0 = N->getOperand(0);
05308   SDValue N1 = N->getOperand(1);
05309 
05310   assert(N0.getValueType().getVectorNumElements() == NumElts &&
05311         "Vector shuffle must be normalized in DAG");
05312 
05313   // If the shuffle mask is an identity operation on the LHS, return the LHS.
05314   bool isIdentity = true;
05315   for (unsigned i = 0; i != NumElts; ++i) {
05316     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
05317         cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() != i) {
05318       isIdentity = false;
05319       break;
05320     }
05321   }
05322   if (isIdentity) return N->getOperand(0);
05323 
05324   // If the shuffle mask is an identity operation on the RHS, return the RHS.
05325   isIdentity = true;
05326   for (unsigned i = 0; i != NumElts; ++i) {
05327     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF &&
05328         cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() !=
05329           i+NumElts) {
05330       isIdentity = false;
05331       break;
05332     }
05333   }
05334   if (isIdentity) return N->getOperand(1);
05335 
05336   // Check if the shuffle is a unary shuffle, i.e. one of the vectors is not
05337   // needed at all.
05338   bool isUnary = true;
05339   bool isSplat = true;
05340   int VecNum = -1;
05341   unsigned BaseIdx = 0;
05342   for (unsigned i = 0; i != NumElts; ++i)
05343     if (ShufMask.getOperand(i).getOpcode() != ISD::UNDEF) {
05344       unsigned Idx=cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue();
05345       int V = (Idx < NumElts) ? 0 : 1;
05346       if (VecNum == -1) {
05347         VecNum = V;
05348         BaseIdx = Idx;
05349       } else {
05350         if (BaseIdx != Idx)
05351           isSplat = false;
05352         if (VecNum != V) {
05353           isUnary = false;
05354           break;
05355         }
05356       }
05357     }
05358 
05359   // Normalize unary shuffle so the RHS is undef.
05360   if (isUnary && VecNum == 1)
05361     std::swap(N0, N1);
05362 
05363   // If it is a splat, check if the argument vector is a build_vector with
05364   // all scalar elements the same.
05365   if (isSplat) {
05366     SDNode *V = N0.getNode();
05367 
05368     // If this is a bit convert that changes the element type of the vector but
05369     // not the number of vector elements, look through it.  Be careful not to
05370     // look though conversions that change things like v4f32 to v2f64.
05371     if (V->getOpcode() == ISD::BIT_CONVERT) {
05372       SDValue ConvInput = V->getOperand(0);
05373       if (ConvInput.getValueType().isVector() &&
05374           ConvInput.getValueType().getVectorNumElements() == NumElts)
05375         V = ConvInput.getNode();
05376     }
05377 
05378     if (V->getOpcode() == ISD::BUILD_VECTOR) {
05379       unsigned NumElems = V->getNumOperands();
05380       if (NumElems > BaseIdx) {
05381         SDValue Base;
05382         bool AllSame = true;
05383         for (unsigned i = 0; i != NumElems; ++i) {
05384           if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
05385             Base = V->getOperand(i);
05386             break;
05387           }
05388         }
05389         // Splat of <u, u, u, u>, return <u, u, u, u>
05390         if (!Base.getNode())
05391           return N0;
05392         for (unsigned i = 0; i != NumElems; ++i) {
05393           if (V->getOperand(i) != Base) {
05394             AllSame = false;
05395             break;
05396           }
05397         }
05398         // Splat of <x, x, x, x>, return <x, x, x, x>
05399         if (AllSame)
05400           return N0;
05401       }
05402     }
05403   }
05404 
05405   // If it is a unary or the LHS and the RHS are the same node, turn the RHS
05406   // into an undef.
05407   if (isUnary || N0 == N1) {
05408     // Check the SHUFFLE mask, mapping any inputs from the 2nd operand into the
05409     // first operand.
05410     SmallVector<SDValue, 8> MappedOps;
05411 
05412     for (unsigned i = 0; i != NumElts; ++i) {
05413       if (ShufMask.getOperand(i).getOpcode() == ISD::UNDEF ||
05414           cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() <
05415             NumElts) {
05416         MappedOps.push_back(ShufMask.getOperand(i));
05417       } else {
05418         unsigned NewIdx = 
05419           cast<ConstantSDNode>(ShufMask.getOperand(i))->getZExtValue() -
05420           NumElts;
05421         MappedOps.push_back(DAG.getConstant(NewIdx,
05422                                         ShufMask.getOperand(i).getValueType()));
05423       }
05424     }
05425 
05426     ShufMask = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05427                            ShufMask.getValueType(),
05428                            &MappedOps[0], MappedOps.size());
05429     AddToWorkList(ShufMask.getNode());
05430     return DAG.getNode(ISD::VECTOR_SHUFFLE, N->getDebugLoc(),
05431                        N->getValueType(0), N0,
05432                        DAG.getNode(ISD::UNDEF, N->getDebugLoc(),
05433                                    N->getValueType(0)),
05434                        ShufMask);
05435   }
05436  
05437   return SDValue();
05438 }
05439 
05440 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
05441 /// an AND to a vector_shuffle with the destination vector and a zero vector.
05442 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
05443 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
05444 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
05445   SDValue LHS = N->getOperand(0);
05446   SDValue RHS = N->getOperand(1);
05447   if (N->getOpcode() == ISD::AND) {
05448     if (RHS.getOpcode() == ISD::BIT_CONVERT)
05449       RHS = RHS.getOperand(0);
05450     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
05451       std::vector<SDValue> IdxOps;
05452       unsigned NumOps = RHS.getNumOperands();
05453       unsigned NumElts = NumOps;
05454       for (unsigned i = 0; i != NumElts; ++i) {
05455         SDValue Elt = RHS.getOperand(i);
05456         if (!isa<ConstantSDNode>(Elt))
05457           return SDValue();
05458         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
05459           IdxOps.push_back(DAG.getIntPtrConstant(i));
05460         else if (cast<ConstantSDNode>(Elt)->isNullValue())
05461           IdxOps.push_back(DAG.getIntPtrConstant(NumElts));
05462         else
05463           return SDValue();
05464       }
05465 
05466       // Let's see if the target supports this vector_shuffle.
05467       if (!TLI.isVectorClearMaskLegal(IdxOps, TLI.getPointerTy(), DAG))
05468         return SDValue();
05469 
05470       // Return the new VECTOR_SHUFFLE node.
05471       MVT EVT = RHS.getValueType().getVectorElementType();
05472       MVT VT = MVT::getVectorVT(EVT, NumElts);
05473       MVT MaskVT = MVT::getVectorVT(TLI.getPointerTy(), NumElts);
05474       std::vector<SDValue> Ops;
05475       LHS = DAG.getNode(ISD::BIT_CONVERT, LHS.getDebugLoc(), VT, LHS);
05476       Ops.push_back(LHS);
05477       AddToWorkList(LHS.getNode());
05478       std::vector<SDValue> ZeroOps(NumElts, DAG.getConstant(0, EVT));
05479       Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05480                                 VT, &ZeroOps[0], ZeroOps.size()));
05481       Ops.push_back(DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
05482                                 MaskVT, &IdxOps[0], IdxOps.size()));
05483       SDValue Result = DAG.getNode(ISD::VECTOR_SHUFFLE, N->getDebugLoc(),
05484                                    VT, &Ops[0], Ops.size());
05485 
05486       if (VT != N->getValueType(0))
05487         Result = DAG.getNode(ISD::BIT_CONVERT, N->getDebugLoc(),
05488                              N->getValueType(0), Result);
05489 
05490       return Result;
05491     }
05492   }
05493 
05494   return SDValue();
05495 }
05496 
05497 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
05498 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
05499   // After legalize, the target may be depending on adds and other
05500   // binary ops to provide legal ways to construct constants or other
05501   // things. Simplifying them may result in a loss of legality.
05502   if (LegalOperations) return SDValue();
05503 
05504   MVT VT = N->getValueType(0);
05505   assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
05506 
05507   MVT EltType = VT.getVectorElementType();
05508   SDValue LHS = N->getOperand(0);
05509   SDValue RHS = N->getOperand(1);
05510   SDValue Shuffle = XformToShuffleWithZero(N);
05511   if (Shuffle.getNode()) return Shuffle;
05512 
05513   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
05514   // this operation.
05515   if (LHS.getOpcode() == ISD::BUILD_VECTOR && 
05516       RHS.getOpcode() == ISD::BUILD_VECTOR) {
05517     SmallVector<SDValue, 8> Ops;
05518     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
05519       SDValue LHSOp = LHS.getOperand(i);
05520       SDValue RHSOp = RHS.getOperand(i);
05521       // If these two elements can't be folded, bail out.
05522       if ((LHSOp.getOpcode() != ISD::UNDEF &&
05523            LHSOp.getOpcode() != ISD::Constant &&
05524            LHSOp.getOpcode() != ISD::ConstantFP) ||
05525           (RHSOp.getOpcode() != ISD::UNDEF &&
05526            RHSOp.getOpcode() != ISD::Constant &&
05527            RHSOp.getOpcode() != ISD::ConstantFP))
05528         break;
05529 
05530       // Can't fold divide by zero.
05531       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
05532           N->getOpcode() == ISD::FDIV) {
05533         if ((RHSOp.getOpcode() == ISD::Constant &&
05534              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
05535             (RHSOp.getOpcode() == ISD::ConstantFP &&
05536              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
05537           break;
05538       }
05539 
05540       Ops.push_back(DAG.getNode(N->getOpcode(), LHS.getDebugLoc(),
05541                                 EltType, LHSOp, RHSOp));
05542       AddToWorkList(Ops.back().getNode());
05543       assert((Ops.back().getOpcode() == ISD::UNDEF ||
05544               Ops.back().getOpcode() == ISD::Constant ||
05545               Ops.back().getOpcode() == ISD::ConstantFP) &&
05546              "Scalar binop didn't fold!");
05547     }
05548     
05549     if (Ops.size() == LHS.getNumOperands()) {
05550       MVT VT = LHS.getValueType();
05551       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
05552                          &Ops[0], Ops.size());
05553     }
05554   }
05555   
05556   return SDValue();
05557 }
05558 
05559 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
05560                                     SDValue N1, SDValue N2){
05561   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
05562   
05563   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
05564                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
05565 
05566   // If we got a simplified select_cc node back from SimplifySelectCC, then
05567   // break it down into a new SETCC node, and a new SELECT node, and then return
05568   // the SELECT node, since we were called with a SELECT node.
05569   if (SCC.getNode()) {
05570     // Check to see if we got a select_cc back (to turn into setcc/select).
05571     // Otherwise, just return whatever node we got back, like fabs.
05572     if (SCC.getOpcode() == ISD::SELECT_CC) {
05573       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
05574                                   N0.getValueType(),
05575                                   SCC.getOperand(0), SCC.getOperand(1), 
05576                                   SCC.getOperand(4));
05577       AddToWorkList(SETCC.getNode());
05578       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
05579                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
05580     }
05581 
05582     return SCC;
05583   }
05584   return SDValue();
05585 }
05586 
05587 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
05588 /// are the two values being selected between, see if we can simplify the
05589 /// select.  Callers of this should assume that TheSelect is deleted if this
05590 /// returns true.  As such, they should return the appropriate thing (e.g. the
05591 /// node) back to the top-level of the DAG combiner loop to avoid it being
05592 /// looked at.
05593 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS, 
05594                                     SDValue RHS) {
05595   
05596   // If this is a select from two identical things, try to pull the operation
05597   // through the select.
05598   if (LHS.getOpcode() == RHS.getOpcode() && LHS.hasOneUse() && RHS.hasOneUse()){
05599     // If this is a load and the token chain is identical, replace the select
05600     // of two loads with a load through a select of the address to load from.
05601     // This triggers in things like "select bool X, 10.0, 123.0" after the FP
05602     // constants have been dropped into the constant pool.
05603     if (LHS.getOpcode() == ISD::LOAD &&
05604         // Do not let this transformation reduce the number of volatile loads.
05605         !cast<LoadSDNode>(LHS)->isVolatile() &&
05606         !cast<LoadSDNode>(RHS)->isVolatile() &&
05607         // Token chains must be identical.
05608         LHS.getOperand(0) == RHS.getOperand(0)) {
05609       LoadSDNode *LLD = cast<LoadSDNode>(LHS);
05610       LoadSDNode *RLD = cast<LoadSDNode>(RHS);
05611 
05612       // If this is an EXTLOAD, the VT's must match.
05613       if (LLD->getMemoryVT() == RLD->getMemoryVT()) {
05614         // FIXME: this conflates two src values, discarding one.  This is not
05615         // the right thing to do, but nothing uses srcvalues now.  When they do,
05616         // turn SrcValue into a list of locations.
05617         SDValue Addr;
05618         if (TheSelect->getOpcode() == ISD::SELECT) {
05619           // Check that the condition doesn't reach either load.  If so, folding
05620           // this will induce a cycle into the DAG.
05621           if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05622               !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode())) {
05623             Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
05624                                LLD->getBasePtr().getValueType(),
05625                                TheSelect->getOperand(0), LLD->getBasePtr(),
05626                                RLD->getBasePtr());
05627           }
05628         } else {
05629           // Check that the condition doesn't reach either load.  If so, folding
05630           // this will induce a cycle into the DAG.
05631           if (!LLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05632               !RLD->isPredecessorOf(TheSelect->getOperand(0).getNode()) &&
05633               !LLD->isPredecessorOf(TheSelect->getOperand(1).getNode()) &&
05634               !RLD->isPredecessorOf(TheSelect->getOperand(1).getNode())) {
05635             Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
05636                                LLD->getBasePtr().getValueType(),
05637                                TheSelect->getOperand(0),
05638                                TheSelect->getOperand(1), 
05639                                LLD->getBasePtr(), RLD->getBasePtr(),
05640                                TheSelect->getOperand(4));
05641           }
05642         }
05643         
05644         if (Addr.getNode()) {
05645           SDValue Load;
05646           if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
05647             Load = DAG.getLoad(TheSelect->getValueType(0),
05648                                TheSelect->getDebugLoc(),
05649                                LLD->getChain(),
05650                                Addr,LLD->getSrcValue(), 
05651                                LLD->getSrcValueOffset(),
05652                                LLD->isVolatile(), 
05653                                LLD->getAlignment());
05654           } else {
05655             Load = DAG.getExtLoad(LLD->getExtensionType(),
05656                                   TheSelect->getDebugLoc(),
05657                                   TheSelect->getValueType(0),
05658                                   LLD->getChain(), Addr, LLD->getSrcValue(),
05659                                   LLD->getSrcValueOffset(),
05660                                   LLD->getMemoryVT(),
05661                                   LLD->isVolatile(), 
05662                                   LLD->getAlignment());
05663           }
05664 
05665           // Users of the select now use the result of the load.
05666           CombineTo(TheSelect, Load);
05667         
05668           // Users of the old loads now use the new load's chain.  We know the
05669           // old-load value is dead now.
05670           CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
05671           CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
05672           return true;
05673         }
05674       }
05675     }
05676   }
05677   
05678   return false;
05679 }
05680 
05681 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, 
05682                                       SDValue N2, SDValue N3,
05683                                       ISD::CondCode CC, bool NotExtCompare) {
05684   MVT VT = N2.getValueType();
05685   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
05686   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
05687   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
05688 
05689   // Determine if the condition we're dealing with is constant
05690   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
05691                               N0, N1, CC, DL, false);
05692   if (SCC.getNode()) AddToWorkList(SCC.getNode());
05693   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
05694 
05695   // fold select_cc true, x, y -> x
05696   if (SCCC && !SCCC->isNullValue())
05697     return N2;
05698   // fold select_cc false, x, y -> y
05699   if (SCCC && SCCC->isNullValue())
05700     return N3;
05701   
05702   // Check to see if we can simplify the select into an fabs node
05703   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
05704     // Allow either -0.0 or 0.0
05705     if (CFP->getValueAPF().isZero()) {
05706       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
05707       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
05708           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
05709           N2 == N3.getOperand(0))
05710         return DAG.getNode(ISD::FABS, DL, VT, N0);
05711       
05712       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
05713       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
05714           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
05715           N2.getOperand(0) == N3)
05716         return DAG.getNode(ISD::FABS, DL, VT, N3);
05717     }
05718   }
05719   
05720   // Check to see if we can perform the "gzip trick", transforming
05721   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
05722   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
05723       N0.getValueType().isInteger() &&
05724       N2.getValueType().isInteger() &&
05725       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
05726        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
05727     MVT XType = N0.getValueType();
05728     MVT AType = N2.getValueType();
05729     if (XType.bitsGE(AType)) {
05730       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
05731       // single-bit constant.
05732       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
05733         unsigned ShCtV = N2C->getAPIntValue().logBase2();
05734         ShCtV = XType.getSizeInBits()-ShCtV-1;
05735         SDValue ShCt = DAG.getConstant(ShCtV, getShiftAmountTy());
05736         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
05737                                     XType, N0, ShCt);
05738         AddToWorkList(Shift.getNode());
05739 
05740         if (XType.bitsGT(AType)) {
05741           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
05742           AddToWorkList(Shift.getNode());
05743         }
05744 
05745         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
05746       }
05747 
05748       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
05749                                   XType, N0,
05750                                   DAG.getConstant(XType.getSizeInBits()-1,
05751                                                   getShiftAmountTy()));
05752       AddToWorkList(Shift.getNode());
05753 
05754       if (XType.bitsGT(AType)) {
05755         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
05756         AddToWorkList(Shift.getNode());
05757       }
05758 
05759       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
05760     }
05761   }
05762   
05763   // fold select C, 16, 0 -> shl C, 4
05764   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
05765       TLI.getBooleanContents() == TargetLowering::ZeroOrOneBooleanContent) {
05766     
05767     // If the caller doesn't want us to simplify this into a zext of a compare,
05768     // don't do it.
05769     if (NotExtCompare && N2C->getAPIntValue() == 1)
05770       return SDValue();
05771     
05772     // Get a SetCC of the condition
05773     // FIXME: Should probably make sure that setcc is legal if we ever have a
05774     // target where it isn't.
05775     SDValue Temp, SCC;
05776     // cast from setcc result type to select result type
05777     if (LegalTypes) {
05778       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
05779                           N0, N1, CC);
05780       if (N2.getValueType().bitsLT(SCC.getValueType()))
05781         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
05782       else
05783         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
05784                            N2.getValueType(), SCC);
05785     } else {
05786       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
05787       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
05788                          N2.getValueType(), SCC);
05789     }
05790 
05791     AddToWorkList(SCC.getNode());
05792     AddToWorkList(Temp.getNode());
05793     
05794     if (N2C->getAPIntValue() == 1)
05795       return Temp;
05796 
05797     // shl setcc result by log2 n2c
05798     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
05799                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
05800                                        getShiftAmountTy()));
05801   }
05802     
05803   // Check to see if this is the equivalent of setcc
05804   // FIXME: Turn all of these into setcc if setcc if setcc is legal
05805   // otherwise, go ahead with the folds.
05806   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
05807     MVT XType = N0.getValueType();
05808     if (!LegalOperations ||
05809         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
05810       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
05811       if (Res.getValueType() != VT)
05812         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
05813       return Res;
05814     }
05815     
05816     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
05817     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ && 
05818         (!LegalOperations ||
05819          TLI.isOperationLegal(ISD::CTLZ, XType))) {
05820       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
05821       return DAG.getNode(ISD::SRL, DL, XType, Ctlz, 
05822                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
05823                                          getShiftAmountTy()));
05824     }
05825     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
05826     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) { 
05827       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
05828                                   XType, DAG.getConstant(0, XType), N0);
05829       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
05830       return DAG.getNode(ISD::SRL, DL, XType,
05831                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
05832                          DAG.getConstant(XType.getSizeInBits()-1,
05833                                          getShiftAmountTy()));
05834     }
05835     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
05836     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
05837       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
05838                                  DAG.getConstant(XType.getSizeInBits()-1,
05839                                                  getShiftAmountTy()));
05840       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
05841     }
05842   }
05843   
05844   // Check to see if this is an integer abs. select_cc setl[te] X, 0, -X, X ->
05845   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
05846   if (N1C && N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE) &&
05847       N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1) &&
05848       N2.getOperand(0) == N1 && N0.getValueType().isInteger()) {
05849     MVT XType = N0.getValueType();
05850     SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType, N0,
05851                                 DAG.getConstant(XType.getSizeInBits()-1,
05852                                                 getShiftAmountTy()));
05853     SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(), XType,
05854                               N0, Shift);
05855     AddToWorkList(Shift.getNode());
05856     AddToWorkList(Add.getNode());
05857     return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
05858   }
05859   // Check to see if this is an integer abs. select_cc setgt X, -1, X, -X ->
05860   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
05861   if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT &&
05862       N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1)) {
05863     if (ConstantSDNode *SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0))) {
05864       MVT XType = N0.getValueType();
05865       if (SubC->isNullValue() && XType.isInteger()) {
05866         SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
05867                                     N0,
05868                                     DAG.getConstant(XType.getSizeInBits()-1,
05869                                                     getShiftAmountTy()));
05870         SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
05871                                   XType, N0, Shift);
05872         AddToWorkList(Shift.getNode());
05873         AddToWorkList(Add.getNode());
05874         return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
05875       }
05876     }
05877   }
05878   
05879   return SDValue();
05880 }
05881 
05882 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
05883 SDValue DAGCombiner::SimplifySetCC(MVT VT, SDValue N0,
05884                                    SDValue N1, ISD::CondCode Cond,
05885                                    DebugLoc DL, bool foldBooleans) {
05886   TargetLowering::DAGCombinerInfo 
05887     DagCombineInfo(DAG, Level == Unrestricted, false, this);
05888   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
05889 }
05890 
05891 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
05892 /// return a DAG expression to select that will generate the same value by
05893 /// multiplying by a magic number.  See:
05894 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
05895 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
05896   std::vector<SDNode*> Built;
05897   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
05898 
05899   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
05900        ii != ee; ++ii)
05901     AddToWorkList(*ii);
05902   return S;
05903 }
05904 
05905 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
05906 /// return a DAG expression to select that will generate the same value by
05907 /// multiplying by a magic number.  See:
05908 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
05909 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
05910   std::vector<SDNode*> Built;
05911   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
05912 
05913   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
05914        ii != ee; ++ii)
05915     AddToWorkList(*ii);
05916   return S;
05917 }
05918 
05919 /// FindBaseOffset - Return true if base is known not to alias with anything
05920 /// but itself.  Provides base object and offset as results.
05921 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset) {
05922   // Assume it is a primitive operation.
05923   Base = Ptr; Offset = 0;
05924   
05925   // If it's an adding a simple constant then integrate the offset.
05926   if (Base.getOpcode() == ISD::ADD) {
05927     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
05928       Base = Base.getOperand(0);
05929       Offset += C->getZExtValue();
05930     }
05931   }
05932   
05933   // If it's any of the following then it can't alias with anything but itself.
05934   return isa<FrameIndexSDNode>(Base) ||
05935          isa<ConstantPoolSDNode>(Base) ||
05936          isa<GlobalAddressSDNode>(Base);
05937 }
05938 
05939 /// isAlias - Return true if there is any possibility that the two addresses
05940 /// overlap.
05941 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
05942                           const Value *SrcValue1, int SrcValueOffset1,
05943                           SDValue Ptr2, int64_t Size2,
05944                           const Value *SrcValue2, int SrcValueOffset2) const {
05945   // If they are the same then they must be aliases.
05946   if (Ptr1 == Ptr2) return true;
05947   
05948   // Gather base node and offset information.
05949   SDValue Base1, Base2;
05950   int64_t Offset1, Offset2;
05951   bool KnownBase1 = FindBaseOffset(Ptr1, Base1, Offset1);
05952   bool KnownBase2 = FindBaseOffset(Ptr2, Base2, Offset2);
05953   
05954   // If they have a same base address then...
05955   if (Base1 == Base2)
05956     // Check to see if the addresses overlap.
05957     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
05958   
05959   // If we know both bases then they can't alias.
05960   if (KnownBase1 && KnownBase2) return false;
05961 
05962   if (CombinerGlobalAA) {
05963     // Use alias analysis information.
05964     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
05965     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
05966     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
05967     AliasAnalysis::AliasResult AAResult = 
05968                              AA.alias(SrcValue1, Overlap1, SrcValue2, Overlap2);
05969     if (AAResult == AliasAnalysis::NoAlias)
05970       return false;
05971   }
05972 
05973   // Otherwise we have to assume they alias.
05974   return true;
05975 }
05976 
05977 /// FindAliasInfo - Extracts the relevant alias information from the memory
05978 /// node.  Returns true if the operand was a load.
05979 bool DAGCombiner::FindAliasInfo(SDNode *N,
05980                         SDValue &Ptr, int64_t &Size,
05981                         const Value *&SrcValue, int &SrcValueOffset) const {
05982   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
05983     Ptr = LD->getBasePtr();
05984     Size = LD->getMemoryVT().getSizeInBits() >> 3;
05985     SrcValue = LD->getSrcValue();
05986     SrcValueOffset = LD->getSrcValueOffset();
05987     return true;
05988   } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
05989     Ptr = ST->getBasePtr();
05990     Size = ST->getMemoryVT().getSizeInBits() >> 3;
05991     SrcValue = ST->getSrcValue();
05992     SrcValueOffset = ST->getSrcValueOffset();
05993   } else {
05994     assert(0 && "FindAliasInfo expected a memory operand");
05995   }
05996   
05997   return false;
05998 }
05999 
06000 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
06001 /// looking for aliasing nodes and adding them to the Aliases vector.
06002 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
06003                                    SmallVector<SDValue, 8> &Aliases) {
06004   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
06005   std::set<SDNode *> Visited;           // Visited node set.
06006   
06007   // Get alias information for node.
06008   SDValue Ptr;
06009   int64_t Size;
06010   const Value *SrcValue;
06011   int SrcValueOffset;
06012   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset);
06013 
06014   // Starting off.
06015   Chains.push_back(OriginalChain);
06016   
06017   // Look at each chain and determine if it is an alias.  If so, add it to the
06018   // aliases list.  If not, then continue up the chain looking for the next
06019   // candidate.  
06020   while (!Chains.empty()) {
06021     SDValue Chain = Chains.back();
06022     Chains.pop_back();
06023     
06024      // Don't bother if we've been before.
06025     if (Visited.find(Chain.getNode()) != Visited.end()) continue;
06026     Visited.insert(Chain.getNode());
06027   
06028     switch (Chain.getOpcode()) {
06029     case ISD::EntryToken:
06030       // Entry token is ideal chain operand, but handled in FindBetterChain.
06031       break;
06032       
06033     case ISD::LOAD:
06034     case ISD::STORE: {
06035       // Get alias information for Chain.
06036       SDValue OpPtr;
06037       int64_t OpSize;
06038       const Value *OpSrcValue;
06039       int OpSrcValueOffset;
06040       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
06041                                     OpSrcValue, OpSrcValueOffset);
06042       
06043       // If chain is alias then stop here.
06044       if (!(IsLoad && IsOpLoad) &&
06045           isAlias(Ptr, Size, SrcValue, SrcValueOffset,
06046                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset)) {
06047         Aliases.push_back(Chain);
06048       } else {
06049         // Look further up the chain.
06050         Chains.push_back(Chain.getOperand(0));      
06051         // Clean up old chain.
06052         AddToWorkList(Chain.getNode());
06053       }
06054       break;
06055     }
06056     
06057     case ISD::TokenFactor:
06058       // We have to check each of the operands of the token factor, so we queue
06059       // then up.  Adding the  operands to the queue (stack) in reverse order
06060       // maintains the original order and increases the likelihood that getNode
06061       // will find a matching token factor (CSE.)
06062       for (unsigned n = Chain.getNumOperands(); n;)
06063         Chains.push_back(Chain.getOperand(--n));
06064       // Eliminate the token factor if we can.
06065       AddToWorkList(Chain.getNode());
06066       break;
06067       
06068     default:
06069       // For all other instructions we will just have to take what we can get.
06070       Aliases.push_back(Chain);
06071       break;
06072     }
06073   }
06074 }
06075 
06076 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
06077 /// for a better chain (aliasing node.)
06078 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
06079   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
06080   
06081   // Accumulate all the aliases to this node.
06082   GatherAllAliases(N, OldChain, Aliases);
06083   
06084   if (Aliases.size() == 0) {
06085     // If no operands then chain to entry token.
06086     return DAG.getEntryNode();
06087   } else if (Aliases.size() == 1) {
06088     // If a single operand then chain to it.  We don't need to revisit it.
06089     return Aliases[0];
06090   }
06091 
06092   // Construct a custom tailored token factor.
06093   SDValue NewChain = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
06094                                  &Aliases[0], Aliases.size());
06095 
06096   // Make sure the old chain gets cleaned up.
06097   if (NewChain != OldChain) AddToWorkList(OldChain.getNode());
06098   
06099   return NewChain;
06100 }
06101 
06102 // SelectionDAG::Combine - This is the entry point for the file.
06103 //
06104 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA, bool Fast) {
06105   /// run - This is the main entry point to this class.
06106   ///
06107   DAGCombiner(*this, AA, Fast).Run(Level);
06108 }