Home | History | Annotate | Download | only in SelectionDAG
      1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
     11 // both before and after the DAG is legalized.
     12 //
     13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
     14 // primarily intended to handle simplification opportunities that are implicit
     15 // in the LLVM IR and exposed by the various codegen lowering phases.
     16 //
     17 //===----------------------------------------------------------------------===//
     18 
     19 #define DEBUG_TYPE "dagcombine"
     20 #include "llvm/CodeGen/SelectionDAG.h"
     21 #include "llvm/DerivedTypes.h"
     22 #include "llvm/LLVMContext.h"
     23 #include "llvm/CodeGen/MachineFunction.h"
     24 #include "llvm/CodeGen/MachineFrameInfo.h"
     25 #include "llvm/CodeGen/PseudoSourceValue.h"
     26 #include "llvm/Analysis/AliasAnalysis.h"
     27 #include "llvm/Target/TargetData.h"
     28 #include "llvm/Target/TargetLowering.h"
     29 #include "llvm/Target/TargetMachine.h"
     30 #include "llvm/Target/TargetOptions.h"
     31 #include "llvm/ADT/SmallPtrSet.h"
     32 #include "llvm/ADT/Statistic.h"
     33 #include "llvm/Support/CommandLine.h"
     34 #include "llvm/Support/Debug.h"
     35 #include "llvm/Support/ErrorHandling.h"
     36 #include "llvm/Support/MathExtras.h"
     37 #include "llvm/Support/raw_ostream.h"
     38 #include <algorithm>
     39 using namespace llvm;
     40 
     41 STATISTIC(NodesCombined   , "Number of dag nodes combined");
     42 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
     43 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
     44 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
     45 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
     46 
     47 namespace {
     48   static cl::opt<bool>
     49     CombinerAA("combiner-alias-analysis", cl::Hidden,
     50                cl::desc("Turn on alias analysis during testing"));
     51 
     52   static cl::opt<bool>
     53     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
     54                cl::desc("Include global information in alias analysis"));
     55 
     56 //------------------------------ DAGCombiner ---------------------------------//
     57 
     58   class DAGCombiner {
     59     SelectionDAG &DAG;
     60     const TargetLowering &TLI;
     61     CombineLevel Level;
     62     CodeGenOpt::Level OptLevel;
     63     bool LegalOperations;
     64     bool LegalTypes;
     65 
     66     // Worklist of all of the nodes that need to be simplified.
     67     std::vector<SDNode*> WorkList;
     68 
     69     // AA - Used for DAG load/store alias analysis.
     70     AliasAnalysis &AA;
     71 
     72     /// AddUsersToWorkList - When an instruction is simplified, add all users of
     73     /// the instruction to the work lists because they might get more simplified
     74     /// now.
     75     ///
     76     void AddUsersToWorkList(SDNode *N) {
     77       for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
     78            UI != UE; ++UI)
     79         AddToWorkList(*UI);
     80     }
     81 
     82     /// visit - call the node-specific routine that knows how to fold each
     83     /// particular type of node.
     84     SDValue visit(SDNode *N);
     85 
     86   public:
     87     /// AddToWorkList - Add to the work list making sure it's instance is at the
     88     /// the back (next to be processed.)
     89     void AddToWorkList(SDNode *N) {
     90       removeFromWorkList(N);
     91       WorkList.push_back(N);
     92     }
     93 
     94     /// removeFromWorkList - remove all instances of N from the worklist.
     95     ///
     96     void removeFromWorkList(SDNode *N) {
     97       WorkList.erase(std::remove(WorkList.begin(), WorkList.end(), N),
     98                      WorkList.end());
     99     }
    100 
    101     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
    102                       bool AddTo = true);
    103 
    104     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
    105       return CombineTo(N, &Res, 1, AddTo);
    106     }
    107 
    108     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
    109                       bool AddTo = true) {
    110       SDValue To[] = { Res0, Res1 };
    111       return CombineTo(N, To, 2, AddTo);
    112     }
    113 
    114     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
    115 
    116   private:
    117 
    118     /// SimplifyDemandedBits - Check the specified integer node value to see if
    119     /// it can be simplified or if things it uses can be simplified by bit
    120     /// propagation.  If so, return true.
    121     bool SimplifyDemandedBits(SDValue Op) {
    122       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
    123       APInt Demanded = APInt::getAllOnesValue(BitWidth);
    124       return SimplifyDemandedBits(Op, Demanded);
    125     }
    126 
    127     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
    128 
    129     bool CombineToPreIndexedLoadStore(SDNode *N);
    130     bool CombineToPostIndexedLoadStore(SDNode *N);
    131 
    132     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
    133     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
    134     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
    135     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
    136     SDValue PromoteIntBinOp(SDValue Op);
    137     SDValue PromoteIntShiftOp(SDValue Op);
    138     SDValue PromoteExtend(SDValue Op);
    139     bool PromoteLoad(SDValue Op);
    140 
    141     void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
    142                          SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
    143                          ISD::NodeType ExtType);
    144 
    145     /// combine - call the node-specific routine that knows how to fold each
    146     /// particular type of node. If that doesn't do anything, try the
    147     /// target-specific DAG combines.
    148     SDValue combine(SDNode *N);
    149 
    150     // Visitation implementation - Implement dag node combining for different
    151     // node types.  The semantics are as follows:
    152     // Return Value:
    153     //   SDValue.getNode() == 0 - No change was made
    154     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
    155     //   otherwise              - N should be replaced by the returned Operand.
    156     //
    157     SDValue visitTokenFactor(SDNode *N);
    158     SDValue visitMERGE_VALUES(SDNode *N);
    159     SDValue visitADD(SDNode *N);
    160     SDValue visitSUB(SDNode *N);
    161     SDValue visitADDC(SDNode *N);
    162     SDValue visitADDE(SDNode *N);
    163     SDValue visitMUL(SDNode *N);
    164     SDValue visitSDIV(SDNode *N);
    165     SDValue visitUDIV(SDNode *N);
    166     SDValue visitSREM(SDNode *N);
    167     SDValue visitUREM(SDNode *N);
    168     SDValue visitMULHU(SDNode *N);
    169     SDValue visitMULHS(SDNode *N);
    170     SDValue visitSMUL_LOHI(SDNode *N);
    171     SDValue visitUMUL_LOHI(SDNode *N);
    172     SDValue visitSMULO(SDNode *N);
    173     SDValue visitUMULO(SDNode *N);
    174     SDValue visitSDIVREM(SDNode *N);
    175     SDValue visitUDIVREM(SDNode *N);
    176     SDValue visitAND(SDNode *N);
    177     SDValue visitOR(SDNode *N);
    178     SDValue visitXOR(SDNode *N);
    179     SDValue SimplifyVBinOp(SDNode *N);
    180     SDValue visitSHL(SDNode *N);
    181     SDValue visitSRA(SDNode *N);
    182     SDValue visitSRL(SDNode *N);
    183     SDValue visitCTLZ(SDNode *N);
    184     SDValue visitCTTZ(SDNode *N);
    185     SDValue visitCTPOP(SDNode *N);
    186     SDValue visitSELECT(SDNode *N);
    187     SDValue visitSELECT_CC(SDNode *N);
    188     SDValue visitSETCC(SDNode *N);
    189     SDValue visitSIGN_EXTEND(SDNode *N);
    190     SDValue visitZERO_EXTEND(SDNode *N);
    191     SDValue visitANY_EXTEND(SDNode *N);
    192     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
    193     SDValue visitTRUNCATE(SDNode *N);
    194     SDValue visitBITCAST(SDNode *N);
    195     SDValue visitBUILD_PAIR(SDNode *N);
    196     SDValue visitFADD(SDNode *N);
    197     SDValue visitFSUB(SDNode *N);
    198     SDValue visitFMUL(SDNode *N);
    199     SDValue visitFDIV(SDNode *N);
    200     SDValue visitFREM(SDNode *N);
    201     SDValue visitFCOPYSIGN(SDNode *N);
    202     SDValue visitSINT_TO_FP(SDNode *N);
    203     SDValue visitUINT_TO_FP(SDNode *N);
    204     SDValue visitFP_TO_SINT(SDNode *N);
    205     SDValue visitFP_TO_UINT(SDNode *N);
    206     SDValue visitFP_ROUND(SDNode *N);
    207     SDValue visitFP_ROUND_INREG(SDNode *N);
    208     SDValue visitFP_EXTEND(SDNode *N);
    209     SDValue visitFNEG(SDNode *N);
    210     SDValue visitFABS(SDNode *N);
    211     SDValue visitBRCOND(SDNode *N);
    212     SDValue visitBR_CC(SDNode *N);
    213     SDValue visitLOAD(SDNode *N);
    214     SDValue visitSTORE(SDNode *N);
    215     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
    216     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
    217     SDValue visitBUILD_VECTOR(SDNode *N);
    218     SDValue visitCONCAT_VECTORS(SDNode *N);
    219     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
    220     SDValue visitVECTOR_SHUFFLE(SDNode *N);
    221     SDValue visitMEMBARRIER(SDNode *N);
    222 
    223     SDValue XformToShuffleWithZero(SDNode *N);
    224     SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
    225 
    226     SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
    227 
    228     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
    229     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
    230     SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
    231     SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
    232                              SDValue N3, ISD::CondCode CC,
    233                              bool NotExtCompare = false);
    234     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
    235                           DebugLoc DL, bool foldBooleans = true);
    236     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
    237                                          unsigned HiOp);
    238     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
    239     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
    240     SDValue BuildSDIV(SDNode *N);
    241     SDValue BuildUDIV(SDNode *N);
    242     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
    243                                bool DemandHighBits = true);
    244     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
    245     SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
    246     SDValue ReduceLoadWidth(SDNode *N);
    247     SDValue ReduceLoadOpStoreWidth(SDNode *N);
    248     SDValue TransformFPLoadStorePair(SDNode *N);
    249 
    250     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
    251 
    252     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
    253     /// looking for aliasing nodes and adding them to the Aliases vector.
    254     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
    255                           SmallVector<SDValue, 8> &Aliases);
    256 
    257     /// isAlias - Return true if there is any possibility that the two addresses
    258     /// overlap.
    259     bool isAlias(SDValue Ptr1, int64_t Size1,
    260                  const Value *SrcValue1, int SrcValueOffset1,
    261                  unsigned SrcValueAlign1,
    262                  const MDNode *TBAAInfo1,
    263                  SDValue Ptr2, int64_t Size2,
    264                  const Value *SrcValue2, int SrcValueOffset2,
    265                  unsigned SrcValueAlign2,
    266                  const MDNode *TBAAInfo2) const;
    267 
    268     /// FindAliasInfo - Extracts the relevant alias information from the memory
    269     /// node.  Returns true if the operand was a load.
    270     bool FindAliasInfo(SDNode *N,
    271                        SDValue &Ptr, int64_t &Size,
    272                        const Value *&SrcValue, int &SrcValueOffset,
    273                        unsigned &SrcValueAlignment,
    274                        const MDNode *&TBAAInfo) const;
    275 
    276     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
    277     /// looking for a better chain (aliasing node.)
    278     SDValue FindBetterChain(SDNode *N, SDValue Chain);
    279 
    280   public:
    281     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
    282       : DAG(D), TLI(D.getTargetLoweringInfo()), Level(Unrestricted),
    283         OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
    284 
    285     /// Run - runs the dag combiner on all nodes in the work list
    286     void Run(CombineLevel AtLevel);
    287 
    288     SelectionDAG &getDAG() const { return DAG; }
    289 
    290     /// getShiftAmountTy - Returns a type large enough to hold any valid
    291     /// shift amount - before type legalization these can be huge.
    292     EVT getShiftAmountTy(EVT LHSTy) {
    293       return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
    294     }
    295 
    296     /// isTypeLegal - This method returns true if we are running before type
    297     /// legalization or if the specified VT is legal.
    298     bool isTypeLegal(const EVT &VT) {
    299       if (!LegalTypes) return true;
    300       return TLI.isTypeLegal(VT);
    301     }
    302   };
    303 }
    304 
    305 
    306 namespace {
    307 /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
    308 /// nodes from the worklist.
    309 class WorkListRemover : public SelectionDAG::DAGUpdateListener {
    310   DAGCombiner &DC;
    311 public:
    312   explicit WorkListRemover(DAGCombiner &dc) : DC(dc) {}
    313 
    314   virtual void NodeDeleted(SDNode *N, SDNode *E) {
    315     DC.removeFromWorkList(N);
    316   }
    317 
    318   virtual void NodeUpdated(SDNode *N) {
    319     // Ignore updates.
    320   }
    321 };
    322 }
    323 
    324 //===----------------------------------------------------------------------===//
    325 //  TargetLowering::DAGCombinerInfo implementation
    326 //===----------------------------------------------------------------------===//
    327 
    328 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
    329   ((DAGCombiner*)DC)->AddToWorkList(N);
    330 }
    331 
    332 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
    333   ((DAGCombiner*)DC)->removeFromWorkList(N);
    334 }
    335 
    336 SDValue TargetLowering::DAGCombinerInfo::
    337 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
    338   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
    339 }
    340 
    341 SDValue TargetLowering::DAGCombinerInfo::
    342 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
    343   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
    344 }
    345 
    346 
    347 SDValue TargetLowering::DAGCombinerInfo::
    348 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
    349   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
    350 }
    351 
    352 void TargetLowering::DAGCombinerInfo::
    353 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
    354   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
    355 }
    356 
    357 //===----------------------------------------------------------------------===//
    358 // Helper Functions
    359 //===----------------------------------------------------------------------===//
    360 
    361 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
    362 /// specified expression for the same cost as the expression itself, or 2 if we
    363 /// can compute the negated form more cheaply than the expression itself.
    364 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
    365                                unsigned Depth = 0) {
    366   // No compile time optimizations on this type.
    367   if (Op.getValueType() == MVT::ppcf128)
    368     return 0;
    369 
    370   // fneg is removable even if it has multiple uses.
    371   if (Op.getOpcode() == ISD::FNEG) return 2;
    372 
    373   // Don't allow anything with multiple uses.
    374   if (!Op.hasOneUse()) return 0;
    375 
    376   // Don't recurse exponentially.
    377   if (Depth > 6) return 0;
    378 
    379   switch (Op.getOpcode()) {
    380   default: return false;
    381   case ISD::ConstantFP:
    382     // Don't invert constant FP values after legalize.  The negated constant
    383     // isn't necessarily legal.
    384     return LegalOperations ? 0 : 1;
    385   case ISD::FADD:
    386     // FIXME: determine better conditions for this xform.
    387     if (!UnsafeFPMath) return 0;
    388 
    389     // fold (fsub (fadd A, B)) -> (fsub (fneg A), B)
    390     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
    391       return V;
    392     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
    393     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
    394   case ISD::FSUB:
    395     // We can't turn -(A-B) into B-A when we honor signed zeros.
    396     if (!UnsafeFPMath) return 0;
    397 
    398     // fold (fneg (fsub A, B)) -> (fsub B, A)
    399     return 1;
    400 
    401   case ISD::FMUL:
    402   case ISD::FDIV:
    403     if (HonorSignDependentRoundingFPMath()) return 0;
    404 
    405     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
    406     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
    407       return V;
    408 
    409     return isNegatibleForFree(Op.getOperand(1), LegalOperations, Depth+1);
    410 
    411   case ISD::FP_EXTEND:
    412   case ISD::FP_ROUND:
    413   case ISD::FSIN:
    414     return isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1);
    415   }
    416 }
    417 
    418 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
    419 /// returns the newly negated expression.
    420 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
    421                                     bool LegalOperations, unsigned Depth = 0) {
    422   // fneg is removable even if it has multiple uses.
    423   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
    424 
    425   // Don't allow anything with multiple uses.
    426   assert(Op.hasOneUse() && "Unknown reuse!");
    427 
    428   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
    429   switch (Op.getOpcode()) {
    430   default: llvm_unreachable("Unknown code");
    431   case ISD::ConstantFP: {
    432     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
    433     V.changeSign();
    434     return DAG.getConstantFP(V, Op.getValueType());
    435   }
    436   case ISD::FADD:
    437     // FIXME: determine better conditions for this xform.
    438     assert(UnsafeFPMath);
    439 
    440     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
    441     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
    442       return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
    443                          GetNegatedExpression(Op.getOperand(0), DAG,
    444                                               LegalOperations, Depth+1),
    445                          Op.getOperand(1));
    446     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
    447     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
    448                        GetNegatedExpression(Op.getOperand(1), DAG,
    449                                             LegalOperations, Depth+1),
    450                        Op.getOperand(0));
    451   case ISD::FSUB:
    452     // We can't turn -(A-B) into B-A when we honor signed zeros.
    453     assert(UnsafeFPMath);
    454 
    455     // fold (fneg (fsub 0, B)) -> B
    456     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
    457       if (N0CFP->getValueAPF().isZero())
    458         return Op.getOperand(1);
    459 
    460     // fold (fneg (fsub A, B)) -> (fsub B, A)
    461     return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
    462                        Op.getOperand(1), Op.getOperand(0));
    463 
    464   case ISD::FMUL:
    465   case ISD::FDIV:
    466     assert(!HonorSignDependentRoundingFPMath());
    467 
    468     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
    469     if (isNegatibleForFree(Op.getOperand(0), LegalOperations, Depth+1))
    470       return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
    471                          GetNegatedExpression(Op.getOperand(0), DAG,
    472                                               LegalOperations, Depth+1),
    473                          Op.getOperand(1));
    474 
    475     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
    476     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
    477                        Op.getOperand(0),
    478                        GetNegatedExpression(Op.getOperand(1), DAG,
    479                                             LegalOperations, Depth+1));
    480 
    481   case ISD::FP_EXTEND:
    482   case ISD::FSIN:
    483     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
    484                        GetNegatedExpression(Op.getOperand(0), DAG,
    485                                             LegalOperations, Depth+1));
    486   case ISD::FP_ROUND:
    487       return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
    488                          GetNegatedExpression(Op.getOperand(0), DAG,
    489                                               LegalOperations, Depth+1),
    490                          Op.getOperand(1));
    491   }
    492 }
    493 
    494 
    495 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
    496 // that selects between the values 1 and 0, making it equivalent to a setcc.
    497 // Also, set the incoming LHS, RHS, and CC references to the appropriate
    498 // nodes based on the type of node we are checking.  This simplifies life a
    499 // bit for the callers.
    500 static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
    501                               SDValue &CC) {
    502   if (N.getOpcode() == ISD::SETCC) {
    503     LHS = N.getOperand(0);
    504     RHS = N.getOperand(1);
    505     CC  = N.getOperand(2);
    506     return true;
    507   }
    508   if (N.getOpcode() == ISD::SELECT_CC &&
    509       N.getOperand(2).getOpcode() == ISD::Constant &&
    510       N.getOperand(3).getOpcode() == ISD::Constant &&
    511       cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
    512       cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
    513     LHS = N.getOperand(0);
    514     RHS = N.getOperand(1);
    515     CC  = N.getOperand(4);
    516     return true;
    517   }
    518   return false;
    519 }
    520 
    521 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
    522 // one use.  If this is true, it allows the users to invert the operation for
    523 // free when it is profitable to do so.
    524 static bool isOneUseSetCC(SDValue N) {
    525   SDValue N0, N1, N2;
    526   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
    527     return true;
    528   return false;
    529 }
    530 
    531 SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
    532                                     SDValue N0, SDValue N1) {
    533   EVT VT = N0.getValueType();
    534   if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
    535     if (isa<ConstantSDNode>(N1)) {
    536       // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
    537       SDValue OpNode =
    538         DAG.FoldConstantArithmetic(Opc, VT,
    539                                    cast<ConstantSDNode>(N0.getOperand(1)),
    540                                    cast<ConstantSDNode>(N1));
    541       return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
    542     }
    543     if (N0.hasOneUse()) {
    544       // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
    545       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
    546                                    N0.getOperand(0), N1);
    547       AddToWorkList(OpNode.getNode());
    548       return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
    549     }
    550   }
    551 
    552   if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
    553     if (isa<ConstantSDNode>(N0)) {
    554       // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
    555       SDValue OpNode =
    556         DAG.FoldConstantArithmetic(Opc, VT,
    557                                    cast<ConstantSDNode>(N1.getOperand(1)),
    558                                    cast<ConstantSDNode>(N0));
    559       return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
    560     }
    561     if (N1.hasOneUse()) {
    562       // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
    563       SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
    564                                    N1.getOperand(0), N0);
    565       AddToWorkList(OpNode.getNode());
    566       return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
    567     }
    568   }
    569 
    570   return SDValue();
    571 }
    572 
    573 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
    574                                bool AddTo) {
    575   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
    576   ++NodesCombined;
    577   DEBUG(dbgs() << "\nReplacing.1 ";
    578         N->dump(&DAG);
    579         dbgs() << "\nWith: ";
    580         To[0].getNode()->dump(&DAG);
    581         dbgs() << " and " << NumTo-1 << " other values\n";
    582         for (unsigned i = 0, e = NumTo; i != e; ++i)
    583           assert((!To[i].getNode() ||
    584                   N->getValueType(i) == To[i].getValueType()) &&
    585                  "Cannot combine value to value of different type!"));
    586   WorkListRemover DeadNodes(*this);
    587   DAG.ReplaceAllUsesWith(N, To, &DeadNodes);
    588 
    589   if (AddTo) {
    590     // Push the new nodes and any users onto the worklist
    591     for (unsigned i = 0, e = NumTo; i != e; ++i) {
    592       if (To[i].getNode()) {
    593         AddToWorkList(To[i].getNode());
    594         AddUsersToWorkList(To[i].getNode());
    595       }
    596     }
    597   }
    598 
    599   // Finally, if the node is now dead, remove it from the graph.  The node
    600   // may not be dead if the replacement process recursively simplified to
    601   // something else needing this node.
    602   if (N->use_empty()) {
    603     // Nodes can be reintroduced into the worklist.  Make sure we do not
    604     // process a node that has been replaced.
    605     removeFromWorkList(N);
    606 
    607     // Finally, since the node is now dead, remove it from the graph.
    608     DAG.DeleteNode(N);
    609   }
    610   return SDValue(N, 0);
    611 }
    612 
    613 void DAGCombiner::
    614 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
    615   // Replace all uses.  If any nodes become isomorphic to other nodes and
    616   // are deleted, make sure to remove them from our worklist.
    617   WorkListRemover DeadNodes(*this);
    618   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New, &DeadNodes);
    619 
    620   // Push the new node and any (possibly new) users onto the worklist.
    621   AddToWorkList(TLO.New.getNode());
    622   AddUsersToWorkList(TLO.New.getNode());
    623 
    624   // Finally, if the node is now dead, remove it from the graph.  The node
    625   // may not be dead if the replacement process recursively simplified to
    626   // something else needing this node.
    627   if (TLO.Old.getNode()->use_empty()) {
    628     removeFromWorkList(TLO.Old.getNode());
    629 
    630     // If the operands of this node are only used by the node, they will now
    631     // be dead.  Make sure to visit them first to delete dead nodes early.
    632     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
    633       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
    634         AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
    635 
    636     DAG.DeleteNode(TLO.Old.getNode());
    637   }
    638 }
    639 
    640 /// SimplifyDemandedBits - Check the specified integer node value to see if
    641 /// it can be simplified or if things it uses can be simplified by bit
    642 /// propagation.  If so, return true.
    643 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
    644   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
    645   APInt KnownZero, KnownOne;
    646   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
    647     return false;
    648 
    649   // Revisit the node.
    650   AddToWorkList(Op.getNode());
    651 
    652   // Replace the old value with the new one.
    653   ++NodesCombined;
    654   DEBUG(dbgs() << "\nReplacing.2 ";
    655         TLO.Old.getNode()->dump(&DAG);
    656         dbgs() << "\nWith: ";
    657         TLO.New.getNode()->dump(&DAG);
    658         dbgs() << '\n');
    659 
    660   CommitTargetLoweringOpt(TLO);
    661   return true;
    662 }
    663 
    664 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
    665   DebugLoc dl = Load->getDebugLoc();
    666   EVT VT = Load->getValueType(0);
    667   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
    668 
    669   DEBUG(dbgs() << "\nReplacing.9 ";
    670         Load->dump(&DAG);
    671         dbgs() << "\nWith: ";
    672         Trunc.getNode()->dump(&DAG);
    673         dbgs() << '\n');
    674   WorkListRemover DeadNodes(*this);
    675   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc, &DeadNodes);
    676   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1),
    677                                 &DeadNodes);
    678   removeFromWorkList(Load);
    679   DAG.DeleteNode(Load);
    680   AddToWorkList(Trunc.getNode());
    681 }
    682 
    683 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
    684   Replace = false;
    685   DebugLoc dl = Op.getDebugLoc();
    686   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
    687     EVT MemVT = LD->getMemoryVT();
    688     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
    689       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
    690                                                   : ISD::EXTLOAD)
    691       : LD->getExtensionType();
    692     Replace = true;
    693     return DAG.getExtLoad(ExtType, dl, PVT,
    694                           LD->getChain(), LD->getBasePtr(),
    695                           LD->getPointerInfo(),
    696                           MemVT, LD->isVolatile(),
    697                           LD->isNonTemporal(), LD->getAlignment());
    698   }
    699 
    700   unsigned Opc = Op.getOpcode();
    701   switch (Opc) {
    702   default: break;
    703   case ISD::AssertSext:
    704     return DAG.getNode(ISD::AssertSext, dl, PVT,
    705                        SExtPromoteOperand(Op.getOperand(0), PVT),
    706                        Op.getOperand(1));
    707   case ISD::AssertZext:
    708     return DAG.getNode(ISD::AssertZext, dl, PVT,
    709                        ZExtPromoteOperand(Op.getOperand(0), PVT),
    710                        Op.getOperand(1));
    711   case ISD::Constant: {
    712     unsigned ExtOpc =
    713       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
    714     return DAG.getNode(ExtOpc, dl, PVT, Op);
    715   }
    716   }
    717 
    718   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
    719     return SDValue();
    720   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
    721 }
    722 
    723 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
    724   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
    725     return SDValue();
    726   EVT OldVT = Op.getValueType();
    727   DebugLoc dl = Op.getDebugLoc();
    728   bool Replace = false;
    729   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
    730   if (NewOp.getNode() == 0)
    731     return SDValue();
    732   AddToWorkList(NewOp.getNode());
    733 
    734   if (Replace)
    735     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
    736   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
    737                      DAG.getValueType(OldVT));
    738 }
    739 
    740 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
    741   EVT OldVT = Op.getValueType();
    742   DebugLoc dl = Op.getDebugLoc();
    743   bool Replace = false;
    744   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
    745   if (NewOp.getNode() == 0)
    746     return SDValue();
    747   AddToWorkList(NewOp.getNode());
    748 
    749   if (Replace)
    750     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
    751   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
    752 }
    753 
    754 /// PromoteIntBinOp - Promote the specified integer binary operation if the
    755 /// target indicates it is beneficial. e.g. On x86, it's usually better to
    756 /// promote i16 operations to i32 since i16 instructions are longer.
    757 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
    758   if (!LegalOperations)
    759     return SDValue();
    760 
    761   EVT VT = Op.getValueType();
    762   if (VT.isVector() || !VT.isInteger())
    763     return SDValue();
    764 
    765   // If operation type is 'undesirable', e.g. i16 on x86, consider
    766   // promoting it.
    767   unsigned Opc = Op.getOpcode();
    768   if (TLI.isTypeDesirableForOp(Opc, VT))
    769     return SDValue();
    770 
    771   EVT PVT = VT;
    772   // Consult target whether it is a good idea to promote this operation and
    773   // what's the right type to promote it to.
    774   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
    775     assert(PVT != VT && "Don't know what type to promote to!");
    776 
    777     bool Replace0 = false;
    778     SDValue N0 = Op.getOperand(0);
    779     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
    780     if (NN0.getNode() == 0)
    781       return SDValue();
    782 
    783     bool Replace1 = false;
    784     SDValue N1 = Op.getOperand(1);
    785     SDValue NN1;
    786     if (N0 == N1)
    787       NN1 = NN0;
    788     else {
    789       NN1 = PromoteOperand(N1, PVT, Replace1);
    790       if (NN1.getNode() == 0)
    791         return SDValue();
    792     }
    793 
    794     AddToWorkList(NN0.getNode());
    795     if (NN1.getNode())
    796       AddToWorkList(NN1.getNode());
    797 
    798     if (Replace0)
    799       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
    800     if (Replace1)
    801       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
    802 
    803     DEBUG(dbgs() << "\nPromoting ";
    804           Op.getNode()->dump(&DAG));
    805     DebugLoc dl = Op.getDebugLoc();
    806     return DAG.getNode(ISD::TRUNCATE, dl, VT,
    807                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
    808   }
    809   return SDValue();
    810 }
    811 
    812 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
    813 /// target indicates it is beneficial. e.g. On x86, it's usually better to
    814 /// promote i16 operations to i32 since i16 instructions are longer.
    815 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
    816   if (!LegalOperations)
    817     return SDValue();
    818 
    819   EVT VT = Op.getValueType();
    820   if (VT.isVector() || !VT.isInteger())
    821     return SDValue();
    822 
    823   // If operation type is 'undesirable', e.g. i16 on x86, consider
    824   // promoting it.
    825   unsigned Opc = Op.getOpcode();
    826   if (TLI.isTypeDesirableForOp(Opc, VT))
    827     return SDValue();
    828 
    829   EVT PVT = VT;
    830   // Consult target whether it is a good idea to promote this operation and
    831   // what's the right type to promote it to.
    832   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
    833     assert(PVT != VT && "Don't know what type to promote to!");
    834 
    835     bool Replace = false;
    836     SDValue N0 = Op.getOperand(0);
    837     if (Opc == ISD::SRA)
    838       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
    839     else if (Opc == ISD::SRL)
    840       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
    841     else
    842       N0 = PromoteOperand(N0, PVT, Replace);
    843     if (N0.getNode() == 0)
    844       return SDValue();
    845 
    846     AddToWorkList(N0.getNode());
    847     if (Replace)
    848       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
    849 
    850     DEBUG(dbgs() << "\nPromoting ";
    851           Op.getNode()->dump(&DAG));
    852     DebugLoc dl = Op.getDebugLoc();
    853     return DAG.getNode(ISD::TRUNCATE, dl, VT,
    854                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
    855   }
    856   return SDValue();
    857 }
    858 
    859 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
    860   if (!LegalOperations)
    861     return SDValue();
    862 
    863   EVT VT = Op.getValueType();
    864   if (VT.isVector() || !VT.isInteger())
    865     return SDValue();
    866 
    867   // If operation type is 'undesirable', e.g. i16 on x86, consider
    868   // promoting it.
    869   unsigned Opc = Op.getOpcode();
    870   if (TLI.isTypeDesirableForOp(Opc, VT))
    871     return SDValue();
    872 
    873   EVT PVT = VT;
    874   // Consult target whether it is a good idea to promote this operation and
    875   // what's the right type to promote it to.
    876   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
    877     assert(PVT != VT && "Don't know what type to promote to!");
    878     // fold (aext (aext x)) -> (aext x)
    879     // fold (aext (zext x)) -> (zext x)
    880     // fold (aext (sext x)) -> (sext x)
    881     DEBUG(dbgs() << "\nPromoting ";
    882           Op.getNode()->dump(&DAG));
    883     return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
    884   }
    885   return SDValue();
    886 }
    887 
    888 bool DAGCombiner::PromoteLoad(SDValue Op) {
    889   if (!LegalOperations)
    890     return false;
    891 
    892   EVT VT = Op.getValueType();
    893   if (VT.isVector() || !VT.isInteger())
    894     return false;
    895 
    896   // If operation type is 'undesirable', e.g. i16 on x86, consider
    897   // promoting it.
    898   unsigned Opc = Op.getOpcode();
    899   if (TLI.isTypeDesirableForOp(Opc, VT))
    900     return false;
    901 
    902   EVT PVT = VT;
    903   // Consult target whether it is a good idea to promote this operation and
    904   // what's the right type to promote it to.
    905   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
    906     assert(PVT != VT && "Don't know what type to promote to!");
    907 
    908     DebugLoc dl = Op.getDebugLoc();
    909     SDNode *N = Op.getNode();
    910     LoadSDNode *LD = cast<LoadSDNode>(N);
    911     EVT MemVT = LD->getMemoryVT();
    912     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
    913       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
    914                                                   : ISD::EXTLOAD)
    915       : LD->getExtensionType();
    916     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
    917                                    LD->getChain(), LD->getBasePtr(),
    918                                    LD->getPointerInfo(),
    919                                    MemVT, LD->isVolatile(),
    920                                    LD->isNonTemporal(), LD->getAlignment());
    921     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
    922 
    923     DEBUG(dbgs() << "\nPromoting ";
    924           N->dump(&DAG);
    925           dbgs() << "\nTo: ";
    926           Result.getNode()->dump(&DAG);
    927           dbgs() << '\n');
    928     WorkListRemover DeadNodes(*this);
    929     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result, &DeadNodes);
    930     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1), &DeadNodes);
    931     removeFromWorkList(N);
    932     DAG.DeleteNode(N);
    933     AddToWorkList(Result.getNode());
    934     return true;
    935   }
    936   return false;
    937 }
    938 
    939 
    940 //===----------------------------------------------------------------------===//
    941 //  Main DAG Combiner implementation
    942 //===----------------------------------------------------------------------===//
    943 
    944 void DAGCombiner::Run(CombineLevel AtLevel) {
    945   // set the instance variables, so that the various visit routines may use it.
    946   Level = AtLevel;
    947   LegalOperations = Level >= NoIllegalOperations;
    948   LegalTypes = Level >= NoIllegalTypes;
    949 
    950   // Add all the dag nodes to the worklist.
    951   WorkList.reserve(DAG.allnodes_size());
    952   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
    953        E = DAG.allnodes_end(); I != E; ++I)
    954     WorkList.push_back(I);
    955 
    956   // Create a dummy node (which is not added to allnodes), that adds a reference
    957   // to the root node, preventing it from being deleted, and tracking any
    958   // changes of the root.
    959   HandleSDNode Dummy(DAG.getRoot());
    960 
    961   // The root of the dag may dangle to deleted nodes until the dag combiner is
    962   // done.  Set it to null to avoid confusion.
    963   DAG.setRoot(SDValue());
    964 
    965   // while the worklist isn't empty, inspect the node on the end of it and
    966   // try and combine it.
    967   while (!WorkList.empty()) {
    968     SDNode *N = WorkList.back();
    969     WorkList.pop_back();
    970 
    971     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
    972     // N is deleted from the DAG, since they too may now be dead or may have a
    973     // reduced number of uses, allowing other xforms.
    974     if (N->use_empty() && N != &Dummy) {
    975       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
    976         AddToWorkList(N->getOperand(i).getNode());
    977 
    978       DAG.DeleteNode(N);
    979       continue;
    980     }
    981 
    982     SDValue RV = combine(N);
    983 
    984     if (RV.getNode() == 0)
    985       continue;
    986 
    987     ++NodesCombined;
    988 
    989     // If we get back the same node we passed in, rather than a new node or
    990     // zero, we know that the node must have defined multiple values and
    991     // CombineTo was used.  Since CombineTo takes care of the worklist
    992     // mechanics for us, we have no work to do in this case.
    993     if (RV.getNode() == N)
    994       continue;
    995 
    996     assert(N->getOpcode() != ISD::DELETED_NODE &&
    997            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
    998            "Node was deleted but visit returned new node!");
    999 
   1000     DEBUG(dbgs() << "\nReplacing.3 ";
   1001           N->dump(&DAG);
   1002           dbgs() << "\nWith: ";
   1003           RV.getNode()->dump(&DAG);
   1004           dbgs() << '\n');
   1005 
   1006     // Transfer debug value.
   1007     DAG.TransferDbgValues(SDValue(N, 0), RV);
   1008     WorkListRemover DeadNodes(*this);
   1009     if (N->getNumValues() == RV.getNode()->getNumValues())
   1010       DAG.ReplaceAllUsesWith(N, RV.getNode(), &DeadNodes);
   1011     else {
   1012       assert(N->getValueType(0) == RV.getValueType() &&
   1013              N->getNumValues() == 1 && "Type mismatch");
   1014       SDValue OpV = RV;
   1015       DAG.ReplaceAllUsesWith(N, &OpV, &DeadNodes);
   1016     }
   1017 
   1018     // Push the new node and any users onto the worklist
   1019     AddToWorkList(RV.getNode());
   1020     AddUsersToWorkList(RV.getNode());
   1021 
   1022     // Add any uses of the old node to the worklist in case this node is the
   1023     // last one that uses them.  They may become dead after this node is
   1024     // deleted.
   1025     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   1026       AddToWorkList(N->getOperand(i).getNode());
   1027 
   1028     // Finally, if the node is now dead, remove it from the graph.  The node
   1029     // may not be dead if the replacement process recursively simplified to
   1030     // something else needing this node.
   1031     if (N->use_empty()) {
   1032       // Nodes can be reintroduced into the worklist.  Make sure we do not
   1033       // process a node that has been replaced.
   1034       removeFromWorkList(N);
   1035 
   1036       // Finally, since the node is now dead, remove it from the graph.
   1037       DAG.DeleteNode(N);
   1038     }
   1039   }
   1040 
   1041   // If the root changed (e.g. it was a dead load, update the root).
   1042   DAG.setRoot(Dummy.getValue());
   1043 }
   1044 
   1045 SDValue DAGCombiner::visit(SDNode *N) {
   1046   switch (N->getOpcode()) {
   1047   default: break;
   1048   case ISD::TokenFactor:        return visitTokenFactor(N);
   1049   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
   1050   case ISD::ADD:                return visitADD(N);
   1051   case ISD::SUB:                return visitSUB(N);
   1052   case ISD::ADDC:               return visitADDC(N);
   1053   case ISD::ADDE:               return visitADDE(N);
   1054   case ISD::MUL:                return visitMUL(N);
   1055   case ISD::SDIV:               return visitSDIV(N);
   1056   case ISD::UDIV:               return visitUDIV(N);
   1057   case ISD::SREM:               return visitSREM(N);
   1058   case ISD::UREM:               return visitUREM(N);
   1059   case ISD::MULHU:              return visitMULHU(N);
   1060   case ISD::MULHS:              return visitMULHS(N);
   1061   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
   1062   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
   1063   case ISD::SMULO:              return visitSMULO(N);
   1064   case ISD::UMULO:              return visitUMULO(N);
   1065   case ISD::SDIVREM:            return visitSDIVREM(N);
   1066   case ISD::UDIVREM:            return visitUDIVREM(N);
   1067   case ISD::AND:                return visitAND(N);
   1068   case ISD::OR:                 return visitOR(N);
   1069   case ISD::XOR:                return visitXOR(N);
   1070   case ISD::SHL:                return visitSHL(N);
   1071   case ISD::SRA:                return visitSRA(N);
   1072   case ISD::SRL:                return visitSRL(N);
   1073   case ISD::CTLZ:               return visitCTLZ(N);
   1074   case ISD::CTTZ:               return visitCTTZ(N);
   1075   case ISD::CTPOP:              return visitCTPOP(N);
   1076   case ISD::SELECT:             return visitSELECT(N);
   1077   case ISD::SELECT_CC:          return visitSELECT_CC(N);
   1078   case ISD::SETCC:              return visitSETCC(N);
   1079   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
   1080   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
   1081   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
   1082   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
   1083   case ISD::TRUNCATE:           return visitTRUNCATE(N);
   1084   case ISD::BITCAST:            return visitBITCAST(N);
   1085   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
   1086   case ISD::FADD:               return visitFADD(N);
   1087   case ISD::FSUB:               return visitFSUB(N);
   1088   case ISD::FMUL:               return visitFMUL(N);
   1089   case ISD::FDIV:               return visitFDIV(N);
   1090   case ISD::FREM:               return visitFREM(N);
   1091   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
   1092   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
   1093   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
   1094   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
   1095   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
   1096   case ISD::FP_ROUND:           return visitFP_ROUND(N);
   1097   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
   1098   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
   1099   case ISD::FNEG:               return visitFNEG(N);
   1100   case ISD::FABS:               return visitFABS(N);
   1101   case ISD::BRCOND:             return visitBRCOND(N);
   1102   case ISD::BR_CC:              return visitBR_CC(N);
   1103   case ISD::LOAD:               return visitLOAD(N);
   1104   case ISD::STORE:              return visitSTORE(N);
   1105   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
   1106   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
   1107   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
   1108   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
   1109   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
   1110   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
   1111   case ISD::MEMBARRIER:         return visitMEMBARRIER(N);
   1112   }
   1113   return SDValue();
   1114 }
   1115 
   1116 SDValue DAGCombiner::combine(SDNode *N) {
   1117   SDValue RV = visit(N);
   1118 
   1119   // If nothing happened, try a target-specific DAG combine.
   1120   if (RV.getNode() == 0) {
   1121     assert(N->getOpcode() != ISD::DELETED_NODE &&
   1122            "Node was deleted but visit returned NULL!");
   1123 
   1124     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
   1125         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
   1126 
   1127       // Expose the DAG combiner to the target combiner impls.
   1128       TargetLowering::DAGCombinerInfo
   1129         DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
   1130 
   1131       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
   1132     }
   1133   }
   1134 
   1135   // If nothing happened still, try promoting the operation.
   1136   if (RV.getNode() == 0) {
   1137     switch (N->getOpcode()) {
   1138     default: break;
   1139     case ISD::ADD:
   1140     case ISD::SUB:
   1141     case ISD::MUL:
   1142     case ISD::AND:
   1143     case ISD::OR:
   1144     case ISD::XOR:
   1145       RV = PromoteIntBinOp(SDValue(N, 0));
   1146       break;
   1147     case ISD::SHL:
   1148     case ISD::SRA:
   1149     case ISD::SRL:
   1150       RV = PromoteIntShiftOp(SDValue(N, 0));
   1151       break;
   1152     case ISD::SIGN_EXTEND:
   1153     case ISD::ZERO_EXTEND:
   1154     case ISD::ANY_EXTEND:
   1155       RV = PromoteExtend(SDValue(N, 0));
   1156       break;
   1157     case ISD::LOAD:
   1158       if (PromoteLoad(SDValue(N, 0)))
   1159         RV = SDValue(N, 0);
   1160       break;
   1161     }
   1162   }
   1163 
   1164   // If N is a commutative binary node, try commuting it to enable more
   1165   // sdisel CSE.
   1166   if (RV.getNode() == 0 &&
   1167       SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
   1168       N->getNumValues() == 1) {
   1169     SDValue N0 = N->getOperand(0);
   1170     SDValue N1 = N->getOperand(1);
   1171 
   1172     // Constant operands are canonicalized to RHS.
   1173     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
   1174       SDValue Ops[] = { N1, N0 };
   1175       SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
   1176                                             Ops, 2);
   1177       if (CSENode)
   1178         return SDValue(CSENode, 0);
   1179     }
   1180   }
   1181 
   1182   return RV;
   1183 }
   1184 
   1185 /// getInputChainForNode - Given a node, return its input chain if it has one,
   1186 /// otherwise return a null sd operand.
   1187 static SDValue getInputChainForNode(SDNode *N) {
   1188   if (unsigned NumOps = N->getNumOperands()) {
   1189     if (N->getOperand(0).getValueType() == MVT::Other)
   1190       return N->getOperand(0);
   1191     else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
   1192       return N->getOperand(NumOps-1);
   1193     for (unsigned i = 1; i < NumOps-1; ++i)
   1194       if (N->getOperand(i).getValueType() == MVT::Other)
   1195         return N->getOperand(i);
   1196   }
   1197   return SDValue();
   1198 }
   1199 
   1200 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
   1201   // If N has two operands, where one has an input chain equal to the other,
   1202   // the 'other' chain is redundant.
   1203   if (N->getNumOperands() == 2) {
   1204     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
   1205       return N->getOperand(0);
   1206     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
   1207       return N->getOperand(1);
   1208   }
   1209 
   1210   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
   1211   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
   1212   SmallPtrSet<SDNode*, 16> SeenOps;
   1213   bool Changed = false;             // If we should replace this token factor.
   1214 
   1215   // Start out with this token factor.
   1216   TFs.push_back(N);
   1217 
   1218   // Iterate through token factors.  The TFs grows when new token factors are
   1219   // encountered.
   1220   for (unsigned i = 0; i < TFs.size(); ++i) {
   1221     SDNode *TF = TFs[i];
   1222 
   1223     // Check each of the operands.
   1224     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
   1225       SDValue Op = TF->getOperand(i);
   1226 
   1227       switch (Op.getOpcode()) {
   1228       case ISD::EntryToken:
   1229         // Entry tokens don't need to be added to the list. They are
   1230         // rededundant.
   1231         Changed = true;
   1232         break;
   1233 
   1234       case ISD::TokenFactor:
   1235         if (Op.hasOneUse() &&
   1236             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
   1237           // Queue up for processing.
   1238           TFs.push_back(Op.getNode());
   1239           // Clean up in case the token factor is removed.
   1240           AddToWorkList(Op.getNode());
   1241           Changed = true;
   1242           break;
   1243         }
   1244         // Fall thru
   1245 
   1246       default:
   1247         // Only add if it isn't already in the list.
   1248         if (SeenOps.insert(Op.getNode()))
   1249           Ops.push_back(Op);
   1250         else
   1251           Changed = true;
   1252         break;
   1253       }
   1254     }
   1255   }
   1256 
   1257   SDValue Result;
   1258 
   1259   // If we've change things around then replace token factor.
   1260   if (Changed) {
   1261     if (Ops.empty()) {
   1262       // The entry token is the only possible outcome.
   1263       Result = DAG.getEntryNode();
   1264     } else {
   1265       // New and improved token factor.
   1266       Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
   1267                            MVT::Other, &Ops[0], Ops.size());
   1268     }
   1269 
   1270     // Don't add users to work list.
   1271     return CombineTo(N, Result, false);
   1272   }
   1273 
   1274   return Result;
   1275 }
   1276 
   1277 /// MERGE_VALUES can always be eliminated.
   1278 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
   1279   WorkListRemover DeadNodes(*this);
   1280   // Replacing results may cause a different MERGE_VALUES to suddenly
   1281   // be CSE'd with N, and carry its uses with it. Iterate until no
   1282   // uses remain, to ensure that the node can be safely deleted.
   1283   do {
   1284     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
   1285       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i),
   1286                                     &DeadNodes);
   1287   } while (!N->use_empty());
   1288   removeFromWorkList(N);
   1289   DAG.DeleteNode(N);
   1290   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   1291 }
   1292 
   1293 static
   1294 SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
   1295                               SelectionDAG &DAG) {
   1296   EVT VT = N0.getValueType();
   1297   SDValue N00 = N0.getOperand(0);
   1298   SDValue N01 = N0.getOperand(1);
   1299   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
   1300 
   1301   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
   1302       isa<ConstantSDNode>(N00.getOperand(1))) {
   1303     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
   1304     N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
   1305                      DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
   1306                                  N00.getOperand(0), N01),
   1307                      DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
   1308                                  N00.getOperand(1), N01));
   1309     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
   1310   }
   1311 
   1312   return SDValue();
   1313 }
   1314 
   1315 SDValue DAGCombiner::visitADD(SDNode *N) {
   1316   SDValue N0 = N->getOperand(0);
   1317   SDValue N1 = N->getOperand(1);
   1318   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1319   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1320   EVT VT = N0.getValueType();
   1321 
   1322   // fold vector ops
   1323   if (VT.isVector()) {
   1324     SDValue FoldedVOp = SimplifyVBinOp(N);
   1325     if (FoldedVOp.getNode()) return FoldedVOp;
   1326   }
   1327 
   1328   // fold (add x, undef) -> undef
   1329   if (N0.getOpcode() == ISD::UNDEF)
   1330     return N0;
   1331   if (N1.getOpcode() == ISD::UNDEF)
   1332     return N1;
   1333   // fold (add c1, c2) -> c1+c2
   1334   if (N0C && N1C)
   1335     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
   1336   // canonicalize constant to RHS
   1337   if (N0C && !N1C)
   1338     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
   1339   // fold (add x, 0) -> x
   1340   if (N1C && N1C->isNullValue())
   1341     return N0;
   1342   // fold (add Sym, c) -> Sym+c
   1343   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
   1344     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
   1345         GA->getOpcode() == ISD::GlobalAddress)
   1346       return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
   1347                                   GA->getOffset() +
   1348                                     (uint64_t)N1C->getSExtValue());
   1349   // fold ((c1-A)+c2) -> (c1+c2)-A
   1350   if (N1C && N0.getOpcode() == ISD::SUB)
   1351     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
   1352       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1353                          DAG.getConstant(N1C->getAPIntValue()+
   1354                                          N0C->getAPIntValue(), VT),
   1355                          N0.getOperand(1));
   1356   // reassociate add
   1357   SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
   1358   if (RADD.getNode() != 0)
   1359     return RADD;
   1360   // fold ((0-A) + B) -> B-A
   1361   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
   1362       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
   1363     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
   1364   // fold (A + (0-B)) -> A-B
   1365   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
   1366       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
   1367     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
   1368   // fold (A+(B-A)) -> B
   1369   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
   1370     return N1.getOperand(0);
   1371   // fold ((B-A)+A) -> B
   1372   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
   1373     return N0.getOperand(0);
   1374   // fold (A+(B-(A+C))) to (B-C)
   1375   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
   1376       N0 == N1.getOperand(1).getOperand(0))
   1377     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
   1378                        N1.getOperand(1).getOperand(1));
   1379   // fold (A+(B-(C+A))) to (B-C)
   1380   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
   1381       N0 == N1.getOperand(1).getOperand(1))
   1382     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
   1383                        N1.getOperand(1).getOperand(0));
   1384   // fold (A+((B-A)+or-C)) to (B+or-C)
   1385   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
   1386       N1.getOperand(0).getOpcode() == ISD::SUB &&
   1387       N0 == N1.getOperand(0).getOperand(1))
   1388     return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
   1389                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
   1390 
   1391   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
   1392   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
   1393     SDValue N00 = N0.getOperand(0);
   1394     SDValue N01 = N0.getOperand(1);
   1395     SDValue N10 = N1.getOperand(0);
   1396     SDValue N11 = N1.getOperand(1);
   1397 
   1398     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
   1399       return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1400                          DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
   1401                          DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
   1402   }
   1403 
   1404   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
   1405     return SDValue(N, 0);
   1406 
   1407   // fold (a+b) -> (a|b) iff a and b share no bits.
   1408   if (VT.isInteger() && !VT.isVector()) {
   1409     APInt LHSZero, LHSOne;
   1410     APInt RHSZero, RHSOne;
   1411     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
   1412     DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
   1413 
   1414     if (LHSZero.getBoolValue()) {
   1415       DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
   1416 
   1417       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
   1418       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
   1419       if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
   1420           (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
   1421         return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
   1422     }
   1423   }
   1424 
   1425   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
   1426   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
   1427     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
   1428     if (Result.getNode()) return Result;
   1429   }
   1430   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
   1431     SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
   1432     if (Result.getNode()) return Result;
   1433   }
   1434 
   1435   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
   1436   if (N1.getOpcode() == ISD::SHL &&
   1437       N1.getOperand(0).getOpcode() == ISD::SUB)
   1438     if (ConstantSDNode *C =
   1439           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
   1440       if (C->getAPIntValue() == 0)
   1441         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
   1442                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
   1443                                        N1.getOperand(0).getOperand(1),
   1444                                        N1.getOperand(1)));
   1445   if (N0.getOpcode() == ISD::SHL &&
   1446       N0.getOperand(0).getOpcode() == ISD::SUB)
   1447     if (ConstantSDNode *C =
   1448           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
   1449       if (C->getAPIntValue() == 0)
   1450         return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
   1451                            DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
   1452                                        N0.getOperand(0).getOperand(1),
   1453                                        N0.getOperand(1)));
   1454 
   1455   if (N1.getOpcode() == ISD::AND) {
   1456     SDValue AndOp0 = N1.getOperand(0);
   1457     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
   1458     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
   1459     unsigned DestBits = VT.getScalarType().getSizeInBits();
   1460 
   1461     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
   1462     // and similar xforms where the inner op is either ~0 or 0.
   1463     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
   1464       DebugLoc DL = N->getDebugLoc();
   1465       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
   1466     }
   1467   }
   1468 
   1469   // add (sext i1), X -> sub X, (zext i1)
   1470   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
   1471       N0.getOperand(0).getValueType() == MVT::i1 &&
   1472       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
   1473     DebugLoc DL = N->getDebugLoc();
   1474     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
   1475     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
   1476   }
   1477 
   1478   return SDValue();
   1479 }
   1480 
   1481 SDValue DAGCombiner::visitADDC(SDNode *N) {
   1482   SDValue N0 = N->getOperand(0);
   1483   SDValue N1 = N->getOperand(1);
   1484   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1485   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1486   EVT VT = N0.getValueType();
   1487 
   1488   // If the flag result is dead, turn this into an ADD.
   1489   if (N->hasNUsesOfValue(0, 1))
   1490     return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0),
   1491                      DAG.getNode(ISD::CARRY_FALSE,
   1492                                  N->getDebugLoc(), MVT::Glue));
   1493 
   1494   // canonicalize constant to RHS.
   1495   if (N0C && !N1C)
   1496     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
   1497 
   1498   // fold (addc x, 0) -> x + no carry out
   1499   if (N1C && N1C->isNullValue())
   1500     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
   1501                                         N->getDebugLoc(), MVT::Glue));
   1502 
   1503   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
   1504   APInt LHSZero, LHSOne;
   1505   APInt RHSZero, RHSOne;
   1506   APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
   1507   DAG.ComputeMaskedBits(N0, Mask, LHSZero, LHSOne);
   1508 
   1509   if (LHSZero.getBoolValue()) {
   1510     DAG.ComputeMaskedBits(N1, Mask, RHSZero, RHSOne);
   1511 
   1512     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
   1513     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
   1514     if ((RHSZero & (~LHSZero & Mask)) == (~LHSZero & Mask) ||
   1515         (LHSZero & (~RHSZero & Mask)) == (~RHSZero & Mask))
   1516       return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
   1517                        DAG.getNode(ISD::CARRY_FALSE,
   1518                                    N->getDebugLoc(), MVT::Glue));
   1519   }
   1520 
   1521   return SDValue();
   1522 }
   1523 
   1524 SDValue DAGCombiner::visitADDE(SDNode *N) {
   1525   SDValue N0 = N->getOperand(0);
   1526   SDValue N1 = N->getOperand(1);
   1527   SDValue CarryIn = N->getOperand(2);
   1528   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1529   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1530 
   1531   // canonicalize constant to RHS
   1532   if (N0C && !N1C)
   1533     return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
   1534                        N1, N0, CarryIn);
   1535 
   1536   // fold (adde x, y, false) -> (addc x, y)
   1537   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
   1538     return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
   1539 
   1540   return SDValue();
   1541 }
   1542 
   1543 // Since it may not be valid to emit a fold to zero for vector initializers
   1544 // check if we can before folding.
   1545 static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
   1546                              SelectionDAG &DAG, bool LegalOperations) {
   1547   if (!VT.isVector()) {
   1548     return DAG.getConstant(0, VT);
   1549   }
   1550   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
   1551     // Produce a vector of zeros.
   1552     SDValue El = DAG.getConstant(0, VT.getVectorElementType());
   1553     std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
   1554     return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
   1555       &Ops[0], Ops.size());
   1556   }
   1557   return SDValue();
   1558 }
   1559 
   1560 SDValue DAGCombiner::visitSUB(SDNode *N) {
   1561   SDValue N0 = N->getOperand(0);
   1562   SDValue N1 = N->getOperand(1);
   1563   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
   1564   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   1565   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
   1566     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
   1567   EVT VT = N0.getValueType();
   1568 
   1569   // fold vector ops
   1570   if (VT.isVector()) {
   1571     SDValue FoldedVOp = SimplifyVBinOp(N);
   1572     if (FoldedVOp.getNode()) return FoldedVOp;
   1573   }
   1574 
   1575   // fold (sub x, x) -> 0
   1576   // FIXME: Refactor this and xor and other similar operations together.
   1577   if (N0 == N1)
   1578     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
   1579   // fold (sub c1, c2) -> c1-c2
   1580   if (N0C && N1C)
   1581     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
   1582   // fold (sub x, c) -> (add x, -c)
   1583   if (N1C)
   1584     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
   1585                        DAG.getConstant(-N1C->getAPIntValue(), VT));
   1586   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
   1587   if (N0C && N0C->isAllOnesValue())
   1588     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
   1589   // fold A-(A-B) -> B
   1590   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
   1591     return N1.getOperand(1);
   1592   // fold (A+B)-A -> B
   1593   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
   1594     return N0.getOperand(1);
   1595   // fold (A+B)-B -> A
   1596   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
   1597     return N0.getOperand(0);
   1598   // fold C2-(A+C1) -> (C2-C1)-A
   1599   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
   1600     SDValue NewC = DAG.getConstant((N0C->getAPIntValue() - N1C1->getAPIntValue()), VT);
   1601     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
   1602 		       N1.getOperand(0));
   1603   }
   1604   // fold ((A+(B+or-C))-B) -> A+or-C
   1605   if (N0.getOpcode() == ISD::ADD &&
   1606       (N0.getOperand(1).getOpcode() == ISD::SUB ||
   1607        N0.getOperand(1).getOpcode() == ISD::ADD) &&
   1608       N0.getOperand(1).getOperand(0) == N1)
   1609     return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
   1610                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
   1611   // fold ((A+(C+B))-B) -> A+C
   1612   if (N0.getOpcode() == ISD::ADD &&
   1613       N0.getOperand(1).getOpcode() == ISD::ADD &&
   1614       N0.getOperand(1).getOperand(1) == N1)
   1615     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
   1616                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
   1617   // fold ((A-(B-C))-C) -> A-B
   1618   if (N0.getOpcode() == ISD::SUB &&
   1619       N0.getOperand(1).getOpcode() == ISD::SUB &&
   1620       N0.getOperand(1).getOperand(1) == N1)
   1621     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1622                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
   1623 
   1624   // If either operand of a sub is undef, the result is undef
   1625   if (N0.getOpcode() == ISD::UNDEF)
   1626     return N0;
   1627   if (N1.getOpcode() == ISD::UNDEF)
   1628     return N1;
   1629 
   1630   // If the relocation model supports it, consider symbol offsets.
   1631   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
   1632     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
   1633       // fold (sub Sym, c) -> Sym-c
   1634       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
   1635         return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
   1636                                     GA->getOffset() -
   1637                                       (uint64_t)N1C->getSExtValue());
   1638       // fold (sub Sym+c1, Sym+c2) -> c1-c2
   1639       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
   1640         if (GA->getGlobal() == GB->getGlobal())
   1641           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
   1642                                  VT);
   1643     }
   1644 
   1645   return SDValue();
   1646 }
   1647 
   1648 SDValue DAGCombiner::visitMUL(SDNode *N) {
   1649   SDValue N0 = N->getOperand(0);
   1650   SDValue N1 = N->getOperand(1);
   1651   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1652   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1653   EVT VT = N0.getValueType();
   1654 
   1655   // fold vector ops
   1656   if (VT.isVector()) {
   1657     SDValue FoldedVOp = SimplifyVBinOp(N);
   1658     if (FoldedVOp.getNode()) return FoldedVOp;
   1659   }
   1660 
   1661   // fold (mul x, undef) -> 0
   1662   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   1663     return DAG.getConstant(0, VT);
   1664   // fold (mul c1, c2) -> c1*c2
   1665   if (N0C && N1C)
   1666     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
   1667   // canonicalize constant to RHS
   1668   if (N0C && !N1C)
   1669     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
   1670   // fold (mul x, 0) -> 0
   1671   if (N1C && N1C->isNullValue())
   1672     return N1;
   1673   // fold (mul x, -1) -> 0-x
   1674   if (N1C && N1C->isAllOnesValue())
   1675     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1676                        DAG.getConstant(0, VT), N0);
   1677   // fold (mul x, (1 << c)) -> x << c
   1678   if (N1C && N1C->getAPIntValue().isPowerOf2())
   1679     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
   1680                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
   1681                                        getShiftAmountTy(N0.getValueType())));
   1682   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
   1683   if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
   1684     unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
   1685     // FIXME: If the input is something that is easily negated (e.g. a
   1686     // single-use add), we should put the negate there.
   1687     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1688                        DAG.getConstant(0, VT),
   1689                        DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
   1690                             DAG.getConstant(Log2Val,
   1691                                       getShiftAmountTy(N0.getValueType()))));
   1692   }
   1693   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
   1694   if (N1C && N0.getOpcode() == ISD::SHL &&
   1695       isa<ConstantSDNode>(N0.getOperand(1))) {
   1696     SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
   1697                              N1, N0.getOperand(1));
   1698     AddToWorkList(C3.getNode());
   1699     return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
   1700                        N0.getOperand(0), C3);
   1701   }
   1702 
   1703   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
   1704   // use.
   1705   {
   1706     SDValue Sh(0,0), Y(0,0);
   1707     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
   1708     if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
   1709         N0.getNode()->hasOneUse()) {
   1710       Sh = N0; Y = N1;
   1711     } else if (N1.getOpcode() == ISD::SHL &&
   1712                isa<ConstantSDNode>(N1.getOperand(1)) &&
   1713                N1.getNode()->hasOneUse()) {
   1714       Sh = N1; Y = N0;
   1715     }
   1716 
   1717     if (Sh.getNode()) {
   1718       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
   1719                                 Sh.getOperand(0), Y);
   1720       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
   1721                          Mul, Sh.getOperand(1));
   1722     }
   1723   }
   1724 
   1725   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
   1726   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
   1727       isa<ConstantSDNode>(N0.getOperand(1)))
   1728     return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
   1729                        DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
   1730                                    N0.getOperand(0), N1),
   1731                        DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
   1732                                    N0.getOperand(1), N1));
   1733 
   1734   // reassociate mul
   1735   SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
   1736   if (RMUL.getNode() != 0)
   1737     return RMUL;
   1738 
   1739   return SDValue();
   1740 }
   1741 
   1742 SDValue DAGCombiner::visitSDIV(SDNode *N) {
   1743   SDValue N0 = N->getOperand(0);
   1744   SDValue N1 = N->getOperand(1);
   1745   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
   1746   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   1747   EVT VT = N->getValueType(0);
   1748 
   1749   // fold vector ops
   1750   if (VT.isVector()) {
   1751     SDValue FoldedVOp = SimplifyVBinOp(N);
   1752     if (FoldedVOp.getNode()) return FoldedVOp;
   1753   }
   1754 
   1755   // fold (sdiv c1, c2) -> c1/c2
   1756   if (N0C && N1C && !N1C->isNullValue())
   1757     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
   1758   // fold (sdiv X, 1) -> X
   1759   if (N1C && N1C->getSExtValue() == 1LL)
   1760     return N0;
   1761   // fold (sdiv X, -1) -> 0-X
   1762   if (N1C && N1C->isAllOnesValue())
   1763     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1764                        DAG.getConstant(0, VT), N0);
   1765   // If we know the sign bits of both operands are zero, strength reduce to a
   1766   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
   1767   if (!VT.isVector()) {
   1768     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
   1769       return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
   1770                          N0, N1);
   1771   }
   1772   // fold (sdiv X, pow2) -> simple ops after legalize
   1773   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap() &&
   1774       (isPowerOf2_64(N1C->getSExtValue()) ||
   1775        isPowerOf2_64(-N1C->getSExtValue()))) {
   1776     // If dividing by powers of two is cheap, then don't perform the following
   1777     // fold.
   1778     if (TLI.isPow2DivCheap())
   1779       return SDValue();
   1780 
   1781     int64_t pow2 = N1C->getSExtValue();
   1782     int64_t abs2 = pow2 > 0 ? pow2 : -pow2;
   1783     unsigned lg2 = Log2_64(abs2);
   1784 
   1785     // Splat the sign bit into the register
   1786     SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
   1787                               DAG.getConstant(VT.getSizeInBits()-1,
   1788                                        getShiftAmountTy(N0.getValueType())));
   1789     AddToWorkList(SGN.getNode());
   1790 
   1791     // Add (N0 < 0) ? abs2 - 1 : 0;
   1792     SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
   1793                               DAG.getConstant(VT.getSizeInBits() - lg2,
   1794                                        getShiftAmountTy(SGN.getValueType())));
   1795     SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
   1796     AddToWorkList(SRL.getNode());
   1797     AddToWorkList(ADD.getNode());    // Divide by pow2
   1798     SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
   1799                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
   1800 
   1801     // If we're dividing by a positive value, we're done.  Otherwise, we must
   1802     // negate the result.
   1803     if (pow2 > 0)
   1804       return SRA;
   1805 
   1806     AddToWorkList(SRA.getNode());
   1807     return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
   1808                        DAG.getConstant(0, VT), SRA);
   1809   }
   1810 
   1811   // if integer divide is expensive and we satisfy the requirements, emit an
   1812   // alternate sequence.
   1813   if (N1C && (N1C->getSExtValue() < -1 || N1C->getSExtValue() > 1) &&
   1814       !TLI.isIntDivCheap()) {
   1815     SDValue Op = BuildSDIV(N);
   1816     if (Op.getNode()) return Op;
   1817   }
   1818 
   1819   // undef / X -> 0
   1820   if (N0.getOpcode() == ISD::UNDEF)
   1821     return DAG.getConstant(0, VT);
   1822   // X / undef -> undef
   1823   if (N1.getOpcode() == ISD::UNDEF)
   1824     return N1;
   1825 
   1826   return SDValue();
   1827 }
   1828 
   1829 SDValue DAGCombiner::visitUDIV(SDNode *N) {
   1830   SDValue N0 = N->getOperand(0);
   1831   SDValue N1 = N->getOperand(1);
   1832   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
   1833   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   1834   EVT VT = N->getValueType(0);
   1835 
   1836   // fold vector ops
   1837   if (VT.isVector()) {
   1838     SDValue FoldedVOp = SimplifyVBinOp(N);
   1839     if (FoldedVOp.getNode()) return FoldedVOp;
   1840   }
   1841 
   1842   // fold (udiv c1, c2) -> c1/c2
   1843   if (N0C && N1C && !N1C->isNullValue())
   1844     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
   1845   // fold (udiv x, (1 << c)) -> x >>u c
   1846   if (N1C && N1C->getAPIntValue().isPowerOf2())
   1847     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
   1848                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
   1849                                        getShiftAmountTy(N0.getValueType())));
   1850   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
   1851   if (N1.getOpcode() == ISD::SHL) {
   1852     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
   1853       if (SHC->getAPIntValue().isPowerOf2()) {
   1854         EVT ADDVT = N1.getOperand(1).getValueType();
   1855         SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
   1856                                   N1.getOperand(1),
   1857                                   DAG.getConstant(SHC->getAPIntValue()
   1858                                                                   .logBase2(),
   1859                                                   ADDVT));
   1860         AddToWorkList(Add.getNode());
   1861         return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
   1862       }
   1863     }
   1864   }
   1865   // fold (udiv x, c) -> alternate
   1866   if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
   1867     SDValue Op = BuildUDIV(N);
   1868     if (Op.getNode()) return Op;
   1869   }
   1870 
   1871   // undef / X -> 0
   1872   if (N0.getOpcode() == ISD::UNDEF)
   1873     return DAG.getConstant(0, VT);
   1874   // X / undef -> undef
   1875   if (N1.getOpcode() == ISD::UNDEF)
   1876     return N1;
   1877 
   1878   return SDValue();
   1879 }
   1880 
   1881 SDValue DAGCombiner::visitSREM(SDNode *N) {
   1882   SDValue N0 = N->getOperand(0);
   1883   SDValue N1 = N->getOperand(1);
   1884   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1885   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1886   EVT VT = N->getValueType(0);
   1887 
   1888   // fold (srem c1, c2) -> c1%c2
   1889   if (N0C && N1C && !N1C->isNullValue())
   1890     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
   1891   // If we know the sign bits of both operands are zero, strength reduce to a
   1892   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
   1893   if (!VT.isVector()) {
   1894     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
   1895       return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
   1896   }
   1897 
   1898   // If X/C can be simplified by the division-by-constant logic, lower
   1899   // X%C to the equivalent of X-X/C*C.
   1900   if (N1C && !N1C->isNullValue()) {
   1901     SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
   1902     AddToWorkList(Div.getNode());
   1903     SDValue OptimizedDiv = combine(Div.getNode());
   1904     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
   1905       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
   1906                                 OptimizedDiv, N1);
   1907       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
   1908       AddToWorkList(Mul.getNode());
   1909       return Sub;
   1910     }
   1911   }
   1912 
   1913   // undef % X -> 0
   1914   if (N0.getOpcode() == ISD::UNDEF)
   1915     return DAG.getConstant(0, VT);
   1916   // X % undef -> undef
   1917   if (N1.getOpcode() == ISD::UNDEF)
   1918     return N1;
   1919 
   1920   return SDValue();
   1921 }
   1922 
   1923 SDValue DAGCombiner::visitUREM(SDNode *N) {
   1924   SDValue N0 = N->getOperand(0);
   1925   SDValue N1 = N->getOperand(1);
   1926   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   1927   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1928   EVT VT = N->getValueType(0);
   1929 
   1930   // fold (urem c1, c2) -> c1%c2
   1931   if (N0C && N1C && !N1C->isNullValue())
   1932     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
   1933   // fold (urem x, pow2) -> (and x, pow2-1)
   1934   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
   1935     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
   1936                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
   1937   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
   1938   if (N1.getOpcode() == ISD::SHL) {
   1939     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
   1940       if (SHC->getAPIntValue().isPowerOf2()) {
   1941         SDValue Add =
   1942           DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
   1943                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
   1944                                  VT));
   1945         AddToWorkList(Add.getNode());
   1946         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
   1947       }
   1948     }
   1949   }
   1950 
   1951   // If X/C can be simplified by the division-by-constant logic, lower
   1952   // X%C to the equivalent of X-X/C*C.
   1953   if (N1C && !N1C->isNullValue()) {
   1954     SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
   1955     AddToWorkList(Div.getNode());
   1956     SDValue OptimizedDiv = combine(Div.getNode());
   1957     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
   1958       SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
   1959                                 OptimizedDiv, N1);
   1960       SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
   1961       AddToWorkList(Mul.getNode());
   1962       return Sub;
   1963     }
   1964   }
   1965 
   1966   // undef % X -> 0
   1967   if (N0.getOpcode() == ISD::UNDEF)
   1968     return DAG.getConstant(0, VT);
   1969   // X % undef -> undef
   1970   if (N1.getOpcode() == ISD::UNDEF)
   1971     return N1;
   1972 
   1973   return SDValue();
   1974 }
   1975 
   1976 SDValue DAGCombiner::visitMULHS(SDNode *N) {
   1977   SDValue N0 = N->getOperand(0);
   1978   SDValue N1 = N->getOperand(1);
   1979   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   1980   EVT VT = N->getValueType(0);
   1981   DebugLoc DL = N->getDebugLoc();
   1982 
   1983   // fold (mulhs x, 0) -> 0
   1984   if (N1C && N1C->isNullValue())
   1985     return N1;
   1986   // fold (mulhs x, 1) -> (sra x, size(x)-1)
   1987   if (N1C && N1C->getAPIntValue() == 1)
   1988     return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
   1989                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
   1990                                        getShiftAmountTy(N0.getValueType())));
   1991   // fold (mulhs x, undef) -> 0
   1992   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   1993     return DAG.getConstant(0, VT);
   1994 
   1995   // If the type twice as wide is legal, transform the mulhs to a wider multiply
   1996   // plus a shift.
   1997   if (VT.isSimple() && !VT.isVector()) {
   1998     MVT Simple = VT.getSimpleVT();
   1999     unsigned SimpleSize = Simple.getSizeInBits();
   2000     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2001     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2002       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
   2003       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
   2004       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
   2005       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
   2006             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
   2007       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
   2008     }
   2009   }
   2010 
   2011   return SDValue();
   2012 }
   2013 
   2014 SDValue DAGCombiner::visitMULHU(SDNode *N) {
   2015   SDValue N0 = N->getOperand(0);
   2016   SDValue N1 = N->getOperand(1);
   2017   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2018   EVT VT = N->getValueType(0);
   2019   DebugLoc DL = N->getDebugLoc();
   2020 
   2021   // fold (mulhu x, 0) -> 0
   2022   if (N1C && N1C->isNullValue())
   2023     return N1;
   2024   // fold (mulhu x, 1) -> 0
   2025   if (N1C && N1C->getAPIntValue() == 1)
   2026     return DAG.getConstant(0, N0.getValueType());
   2027   // fold (mulhu x, undef) -> 0
   2028   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   2029     return DAG.getConstant(0, VT);
   2030 
   2031   // If the type twice as wide is legal, transform the mulhu to a wider multiply
   2032   // plus a shift.
   2033   if (VT.isSimple() && !VT.isVector()) {
   2034     MVT Simple = VT.getSimpleVT();
   2035     unsigned SimpleSize = Simple.getSizeInBits();
   2036     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2037     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2038       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
   2039       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
   2040       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
   2041       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
   2042             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
   2043       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
   2044     }
   2045   }
   2046 
   2047   return SDValue();
   2048 }
   2049 
   2050 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
   2051 /// compute two values. LoOp and HiOp give the opcodes for the two computations
   2052 /// that are being performed. Return true if a simplification was made.
   2053 ///
   2054 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
   2055                                                 unsigned HiOp) {
   2056   // If the high half is not needed, just compute the low half.
   2057   bool HiExists = N->hasAnyUseOfValue(1);
   2058   if (!HiExists &&
   2059       (!LegalOperations ||
   2060        TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
   2061     SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
   2062                               N->op_begin(), N->getNumOperands());
   2063     return CombineTo(N, Res, Res);
   2064   }
   2065 
   2066   // If the low half is not needed, just compute the high half.
   2067   bool LoExists = N->hasAnyUseOfValue(0);
   2068   if (!LoExists &&
   2069       (!LegalOperations ||
   2070        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
   2071     SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
   2072                               N->op_begin(), N->getNumOperands());
   2073     return CombineTo(N, Res, Res);
   2074   }
   2075 
   2076   // If both halves are used, return as it is.
   2077   if (LoExists && HiExists)
   2078     return SDValue();
   2079 
   2080   // If the two computed results can be simplified separately, separate them.
   2081   if (LoExists) {
   2082     SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
   2083                              N->op_begin(), N->getNumOperands());
   2084     AddToWorkList(Lo.getNode());
   2085     SDValue LoOpt = combine(Lo.getNode());
   2086     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
   2087         (!LegalOperations ||
   2088          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
   2089       return CombineTo(N, LoOpt, LoOpt);
   2090   }
   2091 
   2092   if (HiExists) {
   2093     SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
   2094                              N->op_begin(), N->getNumOperands());
   2095     AddToWorkList(Hi.getNode());
   2096     SDValue HiOpt = combine(Hi.getNode());
   2097     if (HiOpt.getNode() && HiOpt != Hi &&
   2098         (!LegalOperations ||
   2099          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
   2100       return CombineTo(N, HiOpt, HiOpt);
   2101   }
   2102 
   2103   return SDValue();
   2104 }
   2105 
   2106 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
   2107   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
   2108   if (Res.getNode()) return Res;
   2109 
   2110   EVT VT = N->getValueType(0);
   2111   DebugLoc DL = N->getDebugLoc();
   2112 
   2113   // If the type twice as wide is legal, transform the mulhu to a wider multiply
   2114   // plus a shift.
   2115   if (VT.isSimple() && !VT.isVector()) {
   2116     MVT Simple = VT.getSimpleVT();
   2117     unsigned SimpleSize = Simple.getSizeInBits();
   2118     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2119     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2120       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
   2121       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
   2122       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
   2123       // Compute the high part as N1.
   2124       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
   2125             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
   2126       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
   2127       // Compute the low part as N0.
   2128       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
   2129       return CombineTo(N, Lo, Hi);
   2130     }
   2131   }
   2132 
   2133   return SDValue();
   2134 }
   2135 
   2136 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
   2137   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
   2138   if (Res.getNode()) return Res;
   2139 
   2140   EVT VT = N->getValueType(0);
   2141   DebugLoc DL = N->getDebugLoc();
   2142 
   2143   // If the type twice as wide is legal, transform the mulhu to a wider multiply
   2144   // plus a shift.
   2145   if (VT.isSimple() && !VT.isVector()) {
   2146     MVT Simple = VT.getSimpleVT();
   2147     unsigned SimpleSize = Simple.getSizeInBits();
   2148     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
   2149     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
   2150       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
   2151       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
   2152       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
   2153       // Compute the high part as N1.
   2154       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
   2155             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
   2156       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
   2157       // Compute the low part as N0.
   2158       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
   2159       return CombineTo(N, Lo, Hi);
   2160     }
   2161   }
   2162 
   2163   return SDValue();
   2164 }
   2165 
   2166 SDValue DAGCombiner::visitSMULO(SDNode *N) {
   2167   // (smulo x, 2) -> (saddo x, x)
   2168   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
   2169     if (C2->getAPIntValue() == 2)
   2170       return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
   2171                          N->getOperand(0), N->getOperand(0));
   2172 
   2173   return SDValue();
   2174 }
   2175 
   2176 SDValue DAGCombiner::visitUMULO(SDNode *N) {
   2177   // (umulo x, 2) -> (uaddo x, x)
   2178   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
   2179     if (C2->getAPIntValue() == 2)
   2180       return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
   2181                          N->getOperand(0), N->getOperand(0));
   2182 
   2183   return SDValue();
   2184 }
   2185 
   2186 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
   2187   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
   2188   if (Res.getNode()) return Res;
   2189 
   2190   return SDValue();
   2191 }
   2192 
   2193 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
   2194   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
   2195   if (Res.getNode()) return Res;
   2196 
   2197   return SDValue();
   2198 }
   2199 
   2200 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
   2201 /// two operands of the same opcode, try to simplify it.
   2202 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
   2203   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
   2204   EVT VT = N0.getValueType();
   2205   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
   2206 
   2207   // Bail early if none of these transforms apply.
   2208   if (N0.getNode()->getNumOperands() == 0) return SDValue();
   2209 
   2210   // For each of OP in AND/OR/XOR:
   2211   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
   2212   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
   2213   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
   2214   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
   2215   //
   2216   // do not sink logical op inside of a vector extend, since it may combine
   2217   // into a vsetcc.
   2218   EVT Op0VT = N0.getOperand(0).getValueType();
   2219   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
   2220        N0.getOpcode() == ISD::SIGN_EXTEND ||
   2221        // Avoid infinite looping with PromoteIntBinOp.
   2222        (N0.getOpcode() == ISD::ANY_EXTEND &&
   2223         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
   2224        (N0.getOpcode() == ISD::TRUNCATE &&
   2225         (!TLI.isZExtFree(VT, Op0VT) ||
   2226          !TLI.isTruncateFree(Op0VT, VT)) &&
   2227         TLI.isTypeLegal(Op0VT))) &&
   2228       !VT.isVector() &&
   2229       Op0VT == N1.getOperand(0).getValueType() &&
   2230       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
   2231     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
   2232                                  N0.getOperand(0).getValueType(),
   2233                                  N0.getOperand(0), N1.getOperand(0));
   2234     AddToWorkList(ORNode.getNode());
   2235     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
   2236   }
   2237 
   2238   // For each of OP in SHL/SRL/SRA/AND...
   2239   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
   2240   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
   2241   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
   2242   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
   2243        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
   2244       N0.getOperand(1) == N1.getOperand(1)) {
   2245     SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
   2246                                  N0.getOperand(0).getValueType(),
   2247                                  N0.getOperand(0), N1.getOperand(0));
   2248     AddToWorkList(ORNode.getNode());
   2249     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
   2250                        ORNode, N0.getOperand(1));
   2251   }
   2252 
   2253   return SDValue();
   2254 }
   2255 
   2256 SDValue DAGCombiner::visitAND(SDNode *N) {
   2257   SDValue N0 = N->getOperand(0);
   2258   SDValue N1 = N->getOperand(1);
   2259   SDValue LL, LR, RL, RR, CC0, CC1;
   2260   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   2261   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2262   EVT VT = N1.getValueType();
   2263   unsigned BitWidth = VT.getScalarType().getSizeInBits();
   2264 
   2265   // fold vector ops
   2266   if (VT.isVector()) {
   2267     SDValue FoldedVOp = SimplifyVBinOp(N);
   2268     if (FoldedVOp.getNode()) return FoldedVOp;
   2269   }
   2270 
   2271   // fold (and x, undef) -> 0
   2272   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
   2273     return DAG.getConstant(0, VT);
   2274   // fold (and c1, c2) -> c1&c2
   2275   if (N0C && N1C)
   2276     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
   2277   // canonicalize constant to RHS
   2278   if (N0C && !N1C)
   2279     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
   2280   // fold (and x, -1) -> x
   2281   if (N1C && N1C->isAllOnesValue())
   2282     return N0;
   2283   // if (and x, c) is known to be zero, return 0
   2284   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
   2285                                    APInt::getAllOnesValue(BitWidth)))
   2286     return DAG.getConstant(0, VT);
   2287   // reassociate and
   2288   SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
   2289   if (RAND.getNode() != 0)
   2290     return RAND;
   2291   // fold (and (or x, C), D) -> D if (C & D) == D
   2292   if (N1C && N0.getOpcode() == ISD::OR)
   2293     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
   2294       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
   2295         return N1;
   2296   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
   2297   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
   2298     SDValue N0Op0 = N0.getOperand(0);
   2299     APInt Mask = ~N1C->getAPIntValue();
   2300     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
   2301     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
   2302       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
   2303                                  N0.getValueType(), N0Op0);
   2304 
   2305       // Replace uses of the AND with uses of the Zero extend node.
   2306       CombineTo(N, Zext);
   2307 
   2308       // We actually want to replace all uses of the any_extend with the
   2309       // zero_extend, to avoid duplicating things.  This will later cause this
   2310       // AND to be folded.
   2311       CombineTo(N0.getNode(), Zext);
   2312       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2313     }
   2314   }
   2315   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
   2316   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
   2317     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
   2318     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
   2319 
   2320     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
   2321         LL.getValueType().isInteger()) {
   2322       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
   2323       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
   2324         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
   2325                                      LR.getValueType(), LL, RL);
   2326         AddToWorkList(ORNode.getNode());
   2327         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
   2328       }
   2329       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
   2330       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
   2331         SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
   2332                                       LR.getValueType(), LL, RL);
   2333         AddToWorkList(ANDNode.getNode());
   2334         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
   2335       }
   2336       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
   2337       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
   2338         SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
   2339                                      LR.getValueType(), LL, RL);
   2340         AddToWorkList(ORNode.getNode());
   2341         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
   2342       }
   2343     }
   2344     // canonicalize equivalent to ll == rl
   2345     if (LL == RR && LR == RL) {
   2346       Op1 = ISD::getSetCCSwappedOperands(Op1);
   2347       std::swap(RL, RR);
   2348     }
   2349     if (LL == RL && LR == RR) {
   2350       bool isInteger = LL.getValueType().isInteger();
   2351       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
   2352       if (Result != ISD::SETCC_INVALID &&
   2353           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
   2354         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
   2355                             LL, LR, Result);
   2356     }
   2357   }
   2358 
   2359   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
   2360   if (N0.getOpcode() == N1.getOpcode()) {
   2361     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   2362     if (Tmp.getNode()) return Tmp;
   2363   }
   2364 
   2365   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
   2366   // fold (and (sra)) -> (and (srl)) when possible.
   2367   if (!VT.isVector() &&
   2368       SimplifyDemandedBits(SDValue(N, 0)))
   2369     return SDValue(N, 0);
   2370 
   2371   // fold (zext_inreg (extload x)) -> (zextload x)
   2372   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
   2373     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   2374     EVT MemVT = LN0->getMemoryVT();
   2375     // If we zero all the possible extended bits, then we can turn this into
   2376     // a zextload if we are running before legalize or the operation is legal.
   2377     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
   2378     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
   2379                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
   2380         ((!LegalOperations && !LN0->isVolatile()) ||
   2381          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
   2382       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
   2383                                        LN0->getChain(), LN0->getBasePtr(),
   2384                                        LN0->getPointerInfo(), MemVT,
   2385                                        LN0->isVolatile(), LN0->isNonTemporal(),
   2386                                        LN0->getAlignment());
   2387       AddToWorkList(N);
   2388       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   2389       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2390     }
   2391   }
   2392   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
   2393   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   2394       N0.hasOneUse()) {
   2395     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   2396     EVT MemVT = LN0->getMemoryVT();
   2397     // If we zero all the possible extended bits, then we can turn this into
   2398     // a zextload if we are running before legalize or the operation is legal.
   2399     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
   2400     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
   2401                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
   2402         ((!LegalOperations && !LN0->isVolatile()) ||
   2403          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
   2404       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
   2405                                        LN0->getChain(),
   2406                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   2407                                        MemVT,
   2408                                        LN0->isVolatile(), LN0->isNonTemporal(),
   2409                                        LN0->getAlignment());
   2410       AddToWorkList(N);
   2411       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   2412       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2413     }
   2414   }
   2415 
   2416   // fold (and (load x), 255) -> (zextload x, i8)
   2417   // fold (and (extload x, i16), 255) -> (zextload x, i8)
   2418   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
   2419   if (N1C && (N0.getOpcode() == ISD::LOAD ||
   2420               (N0.getOpcode() == ISD::ANY_EXTEND &&
   2421                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
   2422     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
   2423     LoadSDNode *LN0 = HasAnyExt
   2424       ? cast<LoadSDNode>(N0.getOperand(0))
   2425       : cast<LoadSDNode>(N0);
   2426     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
   2427         LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
   2428       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
   2429       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
   2430         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
   2431         EVT LoadedVT = LN0->getMemoryVT();
   2432 
   2433         if (ExtVT == LoadedVT &&
   2434             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
   2435           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
   2436 
   2437           SDValue NewLoad =
   2438             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
   2439                            LN0->getChain(), LN0->getBasePtr(),
   2440                            LN0->getPointerInfo(),
   2441                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
   2442                            LN0->getAlignment());
   2443           AddToWorkList(N);
   2444           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
   2445           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2446         }
   2447 
   2448         // Do not change the width of a volatile load.
   2449         // Do not generate loads of non-round integer types since these can
   2450         // be expensive (and would be wrong if the type is not byte sized).
   2451         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
   2452             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
   2453           EVT PtrType = LN0->getOperand(1).getValueType();
   2454 
   2455           unsigned Alignment = LN0->getAlignment();
   2456           SDValue NewPtr = LN0->getBasePtr();
   2457 
   2458           // For big endian targets, we need to add an offset to the pointer
   2459           // to load the correct bytes.  For little endian systems, we merely
   2460           // need to read fewer bytes from the same pointer.
   2461           if (TLI.isBigEndian()) {
   2462             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
   2463             unsigned EVTStoreBytes = ExtVT.getStoreSize();
   2464             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
   2465             NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
   2466                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
   2467             Alignment = MinAlign(Alignment, PtrOff);
   2468           }
   2469 
   2470           AddToWorkList(NewPtr.getNode());
   2471 
   2472           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
   2473           SDValue Load =
   2474             DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
   2475                            LN0->getChain(), NewPtr,
   2476                            LN0->getPointerInfo(),
   2477                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
   2478                            Alignment);
   2479           AddToWorkList(N);
   2480           CombineTo(LN0, Load, Load.getValue(1));
   2481           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   2482         }
   2483       }
   2484     }
   2485   }
   2486 
   2487   return SDValue();
   2488 }
   2489 
   2490 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
   2491 ///
   2492 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
   2493                                         bool DemandHighBits) {
   2494   if (!LegalOperations)
   2495     return SDValue();
   2496 
   2497   EVT VT = N->getValueType(0);
   2498   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
   2499     return SDValue();
   2500   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
   2501     return SDValue();
   2502 
   2503   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
   2504   bool LookPassAnd0 = false;
   2505   bool LookPassAnd1 = false;
   2506   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
   2507       std::swap(N0, N1);
   2508   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
   2509       std::swap(N0, N1);
   2510   if (N0.getOpcode() == ISD::AND) {
   2511     if (!N0.getNode()->hasOneUse())
   2512       return SDValue();
   2513     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   2514     if (!N01C || N01C->getZExtValue() != 0xFF00)
   2515       return SDValue();
   2516     N0 = N0.getOperand(0);
   2517     LookPassAnd0 = true;
   2518   }
   2519 
   2520   if (N1.getOpcode() == ISD::AND) {
   2521     if (!N1.getNode()->hasOneUse())
   2522       return SDValue();
   2523     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   2524     if (!N11C || N11C->getZExtValue() != 0xFF)
   2525       return SDValue();
   2526     N1 = N1.getOperand(0);
   2527     LookPassAnd1 = true;
   2528   }
   2529 
   2530   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
   2531     std::swap(N0, N1);
   2532   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
   2533     return SDValue();
   2534   if (!N0.getNode()->hasOneUse() ||
   2535       !N1.getNode()->hasOneUse())
   2536     return SDValue();
   2537 
   2538   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   2539   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
   2540   if (!N01C || !N11C)
   2541     return SDValue();
   2542   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
   2543     return SDValue();
   2544 
   2545   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
   2546   SDValue N00 = N0->getOperand(0);
   2547   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
   2548     if (!N00.getNode()->hasOneUse())
   2549       return SDValue();
   2550     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
   2551     if (!N001C || N001C->getZExtValue() != 0xFF)
   2552       return SDValue();
   2553     N00 = N00.getOperand(0);
   2554     LookPassAnd0 = true;
   2555   }
   2556 
   2557   SDValue N10 = N1->getOperand(0);
   2558   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
   2559     if (!N10.getNode()->hasOneUse())
   2560       return SDValue();
   2561     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
   2562     if (!N101C || N101C->getZExtValue() != 0xFF00)
   2563       return SDValue();
   2564     N10 = N10.getOperand(0);
   2565     LookPassAnd1 = true;
   2566   }
   2567 
   2568   if (N00 != N10)
   2569     return SDValue();
   2570 
   2571   // Make sure everything beyond the low halfword is zero since the SRL 16
   2572   // will clear the top bits.
   2573   unsigned OpSizeInBits = VT.getSizeInBits();
   2574   if (DemandHighBits && OpSizeInBits > 16 &&
   2575       (!LookPassAnd0 || !LookPassAnd1) &&
   2576       !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
   2577     return SDValue();
   2578 
   2579   SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
   2580   if (OpSizeInBits > 16)
   2581     Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
   2582                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
   2583   return Res;
   2584 }
   2585 
   2586 /// isBSwapHWordElement - Return true if the specified node is an element
   2587 /// that makes up a 32-bit packed halfword byteswap. i.e.
   2588 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
   2589 static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
   2590   if (!N.getNode()->hasOneUse())
   2591     return false;
   2592 
   2593   unsigned Opc = N.getOpcode();
   2594   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
   2595     return false;
   2596 
   2597   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   2598   if (!N1C)
   2599     return false;
   2600 
   2601   unsigned Num;
   2602   switch (N1C->getZExtValue()) {
   2603   default:
   2604     return false;
   2605   case 0xFF:       Num = 0; break;
   2606   case 0xFF00:     Num = 1; break;
   2607   case 0xFF0000:   Num = 2; break;
   2608   case 0xFF000000: Num = 3; break;
   2609   }
   2610 
   2611   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
   2612   SDValue N0 = N.getOperand(0);
   2613   if (Opc == ISD::AND) {
   2614     if (Num == 0 || Num == 2) {
   2615       // (x >> 8) & 0xff
   2616       // (x >> 8) & 0xff0000
   2617       if (N0.getOpcode() != ISD::SRL)
   2618         return false;
   2619       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   2620       if (!C || C->getZExtValue() != 8)
   2621         return false;
   2622     } else {
   2623       // (x << 8) & 0xff00
   2624       // (x << 8) & 0xff000000
   2625       if (N0.getOpcode() != ISD::SHL)
   2626         return false;
   2627       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   2628       if (!C || C->getZExtValue() != 8)
   2629         return false;
   2630     }
   2631   } else if (Opc == ISD::SHL) {
   2632     // (x & 0xff) << 8
   2633     // (x & 0xff0000) << 8
   2634     if (Num != 0 && Num != 2)
   2635       return false;
   2636     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   2637     if (!C || C->getZExtValue() != 8)
   2638       return false;
   2639   } else { // Opc == ISD::SRL
   2640     // (x & 0xff00) >> 8
   2641     // (x & 0xff000000) >> 8
   2642     if (Num != 1 && Num != 3)
   2643       return false;
   2644     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
   2645     if (!C || C->getZExtValue() != 8)
   2646       return false;
   2647   }
   2648 
   2649   if (Parts[Num])
   2650     return false;
   2651 
   2652   Parts[Num] = N0.getOperand(0).getNode();
   2653   return true;
   2654 }
   2655 
   2656 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
   2657 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
   2658 /// => (rotl (bswap x), 16)
   2659 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
   2660   if (!LegalOperations)
   2661     return SDValue();
   2662 
   2663   EVT VT = N->getValueType(0);
   2664   if (VT != MVT::i32)
   2665     return SDValue();
   2666   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
   2667     return SDValue();
   2668 
   2669   SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
   2670   // Look for either
   2671   // (or (or (and), (and)), (or (and), (and)))
   2672   // (or (or (or (and), (and)), (and)), (and))
   2673   if (N0.getOpcode() != ISD::OR)
   2674     return SDValue();
   2675   SDValue N00 = N0.getOperand(0);
   2676   SDValue N01 = N0.getOperand(1);
   2677 
   2678   if (N1.getOpcode() == ISD::OR) {
   2679     // (or (or (and), (and)), (or (and), (and)))
   2680     SDValue N000 = N00.getOperand(0);
   2681     if (!isBSwapHWordElement(N000, Parts))
   2682       return SDValue();
   2683 
   2684     SDValue N001 = N00.getOperand(1);
   2685     if (!isBSwapHWordElement(N001, Parts))
   2686       return SDValue();
   2687     SDValue N010 = N01.getOperand(0);
   2688     if (!isBSwapHWordElement(N010, Parts))
   2689       return SDValue();
   2690     SDValue N011 = N01.getOperand(1);
   2691     if (!isBSwapHWordElement(N011, Parts))
   2692       return SDValue();
   2693   } else {
   2694     // (or (or (or (and), (and)), (and)), (and))
   2695     if (!isBSwapHWordElement(N1, Parts))
   2696       return SDValue();
   2697     if (!isBSwapHWordElement(N01, Parts))
   2698       return SDValue();
   2699     if (N00.getOpcode() != ISD::OR)
   2700       return SDValue();
   2701     SDValue N000 = N00.getOperand(0);
   2702     if (!isBSwapHWordElement(N000, Parts))
   2703       return SDValue();
   2704     SDValue N001 = N00.getOperand(1);
   2705     if (!isBSwapHWordElement(N001, Parts))
   2706       return SDValue();
   2707   }
   2708 
   2709   // Make sure the parts are all coming from the same node.
   2710   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
   2711     return SDValue();
   2712 
   2713   SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
   2714                               SDValue(Parts[0],0));
   2715 
   2716   // Result of the bswap should be rotated by 16. If it's not legal, than
   2717   // do  (x << 16) | (x >> 16).
   2718   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
   2719   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
   2720     return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
   2721   else if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
   2722     return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
   2723   return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
   2724                      DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
   2725                      DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
   2726 }
   2727 
   2728 SDValue DAGCombiner::visitOR(SDNode *N) {
   2729   SDValue N0 = N->getOperand(0);
   2730   SDValue N1 = N->getOperand(1);
   2731   SDValue LL, LR, RL, RR, CC0, CC1;
   2732   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   2733   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   2734   EVT VT = N1.getValueType();
   2735 
   2736   // fold vector ops
   2737   if (VT.isVector()) {
   2738     SDValue FoldedVOp = SimplifyVBinOp(N);
   2739     if (FoldedVOp.getNode()) return FoldedVOp;
   2740   }
   2741 
   2742   // fold (or x, undef) -> -1
   2743   if (!LegalOperations &&
   2744       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
   2745     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
   2746     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
   2747   }
   2748   // fold (or c1, c2) -> c1|c2
   2749   if (N0C && N1C)
   2750     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
   2751   // canonicalize constant to RHS
   2752   if (N0C && !N1C)
   2753     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
   2754   // fold (or x, 0) -> x
   2755   if (N1C && N1C->isNullValue())
   2756     return N0;
   2757   // fold (or x, -1) -> -1
   2758   if (N1C && N1C->isAllOnesValue())
   2759     return N1;
   2760   // fold (or x, c) -> c iff (x & ~c) == 0
   2761   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
   2762     return N1;
   2763 
   2764   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
   2765   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
   2766   if (BSwap.getNode() != 0)
   2767     return BSwap;
   2768   BSwap = MatchBSwapHWordLow(N, N0, N1);
   2769   if (BSwap.getNode() != 0)
   2770     return BSwap;
   2771 
   2772   // reassociate or
   2773   SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
   2774   if (ROR.getNode() != 0)
   2775     return ROR;
   2776   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
   2777   // iff (c1 & c2) == 0.
   2778   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
   2779              isa<ConstantSDNode>(N0.getOperand(1))) {
   2780     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
   2781     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
   2782       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   2783                          DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
   2784                                      N0.getOperand(0), N1),
   2785                          DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
   2786   }
   2787   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
   2788   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
   2789     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
   2790     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
   2791 
   2792     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
   2793         LL.getValueType().isInteger()) {
   2794       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
   2795       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
   2796       if (cast<ConstantSDNode>(LR)->isNullValue() &&
   2797           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
   2798         SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
   2799                                      LR.getValueType(), LL, RL);
   2800         AddToWorkList(ORNode.getNode());
   2801         return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
   2802       }
   2803       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
   2804       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
   2805       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
   2806           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
   2807         SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
   2808                                       LR.getValueType(), LL, RL);
   2809         AddToWorkList(ANDNode.getNode());
   2810         return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
   2811       }
   2812     }
   2813     // canonicalize equivalent to ll == rl
   2814     if (LL == RR && LR == RL) {
   2815       Op1 = ISD::getSetCCSwappedOperands(Op1);
   2816       std::swap(RL, RR);
   2817     }
   2818     if (LL == RL && LR == RR) {
   2819       bool isInteger = LL.getValueType().isInteger();
   2820       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
   2821       if (Result != ISD::SETCC_INVALID &&
   2822           (!LegalOperations || TLI.isCondCodeLegal(Result, LL.getValueType())))
   2823         return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
   2824                             LL, LR, Result);
   2825     }
   2826   }
   2827 
   2828   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
   2829   if (N0.getOpcode() == N1.getOpcode()) {
   2830     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   2831     if (Tmp.getNode()) return Tmp;
   2832   }
   2833 
   2834   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
   2835   if (N0.getOpcode() == ISD::AND &&
   2836       N1.getOpcode() == ISD::AND &&
   2837       N0.getOperand(1).getOpcode() == ISD::Constant &&
   2838       N1.getOperand(1).getOpcode() == ISD::Constant &&
   2839       // Don't increase # computations.
   2840       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
   2841     // We can only do this xform if we know that bits from X that are set in C2
   2842     // but not in C1 are already zero.  Likewise for Y.
   2843     const APInt &LHSMask =
   2844       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   2845     const APInt &RHSMask =
   2846       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
   2847 
   2848     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
   2849         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
   2850       SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
   2851                               N0.getOperand(0), N1.getOperand(0));
   2852       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
   2853                          DAG.getConstant(LHSMask | RHSMask, VT));
   2854     }
   2855   }
   2856 
   2857   // See if this is some rotate idiom.
   2858   if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
   2859     return SDValue(Rot, 0);
   2860 
   2861   // Simplify the operands using demanded-bits information.
   2862   if (!VT.isVector() &&
   2863       SimplifyDemandedBits(SDValue(N, 0)))
   2864     return SDValue(N, 0);
   2865 
   2866   return SDValue();
   2867 }
   2868 
   2869 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
   2870 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
   2871   if (Op.getOpcode() == ISD::AND) {
   2872     if (isa<ConstantSDNode>(Op.getOperand(1))) {
   2873       Mask = Op.getOperand(1);
   2874       Op = Op.getOperand(0);
   2875     } else {
   2876       return false;
   2877     }
   2878   }
   2879 
   2880   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
   2881     Shift = Op;
   2882     return true;
   2883   }
   2884 
   2885   return false;
   2886 }
   2887 
   2888 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
   2889 // idioms for rotate, and if the target supports rotation instructions, generate
   2890 // a rot[lr].
   2891 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
   2892   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
   2893   EVT VT = LHS.getValueType();
   2894   if (!TLI.isTypeLegal(VT)) return 0;
   2895 
   2896   // The target must have at least one rotate flavor.
   2897   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
   2898   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
   2899   if (!HasROTL && !HasROTR) return 0;
   2900 
   2901   // Match "(X shl/srl V1) & V2" where V2 may not be present.
   2902   SDValue LHSShift;   // The shift.
   2903   SDValue LHSMask;    // AND value if any.
   2904   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
   2905     return 0; // Not part of a rotate.
   2906 
   2907   SDValue RHSShift;   // The shift.
   2908   SDValue RHSMask;    // AND value if any.
   2909   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
   2910     return 0; // Not part of a rotate.
   2911 
   2912   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
   2913     return 0;   // Not shifting the same value.
   2914 
   2915   if (LHSShift.getOpcode() == RHSShift.getOpcode())
   2916     return 0;   // Shifts must disagree.
   2917 
   2918   // Canonicalize shl to left side in a shl/srl pair.
   2919   if (RHSShift.getOpcode() == ISD::SHL) {
   2920     std::swap(LHS, RHS);
   2921     std::swap(LHSShift, RHSShift);
   2922     std::swap(LHSMask , RHSMask );
   2923   }
   2924 
   2925   unsigned OpSizeInBits = VT.getSizeInBits();
   2926   SDValue LHSShiftArg = LHSShift.getOperand(0);
   2927   SDValue LHSShiftAmt = LHSShift.getOperand(1);
   2928   SDValue RHSShiftAmt = RHSShift.getOperand(1);
   2929 
   2930   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
   2931   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
   2932   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
   2933       RHSShiftAmt.getOpcode() == ISD::Constant) {
   2934     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
   2935     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
   2936     if ((LShVal + RShVal) != OpSizeInBits)
   2937       return 0;
   2938 
   2939     SDValue Rot;
   2940     if (HasROTL)
   2941       Rot = DAG.getNode(ISD::ROTL, DL, VT, LHSShiftArg, LHSShiftAmt);
   2942     else
   2943       Rot = DAG.getNode(ISD::ROTR, DL, VT, LHSShiftArg, RHSShiftAmt);
   2944 
   2945     // If there is an AND of either shifted operand, apply it to the result.
   2946     if (LHSMask.getNode() || RHSMask.getNode()) {
   2947       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
   2948 
   2949       if (LHSMask.getNode()) {
   2950         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
   2951         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
   2952       }
   2953       if (RHSMask.getNode()) {
   2954         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
   2955         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
   2956       }
   2957 
   2958       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
   2959     }
   2960 
   2961     return Rot.getNode();
   2962   }
   2963 
   2964   // If there is a mask here, and we have a variable shift, we can't be sure
   2965   // that we're masking out the right stuff.
   2966   if (LHSMask.getNode() || RHSMask.getNode())
   2967     return 0;
   2968 
   2969   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
   2970   // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
   2971   if (RHSShiftAmt.getOpcode() == ISD::SUB &&
   2972       LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
   2973     if (ConstantSDNode *SUBC =
   2974           dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
   2975       if (SUBC->getAPIntValue() == OpSizeInBits) {
   2976         if (HasROTL)
   2977           return DAG.getNode(ISD::ROTL, DL, VT,
   2978                              LHSShiftArg, LHSShiftAmt).getNode();
   2979         else
   2980           return DAG.getNode(ISD::ROTR, DL, VT,
   2981                              LHSShiftArg, RHSShiftAmt).getNode();
   2982       }
   2983     }
   2984   }
   2985 
   2986   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
   2987   // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
   2988   if (LHSShiftAmt.getOpcode() == ISD::SUB &&
   2989       RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
   2990     if (ConstantSDNode *SUBC =
   2991           dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
   2992       if (SUBC->getAPIntValue() == OpSizeInBits) {
   2993         if (HasROTR)
   2994           return DAG.getNode(ISD::ROTR, DL, VT,
   2995                              LHSShiftArg, RHSShiftAmt).getNode();
   2996         else
   2997           return DAG.getNode(ISD::ROTL, DL, VT,
   2998                              LHSShiftArg, LHSShiftAmt).getNode();
   2999       }
   3000     }
   3001   }
   3002 
   3003   // Look for sign/zext/any-extended or truncate cases:
   3004   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
   3005        || LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
   3006        || LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
   3007        || LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
   3008       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND
   3009        || RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND
   3010        || RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND
   3011        || RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
   3012     SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
   3013     SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
   3014     if (RExtOp0.getOpcode() == ISD::SUB &&
   3015         RExtOp0.getOperand(1) == LExtOp0) {
   3016       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
   3017       //   (rotl x, y)
   3018       // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
   3019       //   (rotr x, (sub 32, y))
   3020       if (ConstantSDNode *SUBC =
   3021             dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
   3022         if (SUBC->getAPIntValue() == OpSizeInBits) {
   3023           return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
   3024                              LHSShiftArg,
   3025                              HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
   3026         }
   3027       }
   3028     } else if (LExtOp0.getOpcode() == ISD::SUB &&
   3029                RExtOp0 == LExtOp0.getOperand(1)) {
   3030       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
   3031       //   (rotr x, y)
   3032       // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
   3033       //   (rotl x, (sub 32, y))
   3034       if (ConstantSDNode *SUBC =
   3035             dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
   3036         if (SUBC->getAPIntValue() == OpSizeInBits) {
   3037           return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
   3038                              LHSShiftArg,
   3039                              HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
   3040         }
   3041       }
   3042     }
   3043   }
   3044 
   3045   return 0;
   3046 }
   3047 
   3048 SDValue DAGCombiner::visitXOR(SDNode *N) {
   3049   SDValue N0 = N->getOperand(0);
   3050   SDValue N1 = N->getOperand(1);
   3051   SDValue LHS, RHS, CC;
   3052   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3053   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3054   EVT VT = N0.getValueType();
   3055 
   3056   // fold vector ops
   3057   if (VT.isVector()) {
   3058     SDValue FoldedVOp = SimplifyVBinOp(N);
   3059     if (FoldedVOp.getNode()) return FoldedVOp;
   3060   }
   3061 
   3062   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
   3063   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
   3064     return DAG.getConstant(0, VT);
   3065   // fold (xor x, undef) -> undef
   3066   if (N0.getOpcode() == ISD::UNDEF)
   3067     return N0;
   3068   if (N1.getOpcode() == ISD::UNDEF)
   3069     return N1;
   3070   // fold (xor c1, c2) -> c1^c2
   3071   if (N0C && N1C)
   3072     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
   3073   // canonicalize constant to RHS
   3074   if (N0C && !N1C)
   3075     return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
   3076   // fold (xor x, 0) -> x
   3077   if (N1C && N1C->isNullValue())
   3078     return N0;
   3079   // reassociate xor
   3080   SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
   3081   if (RXOR.getNode() != 0)
   3082     return RXOR;
   3083 
   3084   // fold !(x cc y) -> (x !cc y)
   3085   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
   3086     bool isInt = LHS.getValueType().isInteger();
   3087     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
   3088                                                isInt);
   3089 
   3090     if (!LegalOperations || TLI.isCondCodeLegal(NotCC, LHS.getValueType())) {
   3091       switch (N0.getOpcode()) {
   3092       default:
   3093         llvm_unreachable("Unhandled SetCC Equivalent!");
   3094       case ISD::SETCC:
   3095         return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
   3096       case ISD::SELECT_CC:
   3097         return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
   3098                                N0.getOperand(3), NotCC);
   3099       }
   3100     }
   3101   }
   3102 
   3103   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
   3104   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
   3105       N0.getNode()->hasOneUse() &&
   3106       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
   3107     SDValue V = N0.getOperand(0);
   3108     V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
   3109                     DAG.getConstant(1, V.getValueType()));
   3110     AddToWorkList(V.getNode());
   3111     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
   3112   }
   3113 
   3114   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
   3115   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
   3116       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
   3117     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
   3118     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
   3119       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
   3120       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
   3121       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
   3122       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
   3123       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
   3124     }
   3125   }
   3126   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
   3127   if (N1C && N1C->isAllOnesValue() &&
   3128       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
   3129     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
   3130     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
   3131       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
   3132       LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
   3133       RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
   3134       AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
   3135       return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
   3136     }
   3137   }
   3138   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
   3139   if (N1C && N0.getOpcode() == ISD::XOR) {
   3140     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
   3141     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3142     if (N00C)
   3143       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
   3144                          DAG.getConstant(N1C->getAPIntValue() ^
   3145                                          N00C->getAPIntValue(), VT));
   3146     if (N01C)
   3147       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
   3148                          DAG.getConstant(N1C->getAPIntValue() ^
   3149                                          N01C->getAPIntValue(), VT));
   3150   }
   3151   // fold (xor x, x) -> 0
   3152   if (N0 == N1)
   3153     return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
   3154 
   3155   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
   3156   if (N0.getOpcode() == N1.getOpcode()) {
   3157     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
   3158     if (Tmp.getNode()) return Tmp;
   3159   }
   3160 
   3161   // Simplify the expression using non-local knowledge.
   3162   if (!VT.isVector() &&
   3163       SimplifyDemandedBits(SDValue(N, 0)))
   3164     return SDValue(N, 0);
   3165 
   3166   return SDValue();
   3167 }
   3168 
   3169 /// visitShiftByConstant - Handle transforms common to the three shifts, when
   3170 /// the shift amount is a constant.
   3171 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
   3172   SDNode *LHS = N->getOperand(0).getNode();
   3173   if (!LHS->hasOneUse()) return SDValue();
   3174 
   3175   // We want to pull some binops through shifts, so that we have (and (shift))
   3176   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
   3177   // thing happens with address calculations, so it's important to canonicalize
   3178   // it.
   3179   bool HighBitSet = false;  // Can we transform this if the high bit is set?
   3180 
   3181   switch (LHS->getOpcode()) {
   3182   default: return SDValue();
   3183   case ISD::OR:
   3184   case ISD::XOR:
   3185     HighBitSet = false; // We can only transform sra if the high bit is clear.
   3186     break;
   3187   case ISD::AND:
   3188     HighBitSet = true;  // We can only transform sra if the high bit is set.
   3189     break;
   3190   case ISD::ADD:
   3191     if (N->getOpcode() != ISD::SHL)
   3192       return SDValue(); // only shl(add) not sr[al](add).
   3193     HighBitSet = false; // We can only transform sra if the high bit is clear.
   3194     break;
   3195   }
   3196 
   3197   // We require the RHS of the binop to be a constant as well.
   3198   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
   3199   if (!BinOpCst) return SDValue();
   3200 
   3201   // FIXME: disable this unless the input to the binop is a shift by a constant.
   3202   // If it is not a shift, it pessimizes some common cases like:
   3203   //
   3204   //    void foo(int *X, int i) { X[i & 1235] = 1; }
   3205   //    int bar(int *X, int i) { return X[i & 255]; }
   3206   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
   3207   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
   3208        BinOpLHSVal->getOpcode() != ISD::SRA &&
   3209        BinOpLHSVal->getOpcode() != ISD::SRL) ||
   3210       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
   3211     return SDValue();
   3212 
   3213   EVT VT = N->getValueType(0);
   3214 
   3215   // If this is a signed shift right, and the high bit is modified by the
   3216   // logical operation, do not perform the transformation. The highBitSet
   3217   // boolean indicates the value of the high bit of the constant which would
   3218   // cause it to be modified for this operation.
   3219   if (N->getOpcode() == ISD::SRA) {
   3220     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
   3221     if (BinOpRHSSignSet != HighBitSet)
   3222       return SDValue();
   3223   }
   3224 
   3225   // Fold the constants, shifting the binop RHS by the shift amount.
   3226   SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
   3227                                N->getValueType(0),
   3228                                LHS->getOperand(1), N->getOperand(1));
   3229 
   3230   // Create the new shift.
   3231   SDValue NewShift = DAG.getNode(N->getOpcode(),
   3232                                  LHS->getOperand(0).getDebugLoc(),
   3233                                  VT, LHS->getOperand(0), N->getOperand(1));
   3234 
   3235   // Create the new binop.
   3236   return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
   3237 }
   3238 
   3239 SDValue DAGCombiner::visitSHL(SDNode *N) {
   3240   SDValue N0 = N->getOperand(0);
   3241   SDValue N1 = N->getOperand(1);
   3242   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3243   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3244   EVT VT = N0.getValueType();
   3245   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
   3246 
   3247   // fold (shl c1, c2) -> c1<<c2
   3248   if (N0C && N1C)
   3249     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
   3250   // fold (shl 0, x) -> 0
   3251   if (N0C && N0C->isNullValue())
   3252     return N0;
   3253   // fold (shl x, c >= size(x)) -> undef
   3254   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   3255     return DAG.getUNDEF(VT);
   3256   // fold (shl x, 0) -> x
   3257   if (N1C && N1C->isNullValue())
   3258     return N0;
   3259   // fold (shl undef, x) -> 0
   3260   if (N0.getOpcode() == ISD::UNDEF)
   3261     return DAG.getConstant(0, VT);
   3262   // if (shl x, c) is known to be zero, return 0
   3263   if (DAG.MaskedValueIsZero(SDValue(N, 0),
   3264                             APInt::getAllOnesValue(OpSizeInBits)))
   3265     return DAG.getConstant(0, VT);
   3266   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
   3267   if (N1.getOpcode() == ISD::TRUNCATE &&
   3268       N1.getOperand(0).getOpcode() == ISD::AND &&
   3269       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
   3270     SDValue N101 = N1.getOperand(0).getOperand(1);
   3271     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
   3272       EVT TruncVT = N1.getValueType();
   3273       SDValue N100 = N1.getOperand(0).getOperand(0);
   3274       APInt TruncC = N101C->getAPIntValue();
   3275       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
   3276       return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
   3277                          DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
   3278                                      DAG.getNode(ISD::TRUNCATE,
   3279                                                  N->getDebugLoc(),
   3280                                                  TruncVT, N100),
   3281                                      DAG.getConstant(TruncC, TruncVT)));
   3282     }
   3283   }
   3284 
   3285   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   3286     return SDValue(N, 0);
   3287 
   3288   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
   3289   if (N1C && N0.getOpcode() == ISD::SHL &&
   3290       N0.getOperand(1).getOpcode() == ISD::Constant) {
   3291     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
   3292     uint64_t c2 = N1C->getZExtValue();
   3293     if (c1 + c2 >= OpSizeInBits)
   3294       return DAG.getConstant(0, VT);
   3295     return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
   3296                        DAG.getConstant(c1 + c2, N1.getValueType()));
   3297   }
   3298 
   3299   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
   3300   // For this to be valid, the second form must not preserve any of the bits
   3301   // that are shifted out by the inner shift in the first form.  This means
   3302   // the outer shift size must be >= the number of bits added by the ext.
   3303   // As a corollary, we don't care what kind of ext it is.
   3304   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
   3305               N0.getOpcode() == ISD::ANY_EXTEND ||
   3306               N0.getOpcode() == ISD::SIGN_EXTEND) &&
   3307       N0.getOperand(0).getOpcode() == ISD::SHL &&
   3308       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
   3309     uint64_t c1 =
   3310       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
   3311     uint64_t c2 = N1C->getZExtValue();
   3312     EVT InnerShiftVT = N0.getOperand(0).getValueType();
   3313     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
   3314     if (c2 >= OpSizeInBits - InnerShiftSize) {
   3315       if (c1 + c2 >= OpSizeInBits)
   3316         return DAG.getConstant(0, VT);
   3317       return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
   3318                          DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
   3319                                      N0.getOperand(0)->getOperand(0)),
   3320                          DAG.getConstant(c1 + c2, N1.getValueType()));
   3321     }
   3322   }
   3323 
   3324   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
   3325   //                               (and (srl x, (sub c1, c2), MASK)
   3326   if (N1C && N0.getOpcode() == ISD::SRL &&
   3327       N0.getOperand(1).getOpcode() == ISD::Constant) {
   3328     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
   3329     if (c1 < VT.getSizeInBits()) {
   3330       uint64_t c2 = N1C->getZExtValue();
   3331       APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
   3332                                          VT.getSizeInBits() - c1);
   3333       SDValue Shift;
   3334       if (c2 > c1) {
   3335         Mask = Mask.shl(c2-c1);
   3336         Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
   3337                             DAG.getConstant(c2-c1, N1.getValueType()));
   3338       } else {
   3339         Mask = Mask.lshr(c1-c2);
   3340         Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
   3341                             DAG.getConstant(c1-c2, N1.getValueType()));
   3342       }
   3343       return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
   3344                          DAG.getConstant(Mask, VT));
   3345     }
   3346   }
   3347   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
   3348   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
   3349     SDValue HiBitsMask =
   3350       DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
   3351                                             VT.getSizeInBits() -
   3352                                               N1C->getZExtValue()),
   3353                       VT);
   3354     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
   3355                        HiBitsMask);
   3356   }
   3357 
   3358   if (N1C) {
   3359     SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
   3360     if (NewSHL.getNode())
   3361       return NewSHL;
   3362   }
   3363 
   3364   return SDValue();
   3365 }
   3366 
   3367 SDValue DAGCombiner::visitSRA(SDNode *N) {
   3368   SDValue N0 = N->getOperand(0);
   3369   SDValue N1 = N->getOperand(1);
   3370   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3371   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3372   EVT VT = N0.getValueType();
   3373   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
   3374 
   3375   // fold (sra c1, c2) -> (sra c1, c2)
   3376   if (N0C && N1C)
   3377     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
   3378   // fold (sra 0, x) -> 0
   3379   if (N0C && N0C->isNullValue())
   3380     return N0;
   3381   // fold (sra -1, x) -> -1
   3382   if (N0C && N0C->isAllOnesValue())
   3383     return N0;
   3384   // fold (sra x, (setge c, size(x))) -> undef
   3385   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   3386     return DAG.getUNDEF(VT);
   3387   // fold (sra x, 0) -> x
   3388   if (N1C && N1C->isNullValue())
   3389     return N0;
   3390   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
   3391   // sext_inreg.
   3392   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
   3393     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
   3394     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
   3395     if (VT.isVector())
   3396       ExtVT = EVT::getVectorVT(*DAG.getContext(),
   3397                                ExtVT, VT.getVectorNumElements());
   3398     if ((!LegalOperations ||
   3399          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
   3400       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
   3401                          N0.getOperand(0), DAG.getValueType(ExtVT));
   3402   }
   3403 
   3404   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
   3405   if (N1C && N0.getOpcode() == ISD::SRA) {
   3406     if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   3407       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
   3408       if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
   3409       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
   3410                          DAG.getConstant(Sum, N1C->getValueType(0)));
   3411     }
   3412   }
   3413 
   3414   // fold (sra (shl X, m), (sub result_size, n))
   3415   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
   3416   // result_size - n != m.
   3417   // If truncate is free for the target sext(shl) is likely to result in better
   3418   // code.
   3419   if (N0.getOpcode() == ISD::SHL) {
   3420     // Get the two constanst of the shifts, CN0 = m, CN = n.
   3421     const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   3422     if (N01C && N1C) {
   3423       // Determine what the truncate's result bitsize and type would be.
   3424       EVT TruncVT =
   3425         EVT::getIntegerVT(*DAG.getContext(),
   3426                           OpSizeInBits - N1C->getZExtValue());
   3427       // Determine the residual right-shift amount.
   3428       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
   3429 
   3430       // If the shift is not a no-op (in which case this should be just a sign
   3431       // extend already), the truncated to type is legal, sign_extend is legal
   3432       // on that type, and the truncate to that type is both legal and free,
   3433       // perform the transform.
   3434       if ((ShiftAmt > 0) &&
   3435           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
   3436           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
   3437           TLI.isTruncateFree(VT, TruncVT)) {
   3438 
   3439           SDValue Amt = DAG.getConstant(ShiftAmt,
   3440               getShiftAmountTy(N0.getOperand(0).getValueType()));
   3441           SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
   3442                                       N0.getOperand(0), Amt);
   3443           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
   3444                                       Shift);
   3445           return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
   3446                              N->getValueType(0), Trunc);
   3447       }
   3448     }
   3449   }
   3450 
   3451   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
   3452   if (N1.getOpcode() == ISD::TRUNCATE &&
   3453       N1.getOperand(0).getOpcode() == ISD::AND &&
   3454       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
   3455     SDValue N101 = N1.getOperand(0).getOperand(1);
   3456     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
   3457       EVT TruncVT = N1.getValueType();
   3458       SDValue N100 = N1.getOperand(0).getOperand(0);
   3459       APInt TruncC = N101C->getAPIntValue();
   3460       TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
   3461       return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
   3462                          DAG.getNode(ISD::AND, N->getDebugLoc(),
   3463                                      TruncVT,
   3464                                      DAG.getNode(ISD::TRUNCATE,
   3465                                                  N->getDebugLoc(),
   3466                                                  TruncVT, N100),
   3467                                      DAG.getConstant(TruncC, TruncVT)));
   3468     }
   3469   }
   3470 
   3471   // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
   3472   //      if c1 is equal to the number of bits the trunc removes
   3473   if (N0.getOpcode() == ISD::TRUNCATE &&
   3474       (N0.getOperand(0).getOpcode() == ISD::SRL ||
   3475        N0.getOperand(0).getOpcode() == ISD::SRA) &&
   3476       N0.getOperand(0).hasOneUse() &&
   3477       N0.getOperand(0).getOperand(1).hasOneUse() &&
   3478       N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
   3479     EVT LargeVT = N0.getOperand(0).getValueType();
   3480     ConstantSDNode *LargeShiftAmt =
   3481       cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
   3482 
   3483     if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
   3484         LargeShiftAmt->getZExtValue()) {
   3485       SDValue Amt =
   3486         DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
   3487               getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
   3488       SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
   3489                                 N0.getOperand(0).getOperand(0), Amt);
   3490       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
   3491     }
   3492   }
   3493 
   3494   // Simplify, based on bits shifted out of the LHS.
   3495   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   3496     return SDValue(N, 0);
   3497 
   3498 
   3499   // If the sign bit is known to be zero, switch this to a SRL.
   3500   if (DAG.SignBitIsZero(N0))
   3501     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
   3502 
   3503   if (N1C) {
   3504     SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
   3505     if (NewSRA.getNode())
   3506       return NewSRA;
   3507   }
   3508 
   3509   return SDValue();
   3510 }
   3511 
   3512 SDValue DAGCombiner::visitSRL(SDNode *N) {
   3513   SDValue N0 = N->getOperand(0);
   3514   SDValue N1 = N->getOperand(1);
   3515   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3516   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3517   EVT VT = N0.getValueType();
   3518   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
   3519 
   3520   // fold (srl c1, c2) -> c1 >>u c2
   3521   if (N0C && N1C)
   3522     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
   3523   // fold (srl 0, x) -> 0
   3524   if (N0C && N0C->isNullValue())
   3525     return N0;
   3526   // fold (srl x, c >= size(x)) -> undef
   3527   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
   3528     return DAG.getUNDEF(VT);
   3529   // fold (srl x, 0) -> x
   3530   if (N1C && N1C->isNullValue())
   3531     return N0;
   3532   // if (srl x, c) is known to be zero, return 0
   3533   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
   3534                                    APInt::getAllOnesValue(OpSizeInBits)))
   3535     return DAG.getConstant(0, VT);
   3536 
   3537   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
   3538   if (N1C && N0.getOpcode() == ISD::SRL &&
   3539       N0.getOperand(1).getOpcode() == ISD::Constant) {
   3540     uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
   3541     uint64_t c2 = N1C->getZExtValue();
   3542     if (c1 + c2 >= OpSizeInBits)
   3543       return DAG.getConstant(0, VT);
   3544     return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
   3545                        DAG.getConstant(c1 + c2, N1.getValueType()));
   3546   }
   3547 
   3548   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
   3549   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
   3550       N0.getOperand(0).getOpcode() == ISD::SRL &&
   3551       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
   3552     uint64_t c1 =
   3553       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
   3554     uint64_t c2 = N1C->getZExtValue();
   3555     EVT InnerShiftVT = N0.getOperand(0).getValueType();
   3556     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
   3557     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
   3558     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
   3559     if (c1 + OpSizeInBits == InnerShiftSize) {
   3560       if (c1 + c2 >= InnerShiftSize)
   3561         return DAG.getConstant(0, VT);
   3562       return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
   3563                          DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
   3564                                      N0.getOperand(0)->getOperand(0),
   3565                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
   3566     }
   3567   }
   3568 
   3569   // fold (srl (shl x, c), c) -> (and x, cst2)
   3570   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
   3571       N0.getValueSizeInBits() <= 64) {
   3572     uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
   3573     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
   3574                        DAG.getConstant(~0ULL >> ShAmt, VT));
   3575   }
   3576 
   3577 
   3578   // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
   3579   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
   3580     // Shifting in all undef bits?
   3581     EVT SmallVT = N0.getOperand(0).getValueType();
   3582     if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
   3583       return DAG.getUNDEF(VT);
   3584 
   3585     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
   3586       uint64_t ShiftAmt = N1C->getZExtValue();
   3587       SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
   3588                                        N0.getOperand(0),
   3589                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
   3590       AddToWorkList(SmallShift.getNode());
   3591       return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
   3592     }
   3593   }
   3594 
   3595   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
   3596   // bit, which is unmodified by sra.
   3597   if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
   3598     if (N0.getOpcode() == ISD::SRA)
   3599       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
   3600   }
   3601 
   3602   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
   3603   if (N1C && N0.getOpcode() == ISD::CTLZ &&
   3604       N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
   3605     APInt KnownZero, KnownOne;
   3606     APInt Mask = APInt::getAllOnesValue(VT.getScalarType().getSizeInBits());
   3607     DAG.ComputeMaskedBits(N0.getOperand(0), Mask, KnownZero, KnownOne);
   3608 
   3609     // If any of the input bits are KnownOne, then the input couldn't be all
   3610     // zeros, thus the result of the srl will always be zero.
   3611     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
   3612 
   3613     // If all of the bits input the to ctlz node are known to be zero, then
   3614     // the result of the ctlz is "32" and the result of the shift is one.
   3615     APInt UnknownBits = ~KnownZero & Mask;
   3616     if (UnknownBits == 0) return DAG.getConstant(1, VT);
   3617 
   3618     // Otherwise, check to see if there is exactly one bit input to the ctlz.
   3619     if ((UnknownBits & (UnknownBits - 1)) == 0) {
   3620       // Okay, we know that only that the single bit specified by UnknownBits
   3621       // could be set on input to the CTLZ node. If this bit is set, the SRL
   3622       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
   3623       // to an SRL/XOR pair, which is likely to simplify more.
   3624       unsigned ShAmt = UnknownBits.countTrailingZeros();
   3625       SDValue Op = N0.getOperand(0);
   3626 
   3627       if (ShAmt) {
   3628         Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
   3629                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
   3630         AddToWorkList(Op.getNode());
   3631       }
   3632 
   3633       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
   3634                          Op, DAG.getConstant(1, VT));
   3635     }
   3636   }
   3637 
   3638   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
   3639   if (N1.getOpcode() == ISD::TRUNCATE &&
   3640       N1.getOperand(0).getOpcode() == ISD::AND &&
   3641       N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
   3642     SDValue N101 = N1.getOperand(0).getOperand(1);
   3643     if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
   3644       EVT TruncVT = N1.getValueType();
   3645       SDValue N100 = N1.getOperand(0).getOperand(0);
   3646       APInt TruncC = N101C->getAPIntValue();
   3647       TruncC = TruncC.trunc(TruncVT.getSizeInBits());
   3648       return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
   3649                          DAG.getNode(ISD::AND, N->getDebugLoc(),
   3650                                      TruncVT,
   3651                                      DAG.getNode(ISD::TRUNCATE,
   3652                                                  N->getDebugLoc(),
   3653                                                  TruncVT, N100),
   3654                                      DAG.getConstant(TruncC, TruncVT)));
   3655     }
   3656   }
   3657 
   3658   // fold operands of srl based on knowledge that the low bits are not
   3659   // demanded.
   3660   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
   3661     return SDValue(N, 0);
   3662 
   3663   if (N1C) {
   3664     SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
   3665     if (NewSRL.getNode())
   3666       return NewSRL;
   3667   }
   3668 
   3669   // Attempt to convert a srl of a load into a narrower zero-extending load.
   3670   SDValue NarrowLoad = ReduceLoadWidth(N);
   3671   if (NarrowLoad.getNode())
   3672     return NarrowLoad;
   3673 
   3674   // Here is a common situation. We want to optimize:
   3675   //
   3676   //   %a = ...
   3677   //   %b = and i32 %a, 2
   3678   //   %c = srl i32 %b, 1
   3679   //   brcond i32 %c ...
   3680   //
   3681   // into
   3682   //
   3683   //   %a = ...
   3684   //   %b = and %a, 2
   3685   //   %c = setcc eq %b, 0
   3686   //   brcond %c ...
   3687   //
   3688   // However when after the source operand of SRL is optimized into AND, the SRL
   3689   // itself may not be optimized further. Look for it and add the BRCOND into
   3690   // the worklist.
   3691   if (N->hasOneUse()) {
   3692     SDNode *Use = *N->use_begin();
   3693     if (Use->getOpcode() == ISD::BRCOND)
   3694       AddToWorkList(Use);
   3695     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
   3696       // Also look pass the truncate.
   3697       Use = *Use->use_begin();
   3698       if (Use->getOpcode() == ISD::BRCOND)
   3699         AddToWorkList(Use);
   3700     }
   3701   }
   3702 
   3703   return SDValue();
   3704 }
   3705 
   3706 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
   3707   SDValue N0 = N->getOperand(0);
   3708   EVT VT = N->getValueType(0);
   3709 
   3710   // fold (ctlz c1) -> c2
   3711   if (isa<ConstantSDNode>(N0))
   3712     return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
   3713   return SDValue();
   3714 }
   3715 
   3716 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
   3717   SDValue N0 = N->getOperand(0);
   3718   EVT VT = N->getValueType(0);
   3719 
   3720   // fold (cttz c1) -> c2
   3721   if (isa<ConstantSDNode>(N0))
   3722     return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
   3723   return SDValue();
   3724 }
   3725 
   3726 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
   3727   SDValue N0 = N->getOperand(0);
   3728   EVT VT = N->getValueType(0);
   3729 
   3730   // fold (ctpop c1) -> c2
   3731   if (isa<ConstantSDNode>(N0))
   3732     return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
   3733   return SDValue();
   3734 }
   3735 
   3736 SDValue DAGCombiner::visitSELECT(SDNode *N) {
   3737   SDValue N0 = N->getOperand(0);
   3738   SDValue N1 = N->getOperand(1);
   3739   SDValue N2 = N->getOperand(2);
   3740   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   3741   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
   3742   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
   3743   EVT VT = N->getValueType(0);
   3744   EVT VT0 = N0.getValueType();
   3745 
   3746   // fold (select C, X, X) -> X
   3747   if (N1 == N2)
   3748     return N1;
   3749   // fold (select true, X, Y) -> X
   3750   if (N0C && !N0C->isNullValue())
   3751     return N1;
   3752   // fold (select false, X, Y) -> Y
   3753   if (N0C && N0C->isNullValue())
   3754     return N2;
   3755   // fold (select C, 1, X) -> (or C, X)
   3756   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
   3757     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
   3758   // fold (select C, 0, 1) -> (xor C, 1)
   3759   if (VT.isInteger() &&
   3760       (VT0 == MVT::i1 ||
   3761        (VT0.isInteger() &&
   3762         TLI.getBooleanContents(false) == TargetLowering::ZeroOrOneBooleanContent)) &&
   3763       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
   3764     SDValue XORNode;
   3765     if (VT == VT0)
   3766       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
   3767                          N0, DAG.getConstant(1, VT0));
   3768     XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
   3769                           N0, DAG.getConstant(1, VT0));
   3770     AddToWorkList(XORNode.getNode());
   3771     if (VT.bitsGT(VT0))
   3772       return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
   3773     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
   3774   }
   3775   // fold (select C, 0, X) -> (and (not C), X)
   3776   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
   3777     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
   3778     AddToWorkList(NOTNode.getNode());
   3779     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
   3780   }
   3781   // fold (select C, X, 1) -> (or (not C), X)
   3782   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
   3783     SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
   3784     AddToWorkList(NOTNode.getNode());
   3785     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
   3786   }
   3787   // fold (select C, X, 0) -> (and C, X)
   3788   if (VT == MVT::i1 && N2C && N2C->isNullValue())
   3789     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
   3790   // fold (select X, X, Y) -> (or X, Y)
   3791   // fold (select X, 1, Y) -> (or X, Y)
   3792   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
   3793     return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
   3794   // fold (select X, Y, X) -> (and X, Y)
   3795   // fold (select X, Y, 0) -> (and X, Y)
   3796   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
   3797     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
   3798 
   3799   // If we can fold this based on the true/false value, do so.
   3800   if (SimplifySelectOps(N, N1, N2))
   3801     return SDValue(N, 0);  // Don't revisit N.
   3802 
   3803   // fold selects based on a setcc into other things, such as min/max/abs
   3804   if (N0.getOpcode() == ISD::SETCC) {
   3805     // FIXME:
   3806     // Check against MVT::Other for SELECT_CC, which is a workaround for targets
   3807     // having to say they don't support SELECT_CC on every type the DAG knows
   3808     // about, since there is no way to mark an opcode illegal at all value types
   3809     if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
   3810         TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
   3811       return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
   3812                          N0.getOperand(0), N0.getOperand(1),
   3813                          N1, N2, N0.getOperand(2));
   3814     return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
   3815   }
   3816 
   3817   return SDValue();
   3818 }
   3819 
   3820 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
   3821   SDValue N0 = N->getOperand(0);
   3822   SDValue N1 = N->getOperand(1);
   3823   SDValue N2 = N->getOperand(2);
   3824   SDValue N3 = N->getOperand(3);
   3825   SDValue N4 = N->getOperand(4);
   3826   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
   3827 
   3828   // fold select_cc lhs, rhs, x, x, cc -> x
   3829   if (N2 == N3)
   3830     return N2;
   3831 
   3832   // Determine if the condition we're dealing with is constant
   3833   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
   3834                               N0, N1, CC, N->getDebugLoc(), false);
   3835   if (SCC.getNode()) AddToWorkList(SCC.getNode());
   3836 
   3837   if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
   3838     if (!SCCC->isNullValue())
   3839       return N2;    // cond always true -> true val
   3840     else
   3841       return N3;    // cond always false -> false val
   3842   }
   3843 
   3844   // Fold to a simpler select_cc
   3845   if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
   3846     return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
   3847                        SCC.getOperand(0), SCC.getOperand(1), N2, N3,
   3848                        SCC.getOperand(2));
   3849 
   3850   // If we can fold this based on the true/false value, do so.
   3851   if (SimplifySelectOps(N, N2, N3))
   3852     return SDValue(N, 0);  // Don't revisit N.
   3853 
   3854   // fold select_cc into other things, such as min/max/abs
   3855   return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
   3856 }
   3857 
   3858 SDValue DAGCombiner::visitSETCC(SDNode *N) {
   3859   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
   3860                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
   3861                        N->getDebugLoc());
   3862 }
   3863 
   3864 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
   3865 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
   3866 // transformation. Returns true if extension are possible and the above
   3867 // mentioned transformation is profitable.
   3868 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
   3869                                     unsigned ExtOpc,
   3870                                     SmallVector<SDNode*, 4> &ExtendNodes,
   3871                                     const TargetLowering &TLI) {
   3872   bool HasCopyToRegUses = false;
   3873   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
   3874   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
   3875                             UE = N0.getNode()->use_end();
   3876        UI != UE; ++UI) {
   3877     SDNode *User = *UI;
   3878     if (User == N)
   3879       continue;
   3880     if (UI.getUse().getResNo() != N0.getResNo())
   3881       continue;
   3882     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
   3883     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
   3884       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
   3885       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
   3886         // Sign bits will be lost after a zext.
   3887         return false;
   3888       bool Add = false;
   3889       for (unsigned i = 0; i != 2; ++i) {
   3890         SDValue UseOp = User->getOperand(i);
   3891         if (UseOp == N0)
   3892           continue;
   3893         if (!isa<ConstantSDNode>(UseOp))
   3894           return false;
   3895         Add = true;
   3896       }
   3897       if (Add)
   3898         ExtendNodes.push_back(User);
   3899       continue;
   3900     }
   3901     // If truncates aren't free and there are users we can't
   3902     // extend, it isn't worthwhile.
   3903     if (!isTruncFree)
   3904       return false;
   3905     // Remember if this value is live-out.
   3906     if (User->getOpcode() == ISD::CopyToReg)
   3907       HasCopyToRegUses = true;
   3908   }
   3909 
   3910   if (HasCopyToRegUses) {
   3911     bool BothLiveOut = false;
   3912     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
   3913          UI != UE; ++UI) {
   3914       SDUse &Use = UI.getUse();
   3915       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
   3916         BothLiveOut = true;
   3917         break;
   3918       }
   3919     }
   3920     if (BothLiveOut)
   3921       // Both unextended and extended values are live out. There had better be
   3922       // a good reason for the transformation.
   3923       return ExtendNodes.size();
   3924   }
   3925   return true;
   3926 }
   3927 
   3928 void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
   3929                                   SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
   3930                                   ISD::NodeType ExtType) {
   3931   // Extend SetCC uses if necessary.
   3932   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
   3933     SDNode *SetCC = SetCCs[i];
   3934     SmallVector<SDValue, 4> Ops;
   3935 
   3936     for (unsigned j = 0; j != 2; ++j) {
   3937       SDValue SOp = SetCC->getOperand(j);
   3938       if (SOp == Trunc)
   3939         Ops.push_back(ExtLoad);
   3940       else
   3941         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
   3942     }
   3943 
   3944     Ops.push_back(SetCC->getOperand(2));
   3945     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
   3946                                  &Ops[0], Ops.size()));
   3947   }
   3948 }
   3949 
   3950 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
   3951   SDValue N0 = N->getOperand(0);
   3952   EVT VT = N->getValueType(0);
   3953 
   3954   // fold (sext c1) -> c1
   3955   if (isa<ConstantSDNode>(N0))
   3956     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
   3957 
   3958   // fold (sext (sext x)) -> (sext x)
   3959   // fold (sext (aext x)) -> (sext x)
   3960   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
   3961     return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
   3962                        N0.getOperand(0));
   3963 
   3964   if (N0.getOpcode() == ISD::TRUNCATE) {
   3965     // fold (sext (truncate (load x))) -> (sext (smaller load x))
   3966     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
   3967     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   3968     if (NarrowLoad.getNode()) {
   3969       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   3970       if (NarrowLoad.getNode() != N0.getNode()) {
   3971         CombineTo(N0.getNode(), NarrowLoad);
   3972         // CombineTo deleted the truncate, if needed, but not what's under it.
   3973         AddToWorkList(oye);
   3974       }
   3975       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   3976     }
   3977 
   3978     // See if the value being truncated is already sign extended.  If so, just
   3979     // eliminate the trunc/sext pair.
   3980     SDValue Op = N0.getOperand(0);
   3981     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
   3982     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
   3983     unsigned DestBits = VT.getScalarType().getSizeInBits();
   3984     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
   3985 
   3986     if (OpBits == DestBits) {
   3987       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
   3988       // bits, it is already ready.
   3989       if (NumSignBits > DestBits-MidBits)
   3990         return Op;
   3991     } else if (OpBits < DestBits) {
   3992       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
   3993       // bits, just sext from i32.
   3994       if (NumSignBits > OpBits-MidBits)
   3995         return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
   3996     } else {
   3997       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
   3998       // bits, just truncate to i32.
   3999       if (NumSignBits > OpBits-MidBits)
   4000         return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
   4001     }
   4002 
   4003     // fold (sext (truncate x)) -> (sextinreg x).
   4004     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
   4005                                                  N0.getValueType())) {
   4006       if (OpBits < DestBits)
   4007         Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
   4008       else if (OpBits > DestBits)
   4009         Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
   4010       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
   4011                          DAG.getValueType(N0.getValueType()));
   4012     }
   4013   }
   4014 
   4015   // fold (sext (load x)) -> (sext (truncate (sextload x)))
   4016   // None of the supported targets knows how to perform load and sign extend
   4017   // on vectors in one instruction.  We only perform this transformation on
   4018   // scalars.
   4019   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
   4020       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   4021        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
   4022     bool DoXform = true;
   4023     SmallVector<SDNode*, 4> SetCCs;
   4024     if (!N0.hasOneUse())
   4025       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
   4026     if (DoXform) {
   4027       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4028       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
   4029                                        LN0->getChain(),
   4030                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   4031                                        N0.getValueType(),
   4032                                        LN0->isVolatile(), LN0->isNonTemporal(),
   4033                                        LN0->getAlignment());
   4034       CombineTo(N, ExtLoad);
   4035       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
   4036                                   N0.getValueType(), ExtLoad);
   4037       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   4038       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
   4039                       ISD::SIGN_EXTEND);
   4040       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4041     }
   4042   }
   4043 
   4044   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
   4045   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
   4046   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
   4047       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
   4048     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4049     EVT MemVT = LN0->getMemoryVT();
   4050     if ((!LegalOperations && !LN0->isVolatile()) ||
   4051         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
   4052       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
   4053                                        LN0->getChain(),
   4054                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   4055                                        MemVT,
   4056                                        LN0->isVolatile(), LN0->isNonTemporal(),
   4057                                        LN0->getAlignment());
   4058       CombineTo(N, ExtLoad);
   4059       CombineTo(N0.getNode(),
   4060                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
   4061                             N0.getValueType(), ExtLoad),
   4062                 ExtLoad.getValue(1));
   4063       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4064     }
   4065   }
   4066 
   4067   // fold (sext (and/or/xor (load x), cst)) ->
   4068   //      (and/or/xor (sextload x), (sext cst))
   4069   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
   4070        N0.getOpcode() == ISD::XOR) &&
   4071       isa<LoadSDNode>(N0.getOperand(0)) &&
   4072       N0.getOperand(1).getOpcode() == ISD::Constant &&
   4073       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
   4074       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
   4075     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
   4076     if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
   4077       bool DoXform = true;
   4078       SmallVector<SDNode*, 4> SetCCs;
   4079       if (!N0.hasOneUse())
   4080         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
   4081                                           SetCCs, TLI);
   4082       if (DoXform) {
   4083         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
   4084                                          LN0->getChain(), LN0->getBasePtr(),
   4085                                          LN0->getPointerInfo(),
   4086                                          LN0->getMemoryVT(),
   4087                                          LN0->isVolatile(),
   4088                                          LN0->isNonTemporal(),
   4089                                          LN0->getAlignment());
   4090         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   4091         Mask = Mask.sext(VT.getSizeInBits());
   4092         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
   4093                                   ExtLoad, DAG.getConstant(Mask, VT));
   4094         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
   4095                                     N0.getOperand(0).getDebugLoc(),
   4096                                     N0.getOperand(0).getValueType(), ExtLoad);
   4097         CombineTo(N, And);
   4098         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
   4099         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
   4100                         ISD::SIGN_EXTEND);
   4101         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4102       }
   4103     }
   4104   }
   4105 
   4106   if (N0.getOpcode() == ISD::SETCC) {
   4107     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
   4108     // Only do this before legalize for now.
   4109     if (VT.isVector() && !LegalOperations) {
   4110       EVT N0VT = N0.getOperand(0).getValueType();
   4111         // We know that the # elements of the results is the same as the
   4112         // # elements of the compare (and the # elements of the compare result
   4113         // for that matter).  Check to see that they are the same size.  If so,
   4114         // we know that the element size of the sext'd result matches the
   4115         // element size of the compare operands.
   4116       if (VT.getSizeInBits() == N0VT.getSizeInBits())
   4117         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
   4118                              N0.getOperand(1),
   4119                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
   4120       // If the desired elements are smaller or larger than the source
   4121       // elements we can use a matching integer vector type and then
   4122       // truncate/sign extend
   4123       else {
   4124         EVT MatchingElementType =
   4125           EVT::getIntegerVT(*DAG.getContext(),
   4126                             N0VT.getScalarType().getSizeInBits());
   4127         EVT MatchingVectorType =
   4128           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
   4129                            N0VT.getVectorNumElements());
   4130         SDValue VsetCC =
   4131           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
   4132                         N0.getOperand(1),
   4133                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
   4134         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
   4135       }
   4136     }
   4137 
   4138     // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
   4139     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
   4140     SDValue NegOne =
   4141       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
   4142     SDValue SCC =
   4143       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
   4144                        NegOne, DAG.getConstant(0, VT),
   4145                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   4146     if (SCC.getNode()) return SCC;
   4147     if (!LegalOperations ||
   4148         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(VT)))
   4149       return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
   4150                          DAG.getSetCC(N->getDebugLoc(),
   4151                                       TLI.getSetCCResultType(VT),
   4152                                       N0.getOperand(0), N0.getOperand(1),
   4153                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
   4154                          NegOne, DAG.getConstant(0, VT));
   4155   }
   4156 
   4157   // fold (sext x) -> (zext x) if the sign bit is known zero.
   4158   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
   4159       DAG.SignBitIsZero(N0))
   4160     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
   4161 
   4162   return SDValue();
   4163 }
   4164 
   4165 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
   4166   SDValue N0 = N->getOperand(0);
   4167   EVT VT = N->getValueType(0);
   4168 
   4169   // fold (zext c1) -> c1
   4170   if (isa<ConstantSDNode>(N0))
   4171     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
   4172   // fold (zext (zext x)) -> (zext x)
   4173   // fold (zext (aext x)) -> (zext x)
   4174   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
   4175     return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
   4176                        N0.getOperand(0));
   4177 
   4178   // fold (zext (truncate (load x))) -> (zext (smaller load x))
   4179   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
   4180   if (N0.getOpcode() == ISD::TRUNCATE) {
   4181     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   4182     if (NarrowLoad.getNode()) {
   4183       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   4184       if (NarrowLoad.getNode() != N0.getNode()) {
   4185         CombineTo(N0.getNode(), NarrowLoad);
   4186         // CombineTo deleted the truncate, if needed, but not what's under it.
   4187         AddToWorkList(oye);
   4188       }
   4189       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4190     }
   4191   }
   4192 
   4193   // fold (zext (truncate x)) -> (and x, mask)
   4194   if (N0.getOpcode() == ISD::TRUNCATE &&
   4195       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
   4196 
   4197     // fold (zext (truncate (load x))) -> (zext (smaller load x))
   4198     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
   4199     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   4200     if (NarrowLoad.getNode()) {
   4201       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   4202       if (NarrowLoad.getNode() != N0.getNode()) {
   4203         CombineTo(N0.getNode(), NarrowLoad);
   4204         // CombineTo deleted the truncate, if needed, but not what's under it.
   4205         AddToWorkList(oye);
   4206       }
   4207       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4208     }
   4209 
   4210     SDValue Op = N0.getOperand(0);
   4211     if (Op.getValueType().bitsLT(VT)) {
   4212       Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
   4213     } else if (Op.getValueType().bitsGT(VT)) {
   4214       Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
   4215     }
   4216     return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
   4217                                   N0.getValueType().getScalarType());
   4218   }
   4219 
   4220   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
   4221   // if either of the casts is not free.
   4222   if (N0.getOpcode() == ISD::AND &&
   4223       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
   4224       N0.getOperand(1).getOpcode() == ISD::Constant &&
   4225       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
   4226                            N0.getValueType()) ||
   4227        !TLI.isZExtFree(N0.getValueType(), VT))) {
   4228     SDValue X = N0.getOperand(0).getOperand(0);
   4229     if (X.getValueType().bitsLT(VT)) {
   4230       X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
   4231     } else if (X.getValueType().bitsGT(VT)) {
   4232       X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
   4233     }
   4234     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   4235     Mask = Mask.zext(VT.getSizeInBits());
   4236     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   4237                        X, DAG.getConstant(Mask, VT));
   4238   }
   4239 
   4240   // fold (zext (load x)) -> (zext (truncate (zextload x)))
   4241   // None of the supported targets knows how to perform load and vector_zext
   4242   // on vectors in one instruction.  We only perform this transformation on
   4243   // scalars.
   4244   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
   4245       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   4246        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
   4247     bool DoXform = true;
   4248     SmallVector<SDNode*, 4> SetCCs;
   4249     if (!N0.hasOneUse())
   4250       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
   4251     if (DoXform) {
   4252       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4253       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
   4254                                        LN0->getChain(),
   4255                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   4256                                        N0.getValueType(),
   4257                                        LN0->isVolatile(), LN0->isNonTemporal(),
   4258                                        LN0->getAlignment());
   4259       CombineTo(N, ExtLoad);
   4260       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
   4261                                   N0.getValueType(), ExtLoad);
   4262       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   4263 
   4264       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
   4265                       ISD::ZERO_EXTEND);
   4266       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4267     }
   4268   }
   4269 
   4270   // fold (zext (and/or/xor (load x), cst)) ->
   4271   //      (and/or/xor (zextload x), (zext cst))
   4272   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
   4273        N0.getOpcode() == ISD::XOR) &&
   4274       isa<LoadSDNode>(N0.getOperand(0)) &&
   4275       N0.getOperand(1).getOpcode() == ISD::Constant &&
   4276       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
   4277       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
   4278     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
   4279     if (LN0->getExtensionType() != ISD::SEXTLOAD) {
   4280       bool DoXform = true;
   4281       SmallVector<SDNode*, 4> SetCCs;
   4282       if (!N0.hasOneUse())
   4283         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
   4284                                           SetCCs, TLI);
   4285       if (DoXform) {
   4286         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
   4287                                          LN0->getChain(), LN0->getBasePtr(),
   4288                                          LN0->getPointerInfo(),
   4289                                          LN0->getMemoryVT(),
   4290                                          LN0->isVolatile(),
   4291                                          LN0->isNonTemporal(),
   4292                                          LN0->getAlignment());
   4293         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   4294         Mask = Mask.zext(VT.getSizeInBits());
   4295         SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
   4296                                   ExtLoad, DAG.getConstant(Mask, VT));
   4297         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
   4298                                     N0.getOperand(0).getDebugLoc(),
   4299                                     N0.getOperand(0).getValueType(), ExtLoad);
   4300         CombineTo(N, And);
   4301         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
   4302         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
   4303                         ISD::ZERO_EXTEND);
   4304         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4305       }
   4306     }
   4307   }
   4308 
   4309   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
   4310   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
   4311   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
   4312       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
   4313     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4314     EVT MemVT = LN0->getMemoryVT();
   4315     if ((!LegalOperations && !LN0->isVolatile()) ||
   4316         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
   4317       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
   4318                                        LN0->getChain(),
   4319                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   4320                                        MemVT,
   4321                                        LN0->isVolatile(), LN0->isNonTemporal(),
   4322                                        LN0->getAlignment());
   4323       CombineTo(N, ExtLoad);
   4324       CombineTo(N0.getNode(),
   4325                 DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
   4326                             ExtLoad),
   4327                 ExtLoad.getValue(1));
   4328       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4329     }
   4330   }
   4331 
   4332   if (N0.getOpcode() == ISD::SETCC) {
   4333     if (!LegalOperations && VT.isVector()) {
   4334       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
   4335       // Only do this before legalize for now.
   4336       EVT N0VT = N0.getOperand(0).getValueType();
   4337       EVT EltVT = VT.getVectorElementType();
   4338       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
   4339                                     DAG.getConstant(1, EltVT));
   4340       if (VT.getSizeInBits() == N0VT.getSizeInBits())
   4341         // We know that the # elements of the results is the same as the
   4342         // # elements of the compare (and the # elements of the compare result
   4343         // for that matter).  Check to see that they are the same size.  If so,
   4344         // we know that the element size of the sext'd result matches the
   4345         // element size of the compare operands.
   4346         return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   4347                            DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
   4348                                          N0.getOperand(1),
   4349                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
   4350                            DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
   4351                                        &OneOps[0], OneOps.size()));
   4352 
   4353       // If the desired elements are smaller or larger than the source
   4354       // elements we can use a matching integer vector type and then
   4355       // truncate/sign extend
   4356       EVT MatchingElementType =
   4357         EVT::getIntegerVT(*DAG.getContext(),
   4358                           N0VT.getScalarType().getSizeInBits());
   4359       EVT MatchingVectorType =
   4360         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
   4361                          N0VT.getVectorNumElements());
   4362       SDValue VsetCC =
   4363         DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
   4364                       N0.getOperand(1),
   4365                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
   4366       return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   4367                          DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
   4368                          DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
   4369                                      &OneOps[0], OneOps.size()));
   4370     }
   4371 
   4372     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
   4373     SDValue SCC =
   4374       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
   4375                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
   4376                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   4377     if (SCC.getNode()) return SCC;
   4378   }
   4379 
   4380   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
   4381   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
   4382       isa<ConstantSDNode>(N0.getOperand(1)) &&
   4383       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
   4384       N0.hasOneUse()) {
   4385     SDValue ShAmt = N0.getOperand(1);
   4386     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
   4387     if (N0.getOpcode() == ISD::SHL) {
   4388       SDValue InnerZExt = N0.getOperand(0);
   4389       // If the original shl may be shifting out bits, do not perform this
   4390       // transformation.
   4391       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
   4392         InnerZExt.getOperand(0).getValueType().getSizeInBits();
   4393       if (ShAmtVal > KnownZeroBits)
   4394         return SDValue();
   4395     }
   4396 
   4397     DebugLoc DL = N->getDebugLoc();
   4398 
   4399     // Ensure that the shift amount is wide enough for the shifted value.
   4400     if (VT.getSizeInBits() >= 256)
   4401       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
   4402 
   4403     return DAG.getNode(N0.getOpcode(), DL, VT,
   4404                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
   4405                        ShAmt);
   4406   }
   4407 
   4408   return SDValue();
   4409 }
   4410 
   4411 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
   4412   SDValue N0 = N->getOperand(0);
   4413   EVT VT = N->getValueType(0);
   4414 
   4415   // fold (aext c1) -> c1
   4416   if (isa<ConstantSDNode>(N0))
   4417     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
   4418   // fold (aext (aext x)) -> (aext x)
   4419   // fold (aext (zext x)) -> (zext x)
   4420   // fold (aext (sext x)) -> (sext x)
   4421   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
   4422       N0.getOpcode() == ISD::ZERO_EXTEND ||
   4423       N0.getOpcode() == ISD::SIGN_EXTEND)
   4424     return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
   4425 
   4426   // fold (aext (truncate (load x))) -> (aext (smaller load x))
   4427   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
   4428   if (N0.getOpcode() == ISD::TRUNCATE) {
   4429     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
   4430     if (NarrowLoad.getNode()) {
   4431       SDNode* oye = N0.getNode()->getOperand(0).getNode();
   4432       if (NarrowLoad.getNode() != N0.getNode()) {
   4433         CombineTo(N0.getNode(), NarrowLoad);
   4434         // CombineTo deleted the truncate, if needed, but not what's under it.
   4435         AddToWorkList(oye);
   4436       }
   4437       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4438     }
   4439   }
   4440 
   4441   // fold (aext (truncate x))
   4442   if (N0.getOpcode() == ISD::TRUNCATE) {
   4443     SDValue TruncOp = N0.getOperand(0);
   4444     if (TruncOp.getValueType() == VT)
   4445       return TruncOp; // x iff x size == zext size.
   4446     if (TruncOp.getValueType().bitsGT(VT))
   4447       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
   4448     return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
   4449   }
   4450 
   4451   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
   4452   // if the trunc is not free.
   4453   if (N0.getOpcode() == ISD::AND &&
   4454       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
   4455       N0.getOperand(1).getOpcode() == ISD::Constant &&
   4456       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
   4457                           N0.getValueType())) {
   4458     SDValue X = N0.getOperand(0).getOperand(0);
   4459     if (X.getValueType().bitsLT(VT)) {
   4460       X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
   4461     } else if (X.getValueType().bitsGT(VT)) {
   4462       X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
   4463     }
   4464     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
   4465     Mask = Mask.zext(VT.getSizeInBits());
   4466     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   4467                        X, DAG.getConstant(Mask, VT));
   4468   }
   4469 
   4470   // fold (aext (load x)) -> (aext (truncate (extload x)))
   4471   // None of the supported targets knows how to perform load and any_ext
   4472   // on vectors in one instruction.  We only perform this transformation on
   4473   // scalars.
   4474   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
   4475       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   4476        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
   4477     bool DoXform = true;
   4478     SmallVector<SDNode*, 4> SetCCs;
   4479     if (!N0.hasOneUse())
   4480       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
   4481     if (DoXform) {
   4482       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4483       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
   4484                                        LN0->getChain(),
   4485                                        LN0->getBasePtr(), LN0->getPointerInfo(),
   4486                                        N0.getValueType(),
   4487                                        LN0->isVolatile(), LN0->isNonTemporal(),
   4488                                        LN0->getAlignment());
   4489       CombineTo(N, ExtLoad);
   4490       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
   4491                                   N0.getValueType(), ExtLoad);
   4492       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
   4493       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
   4494                       ISD::ANY_EXTEND);
   4495       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4496     }
   4497   }
   4498 
   4499   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
   4500   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
   4501   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
   4502   if (N0.getOpcode() == ISD::LOAD &&
   4503       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   4504       N0.hasOneUse()) {
   4505     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4506     EVT MemVT = LN0->getMemoryVT();
   4507     SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
   4508                                      VT, LN0->getChain(), LN0->getBasePtr(),
   4509                                      LN0->getPointerInfo(), MemVT,
   4510                                      LN0->isVolatile(), LN0->isNonTemporal(),
   4511                                      LN0->getAlignment());
   4512     CombineTo(N, ExtLoad);
   4513     CombineTo(N0.getNode(),
   4514               DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
   4515                           N0.getValueType(), ExtLoad),
   4516               ExtLoad.getValue(1));
   4517     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4518   }
   4519 
   4520   if (N0.getOpcode() == ISD::SETCC) {
   4521     // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
   4522     // Only do this before legalize for now.
   4523     if (VT.isVector() && !LegalOperations) {
   4524       EVT N0VT = N0.getOperand(0).getValueType();
   4525         // We know that the # elements of the results is the same as the
   4526         // # elements of the compare (and the # elements of the compare result
   4527         // for that matter).  Check to see that they are the same size.  If so,
   4528         // we know that the element size of the sext'd result matches the
   4529         // element size of the compare operands.
   4530       if (VT.getSizeInBits() == N0VT.getSizeInBits())
   4531         return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
   4532                              N0.getOperand(1),
   4533                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
   4534       // If the desired elements are smaller or larger than the source
   4535       // elements we can use a matching integer vector type and then
   4536       // truncate/sign extend
   4537       else {
   4538         EVT MatchingElementType =
   4539           EVT::getIntegerVT(*DAG.getContext(),
   4540                             N0VT.getScalarType().getSizeInBits());
   4541         EVT MatchingVectorType =
   4542           EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
   4543                            N0VT.getVectorNumElements());
   4544         SDValue VsetCC =
   4545           DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
   4546                         N0.getOperand(1),
   4547                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
   4548         return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
   4549       }
   4550     }
   4551 
   4552     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
   4553     SDValue SCC =
   4554       SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
   4555                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
   4556                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
   4557     if (SCC.getNode())
   4558       return SCC;
   4559   }
   4560 
   4561   return SDValue();
   4562 }
   4563 
   4564 /// GetDemandedBits - See if the specified operand can be simplified with the
   4565 /// knowledge that only the bits specified by Mask are used.  If so, return the
   4566 /// simpler operand, otherwise return a null SDValue.
   4567 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
   4568   switch (V.getOpcode()) {
   4569   default: break;
   4570   case ISD::OR:
   4571   case ISD::XOR:
   4572     // If the LHS or RHS don't contribute bits to the or, drop them.
   4573     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
   4574       return V.getOperand(1);
   4575     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
   4576       return V.getOperand(0);
   4577     break;
   4578   case ISD::SRL:
   4579     // Only look at single-use SRLs.
   4580     if (!V.getNode()->hasOneUse())
   4581       break;
   4582     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
   4583       // See if we can recursively simplify the LHS.
   4584       unsigned Amt = RHSC->getZExtValue();
   4585 
   4586       // Watch out for shift count overflow though.
   4587       if (Amt >= Mask.getBitWidth()) break;
   4588       APInt NewMask = Mask << Amt;
   4589       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
   4590       if (SimplifyLHS.getNode())
   4591         return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
   4592                            SimplifyLHS, V.getOperand(1));
   4593     }
   4594   }
   4595   return SDValue();
   4596 }
   4597 
   4598 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
   4599 /// bits and then truncated to a narrower type and where N is a multiple
   4600 /// of number of bits of the narrower type, transform it to a narrower load
   4601 /// from address + N / num of bits of new type. If the result is to be
   4602 /// extended, also fold the extension to form a extending load.
   4603 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
   4604   unsigned Opc = N->getOpcode();
   4605 
   4606   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
   4607   SDValue N0 = N->getOperand(0);
   4608   EVT VT = N->getValueType(0);
   4609   EVT ExtVT = VT;
   4610 
   4611   // This transformation isn't valid for vector loads.
   4612   if (VT.isVector())
   4613     return SDValue();
   4614 
   4615   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
   4616   // extended to VT.
   4617   if (Opc == ISD::SIGN_EXTEND_INREG) {
   4618     ExtType = ISD::SEXTLOAD;
   4619     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
   4620   } else if (Opc == ISD::SRL) {
   4621     // Another special-case: SRL is basically zero-extending a narrower value.
   4622     ExtType = ISD::ZEXTLOAD;
   4623     N0 = SDValue(N, 0);
   4624     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
   4625     if (!N01) return SDValue();
   4626     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
   4627                               VT.getSizeInBits() - N01->getZExtValue());
   4628   }
   4629   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
   4630     return SDValue();
   4631 
   4632   unsigned EVTBits = ExtVT.getSizeInBits();
   4633 
   4634   // Do not generate loads of non-round integer types since these can
   4635   // be expensive (and would be wrong if the type is not byte sized).
   4636   if (!ExtVT.isRound())
   4637     return SDValue();
   4638 
   4639   unsigned ShAmt = 0;
   4640   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
   4641     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   4642       ShAmt = N01->getZExtValue();
   4643       // Is the shift amount a multiple of size of VT?
   4644       if ((ShAmt & (EVTBits-1)) == 0) {
   4645         N0 = N0.getOperand(0);
   4646         // Is the load width a multiple of size of VT?
   4647         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
   4648           return SDValue();
   4649       }
   4650 
   4651       // At this point, we must have a load or else we can't do the transform.
   4652       if (!isa<LoadSDNode>(N0)) return SDValue();
   4653 
   4654       // If the shift amount is larger than the input type then we're not
   4655       // accessing any of the loaded bytes.  If the load was a zextload/extload
   4656       // then the result of the shift+trunc is zero/undef (handled elsewhere).
   4657       // If the load was a sextload then the result is a splat of the sign bit
   4658       // of the extended byte.  This is not worth optimizing for.
   4659       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
   4660         return SDValue();
   4661     }
   4662   }
   4663 
   4664   // If the load is shifted left (and the result isn't shifted back right),
   4665   // we can fold the truncate through the shift.
   4666   unsigned ShLeftAmt = 0;
   4667   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
   4668       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
   4669     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
   4670       ShLeftAmt = N01->getZExtValue();
   4671       N0 = N0.getOperand(0);
   4672     }
   4673   }
   4674 
   4675   // If we haven't found a load, we can't narrow it.  Don't transform one with
   4676   // multiple uses, this would require adding a new load.
   4677   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse() ||
   4678       // Don't change the width of a volatile load.
   4679       cast<LoadSDNode>(N0)->isVolatile())
   4680     return SDValue();
   4681 
   4682   // Verify that we are actually reducing a load width here.
   4683   if (cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits() < EVTBits)
   4684     return SDValue();
   4685 
   4686   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4687   EVT PtrType = N0.getOperand(1).getValueType();
   4688 
   4689   // For big endian targets, we need to adjust the offset to the pointer to
   4690   // load the correct bytes.
   4691   if (TLI.isBigEndian()) {
   4692     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
   4693     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
   4694     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
   4695   }
   4696 
   4697   uint64_t PtrOff = ShAmt / 8;
   4698   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
   4699   SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
   4700                                PtrType, LN0->getBasePtr(),
   4701                                DAG.getConstant(PtrOff, PtrType));
   4702   AddToWorkList(NewPtr.getNode());
   4703 
   4704   SDValue Load;
   4705   if (ExtType == ISD::NON_EXTLOAD)
   4706     Load =  DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
   4707                         LN0->getPointerInfo().getWithOffset(PtrOff),
   4708                         LN0->isVolatile(), LN0->isNonTemporal(), NewAlign);
   4709   else
   4710     Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
   4711                           LN0->getPointerInfo().getWithOffset(PtrOff),
   4712                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
   4713                           NewAlign);
   4714 
   4715   // Replace the old load's chain with the new load's chain.
   4716   WorkListRemover DeadNodes(*this);
   4717   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1),
   4718                                 &DeadNodes);
   4719 
   4720   // Shift the result left, if we've swallowed a left shift.
   4721   SDValue Result = Load;
   4722   if (ShLeftAmt != 0) {
   4723     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
   4724     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
   4725       ShImmTy = VT;
   4726     Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
   4727                          Result, DAG.getConstant(ShLeftAmt, ShImmTy));
   4728   }
   4729 
   4730   // Return the new loaded value.
   4731   return Result;
   4732 }
   4733 
   4734 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
   4735   SDValue N0 = N->getOperand(0);
   4736   SDValue N1 = N->getOperand(1);
   4737   EVT VT = N->getValueType(0);
   4738   EVT EVT = cast<VTSDNode>(N1)->getVT();
   4739   unsigned VTBits = VT.getScalarType().getSizeInBits();
   4740   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
   4741 
   4742   // fold (sext_in_reg c1) -> c1
   4743   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
   4744     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
   4745 
   4746   // If the input is already sign extended, just drop the extension.
   4747   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
   4748     return N0;
   4749 
   4750   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
   4751   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
   4752       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
   4753     return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
   4754                        N0.getOperand(0), N1);
   4755   }
   4756 
   4757   // fold (sext_in_reg (sext x)) -> (sext x)
   4758   // fold (sext_in_reg (aext x)) -> (sext x)
   4759   // if x is small enough.
   4760   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
   4761     SDValue N00 = N0.getOperand(0);
   4762     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
   4763         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
   4764       return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
   4765   }
   4766 
   4767   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
   4768   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
   4769     return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
   4770 
   4771   // fold operands of sext_in_reg based on knowledge that the top bits are not
   4772   // demanded.
   4773   if (SimplifyDemandedBits(SDValue(N, 0)))
   4774     return SDValue(N, 0);
   4775 
   4776   // fold (sext_in_reg (load x)) -> (smaller sextload x)
   4777   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
   4778   SDValue NarrowLoad = ReduceLoadWidth(N);
   4779   if (NarrowLoad.getNode())
   4780     return NarrowLoad;
   4781 
   4782   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
   4783   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
   4784   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
   4785   if (N0.getOpcode() == ISD::SRL) {
   4786     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
   4787       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
   4788         // We can turn this into an SRA iff the input to the SRL is already sign
   4789         // extended enough.
   4790         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
   4791         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
   4792           return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
   4793                              N0.getOperand(0), N0.getOperand(1));
   4794       }
   4795   }
   4796 
   4797   // fold (sext_inreg (extload x)) -> (sextload x)
   4798   if (ISD::isEXTLoad(N0.getNode()) &&
   4799       ISD::isUNINDEXEDLoad(N0.getNode()) &&
   4800       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
   4801       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   4802        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
   4803     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4804     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
   4805                                      LN0->getChain(),
   4806                                      LN0->getBasePtr(), LN0->getPointerInfo(),
   4807                                      EVT,
   4808                                      LN0->isVolatile(), LN0->isNonTemporal(),
   4809                                      LN0->getAlignment());
   4810     CombineTo(N, ExtLoad);
   4811     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   4812     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4813   }
   4814   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
   4815   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
   4816       N0.hasOneUse() &&
   4817       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
   4818       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   4819        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
   4820     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4821     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
   4822                                      LN0->getChain(),
   4823                                      LN0->getBasePtr(), LN0->getPointerInfo(),
   4824                                      EVT,
   4825                                      LN0->isVolatile(), LN0->isNonTemporal(),
   4826                                      LN0->getAlignment());
   4827     CombineTo(N, ExtLoad);
   4828     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
   4829     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   4830   }
   4831 
   4832   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
   4833   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
   4834     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
   4835                                        N0.getOperand(1), false);
   4836     if (BSwap.getNode() != 0)
   4837       return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
   4838                          BSwap, N1);
   4839   }
   4840 
   4841   return SDValue();
   4842 }
   4843 
   4844 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
   4845   SDValue N0 = N->getOperand(0);
   4846   EVT VT = N->getValueType(0);
   4847 
   4848   // noop truncate
   4849   if (N0.getValueType() == N->getValueType(0))
   4850     return N0;
   4851   // fold (truncate c1) -> c1
   4852   if (isa<ConstantSDNode>(N0))
   4853     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
   4854   // fold (truncate (truncate x)) -> (truncate x)
   4855   if (N0.getOpcode() == ISD::TRUNCATE)
   4856     return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
   4857   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
   4858   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
   4859       N0.getOpcode() == ISD::SIGN_EXTEND ||
   4860       N0.getOpcode() == ISD::ANY_EXTEND) {
   4861     if (N0.getOperand(0).getValueType().bitsLT(VT))
   4862       // if the source is smaller than the dest, we still need an extend
   4863       return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
   4864                          N0.getOperand(0));
   4865     else if (N0.getOperand(0).getValueType().bitsGT(VT))
   4866       // if the source is larger than the dest, than we just need the truncate
   4867       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
   4868     else
   4869       // if the source and dest are the same type, we can drop both the extend
   4870       // and the truncate.
   4871       return N0.getOperand(0);
   4872   }
   4873 
   4874   // See if we can simplify the input to this truncate through knowledge that
   4875   // only the low bits are being used.
   4876   // For example "trunc (or (shl x, 8), y)" // -> trunc y
   4877   // Currently we only perform this optimization on scalars because vectors
   4878   // may have different active low bits.
   4879   if (!VT.isVector()) {
   4880     SDValue Shorter =
   4881       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
   4882                                                VT.getSizeInBits()));
   4883     if (Shorter.getNode())
   4884       return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
   4885   }
   4886   // fold (truncate (load x)) -> (smaller load x)
   4887   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
   4888   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
   4889     SDValue Reduced = ReduceLoadWidth(N);
   4890     if (Reduced.getNode())
   4891       return Reduced;
   4892   }
   4893 
   4894   // Simplify the operands using demanded-bits information.
   4895   if (!VT.isVector() &&
   4896       SimplifyDemandedBits(SDValue(N, 0)))
   4897     return SDValue(N, 0);
   4898 
   4899   return SDValue();
   4900 }
   4901 
   4902 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
   4903   SDValue Elt = N->getOperand(i);
   4904   if (Elt.getOpcode() != ISD::MERGE_VALUES)
   4905     return Elt.getNode();
   4906   return Elt.getOperand(Elt.getResNo()).getNode();
   4907 }
   4908 
   4909 /// CombineConsecutiveLoads - build_pair (load, load) -> load
   4910 /// if load locations are consecutive.
   4911 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
   4912   assert(N->getOpcode() == ISD::BUILD_PAIR);
   4913 
   4914   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
   4915   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
   4916   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
   4917       LD1->getPointerInfo().getAddrSpace() !=
   4918          LD2->getPointerInfo().getAddrSpace())
   4919     return SDValue();
   4920   EVT LD1VT = LD1->getValueType(0);
   4921 
   4922   if (ISD::isNON_EXTLoad(LD2) &&
   4923       LD2->hasOneUse() &&
   4924       // If both are volatile this would reduce the number of volatile loads.
   4925       // If one is volatile it might be ok, but play conservative and bail out.
   4926       !LD1->isVolatile() &&
   4927       !LD2->isVolatile() &&
   4928       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
   4929     unsigned Align = LD1->getAlignment();
   4930     unsigned NewAlign = TLI.getTargetData()->
   4931       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
   4932 
   4933     if (NewAlign <= Align &&
   4934         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
   4935       return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
   4936                          LD1->getBasePtr(), LD1->getPointerInfo(),
   4937                          false, false, Align);
   4938   }
   4939 
   4940   return SDValue();
   4941 }
   4942 
   4943 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
   4944   SDValue N0 = N->getOperand(0);
   4945   EVT VT = N->getValueType(0);
   4946 
   4947   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
   4948   // Only do this before legalize, since afterward the target may be depending
   4949   // on the bitconvert.
   4950   // First check to see if this is all constant.
   4951   if (!LegalTypes &&
   4952       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
   4953       VT.isVector()) {
   4954     bool isSimple = true;
   4955     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
   4956       if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
   4957           N0.getOperand(i).getOpcode() != ISD::Constant &&
   4958           N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
   4959         isSimple = false;
   4960         break;
   4961       }
   4962 
   4963     EVT DestEltVT = N->getValueType(0).getVectorElementType();
   4964     assert(!DestEltVT.isVector() &&
   4965            "Element type of vector ValueType must not be vector!");
   4966     if (isSimple)
   4967       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
   4968   }
   4969 
   4970   // If the input is a constant, let getNode fold it.
   4971   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
   4972     SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
   4973     if (Res.getNode() != N) {
   4974       if (!LegalOperations ||
   4975           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
   4976         return Res;
   4977 
   4978       // Folding it resulted in an illegal node, and it's too late to
   4979       // do that. Clean up the old node and forego the transformation.
   4980       // Ideally this won't happen very often, because instcombine
   4981       // and the earlier dagcombine runs (where illegal nodes are
   4982       // permitted) should have folded most of them already.
   4983       DAG.DeleteNode(Res.getNode());
   4984     }
   4985   }
   4986 
   4987   // (conv (conv x, t1), t2) -> (conv x, t2)
   4988   if (N0.getOpcode() == ISD::BITCAST)
   4989     return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
   4990                        N0.getOperand(0));
   4991 
   4992   // fold (conv (load x)) -> (load (conv*)x)
   4993   // If the resultant load doesn't need a higher alignment than the original!
   4994   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
   4995       // Do not change the width of a volatile load.
   4996       !cast<LoadSDNode>(N0)->isVolatile() &&
   4997       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
   4998     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   4999     unsigned Align = TLI.getTargetData()->
   5000       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
   5001     unsigned OrigAlign = LN0->getAlignment();
   5002 
   5003     if (Align <= OrigAlign) {
   5004       SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
   5005                                  LN0->getBasePtr(), LN0->getPointerInfo(),
   5006                                  LN0->isVolatile(), LN0->isNonTemporal(),
   5007                                  OrigAlign);
   5008       AddToWorkList(N);
   5009       CombineTo(N0.getNode(),
   5010                 DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
   5011                             N0.getValueType(), Load),
   5012                 Load.getValue(1));
   5013       return Load;
   5014     }
   5015   }
   5016 
   5017   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
   5018   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
   5019   // This often reduces constant pool loads.
   5020   if ((N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FABS) &&
   5021       N0.getNode()->hasOneUse() && VT.isInteger() && !VT.isVector()) {
   5022     SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
   5023                                   N0.getOperand(0));
   5024     AddToWorkList(NewConv.getNode());
   5025 
   5026     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
   5027     if (N0.getOpcode() == ISD::FNEG)
   5028       return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
   5029                          NewConv, DAG.getConstant(SignBit, VT));
   5030     assert(N0.getOpcode() == ISD::FABS);
   5031     return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
   5032                        NewConv, DAG.getConstant(~SignBit, VT));
   5033   }
   5034 
   5035   // fold (bitconvert (fcopysign cst, x)) ->
   5036   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
   5037   // Note that we don't handle (copysign x, cst) because this can always be
   5038   // folded to an fneg or fabs.
   5039   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
   5040       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
   5041       VT.isInteger() && !VT.isVector()) {
   5042     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
   5043     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
   5044     if (isTypeLegal(IntXVT)) {
   5045       SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
   5046                               IntXVT, N0.getOperand(1));
   5047       AddToWorkList(X.getNode());
   5048 
   5049       // If X has a different width than the result/lhs, sext it or truncate it.
   5050       unsigned VTWidth = VT.getSizeInBits();
   5051       if (OrigXWidth < VTWidth) {
   5052         X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
   5053         AddToWorkList(X.getNode());
   5054       } else if (OrigXWidth > VTWidth) {
   5055         // To get the sign bit in the right place, we have to shift it right
   5056         // before truncating.
   5057         X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
   5058                         X.getValueType(), X,
   5059                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
   5060         AddToWorkList(X.getNode());
   5061         X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
   5062         AddToWorkList(X.getNode());
   5063       }
   5064 
   5065       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
   5066       X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
   5067                       X, DAG.getConstant(SignBit, VT));
   5068       AddToWorkList(X.getNode());
   5069 
   5070       SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
   5071                                 VT, N0.getOperand(0));
   5072       Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
   5073                         Cst, DAG.getConstant(~SignBit, VT));
   5074       AddToWorkList(Cst.getNode());
   5075 
   5076       return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
   5077     }
   5078   }
   5079 
   5080   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
   5081   if (N0.getOpcode() == ISD::BUILD_PAIR) {
   5082     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
   5083     if (CombineLD.getNode())
   5084       return CombineLD;
   5085   }
   5086 
   5087   return SDValue();
   5088 }
   5089 
   5090 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
   5091   EVT VT = N->getValueType(0);
   5092   return CombineConsecutiveLoads(N, VT);
   5093 }
   5094 
   5095 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
   5096 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
   5097 /// destination element value type.
   5098 SDValue DAGCombiner::
   5099 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
   5100   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
   5101 
   5102   // If this is already the right type, we're done.
   5103   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
   5104 
   5105   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
   5106   unsigned DstBitSize = DstEltVT.getSizeInBits();
   5107 
   5108   // If this is a conversion of N elements of one type to N elements of another
   5109   // type, convert each element.  This handles FP<->INT cases.
   5110   if (SrcBitSize == DstBitSize) {
   5111     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
   5112                               BV->getValueType(0).getVectorNumElements());
   5113 
   5114     // Due to the FP element handling below calling this routine recursively,
   5115     // we can end up with a scalar-to-vector node here.
   5116     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
   5117       return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
   5118                          DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
   5119                                      DstEltVT, BV->getOperand(0)));
   5120 
   5121     SmallVector<SDValue, 8> Ops;
   5122     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
   5123       SDValue Op = BV->getOperand(i);
   5124       // If the vector element type is not legal, the BUILD_VECTOR operands
   5125       // are promoted and implicitly truncated.  Make that explicit here.
   5126       if (Op.getValueType() != SrcEltVT)
   5127         Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
   5128       Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
   5129                                 DstEltVT, Op));
   5130       AddToWorkList(Ops.back().getNode());
   5131     }
   5132     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
   5133                        &Ops[0], Ops.size());
   5134   }
   5135 
   5136   // Otherwise, we're growing or shrinking the elements.  To avoid having to
   5137   // handle annoying details of growing/shrinking FP values, we convert them to
   5138   // int first.
   5139   if (SrcEltVT.isFloatingPoint()) {
   5140     // Convert the input float vector to a int vector where the elements are the
   5141     // same sizes.
   5142     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
   5143     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
   5144     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
   5145     SrcEltVT = IntVT;
   5146   }
   5147 
   5148   // Now we know the input is an integer vector.  If the output is a FP type,
   5149   // convert to integer first, then to FP of the right size.
   5150   if (DstEltVT.isFloatingPoint()) {
   5151     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
   5152     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
   5153     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
   5154 
   5155     // Next, convert to FP elements of the same size.
   5156     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
   5157   }
   5158 
   5159   // Okay, we know the src/dst types are both integers of differing types.
   5160   // Handling growing first.
   5161   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
   5162   if (SrcBitSize < DstBitSize) {
   5163     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
   5164 
   5165     SmallVector<SDValue, 8> Ops;
   5166     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
   5167          i += NumInputsPerOutput) {
   5168       bool isLE = TLI.isLittleEndian();
   5169       APInt NewBits = APInt(DstBitSize, 0);
   5170       bool EltIsUndef = true;
   5171       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
   5172         // Shift the previously computed bits over.
   5173         NewBits <<= SrcBitSize;
   5174         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
   5175         if (Op.getOpcode() == ISD::UNDEF) continue;
   5176         EltIsUndef = false;
   5177 
   5178         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
   5179                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
   5180       }
   5181 
   5182       if (EltIsUndef)
   5183         Ops.push_back(DAG.getUNDEF(DstEltVT));
   5184       else
   5185         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
   5186     }
   5187 
   5188     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
   5189     return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
   5190                        &Ops[0], Ops.size());
   5191   }
   5192 
   5193   // Finally, this must be the case where we are shrinking elements: each input
   5194   // turns into multiple outputs.
   5195   bool isS2V = ISD::isScalarToVector(BV);
   5196   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
   5197   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
   5198                             NumOutputsPerInput*BV->getNumOperands());
   5199   SmallVector<SDValue, 8> Ops;
   5200 
   5201   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
   5202     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
   5203       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
   5204         Ops.push_back(DAG.getUNDEF(DstEltVT));
   5205       continue;
   5206     }
   5207 
   5208     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
   5209                   getAPIntValue().zextOrTrunc(SrcBitSize);
   5210 
   5211     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
   5212       APInt ThisVal = OpVal.trunc(DstBitSize);
   5213       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
   5214       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
   5215         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
   5216         return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
   5217                            Ops[0]);
   5218       OpVal = OpVal.lshr(DstBitSize);
   5219     }
   5220 
   5221     // For big endian targets, swap the order of the pieces of each element.
   5222     if (TLI.isBigEndian())
   5223       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
   5224   }
   5225 
   5226   return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
   5227                      &Ops[0], Ops.size());
   5228 }
   5229 
   5230 SDValue DAGCombiner::visitFADD(SDNode *N) {
   5231   SDValue N0 = N->getOperand(0);
   5232   SDValue N1 = N->getOperand(1);
   5233   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5234   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5235   EVT VT = N->getValueType(0);
   5236 
   5237   // fold vector ops
   5238   if (VT.isVector()) {
   5239     SDValue FoldedVOp = SimplifyVBinOp(N);
   5240     if (FoldedVOp.getNode()) return FoldedVOp;
   5241   }
   5242 
   5243   // fold (fadd c1, c2) -> (fadd c1, c2)
   5244   if (N0CFP && N1CFP && VT != MVT::ppcf128)
   5245     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
   5246   // canonicalize constant to RHS
   5247   if (N0CFP && !N1CFP)
   5248     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
   5249   // fold (fadd A, 0) -> A
   5250   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
   5251     return N0;
   5252   // fold (fadd A, (fneg B)) -> (fsub A, B)
   5253   if (isNegatibleForFree(N1, LegalOperations) == 2)
   5254     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
   5255                        GetNegatedExpression(N1, DAG, LegalOperations));
   5256   // fold (fadd (fneg A), B) -> (fsub B, A)
   5257   if (isNegatibleForFree(N0, LegalOperations) == 2)
   5258     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
   5259                        GetNegatedExpression(N0, DAG, LegalOperations));
   5260 
   5261   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
   5262   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FADD &&
   5263       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
   5264     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
   5265                        DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
   5266                                    N0.getOperand(1), N1));
   5267 
   5268   return SDValue();
   5269 }
   5270 
   5271 SDValue DAGCombiner::visitFSUB(SDNode *N) {
   5272   SDValue N0 = N->getOperand(0);
   5273   SDValue N1 = N->getOperand(1);
   5274   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5275   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5276   EVT VT = N->getValueType(0);
   5277 
   5278   // fold vector ops
   5279   if (VT.isVector()) {
   5280     SDValue FoldedVOp = SimplifyVBinOp(N);
   5281     if (FoldedVOp.getNode()) return FoldedVOp;
   5282   }
   5283 
   5284   // fold (fsub c1, c2) -> c1-c2
   5285   if (N0CFP && N1CFP && VT != MVT::ppcf128)
   5286     return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
   5287   // fold (fsub A, 0) -> A
   5288   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
   5289     return N0;
   5290   // fold (fsub 0, B) -> -B
   5291   if (UnsafeFPMath && N0CFP && N0CFP->getValueAPF().isZero()) {
   5292     if (isNegatibleForFree(N1, LegalOperations))
   5293       return GetNegatedExpression(N1, DAG, LegalOperations);
   5294     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   5295       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N1);
   5296   }
   5297   // fold (fsub A, (fneg B)) -> (fadd A, B)
   5298   if (isNegatibleForFree(N1, LegalOperations))
   5299     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0,
   5300                        GetNegatedExpression(N1, DAG, LegalOperations));
   5301 
   5302   return SDValue();
   5303 }
   5304 
   5305 SDValue DAGCombiner::visitFMUL(SDNode *N) {
   5306   SDValue N0 = N->getOperand(0);
   5307   SDValue N1 = N->getOperand(1);
   5308   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5309   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5310   EVT VT = N->getValueType(0);
   5311 
   5312   // fold vector ops
   5313   if (VT.isVector()) {
   5314     SDValue FoldedVOp = SimplifyVBinOp(N);
   5315     if (FoldedVOp.getNode()) return FoldedVOp;
   5316   }
   5317 
   5318   // fold (fmul c1, c2) -> c1*c2
   5319   if (N0CFP && N1CFP && VT != MVT::ppcf128)
   5320     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
   5321   // canonicalize constant to RHS
   5322   if (N0CFP && !N1CFP)
   5323     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
   5324   // fold (fmul A, 0) -> 0
   5325   if (UnsafeFPMath && N1CFP && N1CFP->getValueAPF().isZero())
   5326     return N1;
   5327   // fold (fmul A, 0) -> 0, vector edition.
   5328   if (UnsafeFPMath && ISD::isBuildVectorAllZeros(N1.getNode()))
   5329     return N1;
   5330   // fold (fmul X, 2.0) -> (fadd X, X)
   5331   if (N1CFP && N1CFP->isExactlyValue(+2.0))
   5332     return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
   5333   // fold (fmul X, -1.0) -> (fneg X)
   5334   if (N1CFP && N1CFP->isExactlyValue(-1.0))
   5335     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   5336       return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
   5337 
   5338   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
   5339   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
   5340     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
   5341       // Both can be negated for free, check to see if at least one is cheaper
   5342       // negated.
   5343       if (LHSNeg == 2 || RHSNeg == 2)
   5344         return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
   5345                            GetNegatedExpression(N0, DAG, LegalOperations),
   5346                            GetNegatedExpression(N1, DAG, LegalOperations));
   5347     }
   5348   }
   5349 
   5350   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
   5351   if (UnsafeFPMath && N1CFP && N0.getOpcode() == ISD::FMUL &&
   5352       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
   5353     return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
   5354                        DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
   5355                                    N0.getOperand(1), N1));
   5356 
   5357   return SDValue();
   5358 }
   5359 
   5360 SDValue DAGCombiner::visitFDIV(SDNode *N) {
   5361   SDValue N0 = N->getOperand(0);
   5362   SDValue N1 = N->getOperand(1);
   5363   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5364   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5365   EVT VT = N->getValueType(0);
   5366 
   5367   // fold vector ops
   5368   if (VT.isVector()) {
   5369     SDValue FoldedVOp = SimplifyVBinOp(N);
   5370     if (FoldedVOp.getNode()) return FoldedVOp;
   5371   }
   5372 
   5373   // fold (fdiv c1, c2) -> c1/c2
   5374   if (N0CFP && N1CFP && VT != MVT::ppcf128)
   5375     return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
   5376 
   5377 
   5378   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
   5379   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations)) {
   5380     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations)) {
   5381       // Both can be negated for free, check to see if at least one is cheaper
   5382       // negated.
   5383       if (LHSNeg == 2 || RHSNeg == 2)
   5384         return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
   5385                            GetNegatedExpression(N0, DAG, LegalOperations),
   5386                            GetNegatedExpression(N1, DAG, LegalOperations));
   5387     }
   5388   }
   5389 
   5390   return SDValue();
   5391 }
   5392 
   5393 SDValue DAGCombiner::visitFREM(SDNode *N) {
   5394   SDValue N0 = N->getOperand(0);
   5395   SDValue N1 = N->getOperand(1);
   5396   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5397   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5398   EVT VT = N->getValueType(0);
   5399 
   5400   // fold (frem c1, c2) -> fmod(c1,c2)
   5401   if (N0CFP && N1CFP && VT != MVT::ppcf128)
   5402     return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
   5403 
   5404   return SDValue();
   5405 }
   5406 
   5407 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
   5408   SDValue N0 = N->getOperand(0);
   5409   SDValue N1 = N->getOperand(1);
   5410   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5411   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
   5412   EVT VT = N->getValueType(0);
   5413 
   5414   if (N0CFP && N1CFP && VT != MVT::ppcf128)  // Constant fold
   5415     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
   5416 
   5417   if (N1CFP) {
   5418     const APFloat& V = N1CFP->getValueAPF();
   5419     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
   5420     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
   5421     if (!V.isNegative()) {
   5422       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
   5423         return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
   5424     } else {
   5425       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
   5426         return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
   5427                            DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
   5428     }
   5429   }
   5430 
   5431   // copysign(fabs(x), y) -> copysign(x, y)
   5432   // copysign(fneg(x), y) -> copysign(x, y)
   5433   // copysign(copysign(x,z), y) -> copysign(x, y)
   5434   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
   5435       N0.getOpcode() == ISD::FCOPYSIGN)
   5436     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
   5437                        N0.getOperand(0), N1);
   5438 
   5439   // copysign(x, abs(y)) -> abs(x)
   5440   if (N1.getOpcode() == ISD::FABS)
   5441     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
   5442 
   5443   // copysign(x, copysign(y,z)) -> copysign(x, z)
   5444   if (N1.getOpcode() == ISD::FCOPYSIGN)
   5445     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
   5446                        N0, N1.getOperand(1));
   5447 
   5448   // copysign(x, fp_extend(y)) -> copysign(x, y)
   5449   // copysign(x, fp_round(y)) -> copysign(x, y)
   5450   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
   5451     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
   5452                        N0, N1.getOperand(0));
   5453 
   5454   return SDValue();
   5455 }
   5456 
   5457 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
   5458   SDValue N0 = N->getOperand(0);
   5459   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   5460   EVT VT = N->getValueType(0);
   5461   EVT OpVT = N0.getValueType();
   5462 
   5463   // fold (sint_to_fp c1) -> c1fp
   5464   if (N0C && OpVT != MVT::ppcf128 &&
   5465       // ...but only if the target supports immediate floating-point values
   5466       (Level == llvm::Unrestricted ||
   5467        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
   5468     return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
   5469 
   5470   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
   5471   // but UINT_TO_FP is legal on this target, try to convert.
   5472   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
   5473       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
   5474     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
   5475     if (DAG.SignBitIsZero(N0))
   5476       return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
   5477   }
   5478 
   5479   return SDValue();
   5480 }
   5481 
   5482 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
   5483   SDValue N0 = N->getOperand(0);
   5484   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
   5485   EVT VT = N->getValueType(0);
   5486   EVT OpVT = N0.getValueType();
   5487 
   5488   // fold (uint_to_fp c1) -> c1fp
   5489   if (N0C && OpVT != MVT::ppcf128 &&
   5490       // ...but only if the target supports immediate floating-point values
   5491       (Level == llvm::Unrestricted ||
   5492        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
   5493     return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
   5494 
   5495   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
   5496   // but SINT_TO_FP is legal on this target, try to convert.
   5497   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
   5498       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
   5499     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
   5500     if (DAG.SignBitIsZero(N0))
   5501       return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
   5502   }
   5503 
   5504   return SDValue();
   5505 }
   5506 
   5507 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
   5508   SDValue N0 = N->getOperand(0);
   5509   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5510   EVT VT = N->getValueType(0);
   5511 
   5512   // fold (fp_to_sint c1fp) -> c1
   5513   if (N0CFP)
   5514     return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
   5515 
   5516   return SDValue();
   5517 }
   5518 
   5519 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
   5520   SDValue N0 = N->getOperand(0);
   5521   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5522   EVT VT = N->getValueType(0);
   5523 
   5524   // fold (fp_to_uint c1fp) -> c1
   5525   if (N0CFP && VT != MVT::ppcf128)
   5526     return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
   5527 
   5528   return SDValue();
   5529 }
   5530 
   5531 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
   5532   SDValue N0 = N->getOperand(0);
   5533   SDValue N1 = N->getOperand(1);
   5534   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5535   EVT VT = N->getValueType(0);
   5536 
   5537   // fold (fp_round c1fp) -> c1fp
   5538   if (N0CFP && N0.getValueType() != MVT::ppcf128)
   5539     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
   5540 
   5541   // fold (fp_round (fp_extend x)) -> x
   5542   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
   5543     return N0.getOperand(0);
   5544 
   5545   // fold (fp_round (fp_round x)) -> (fp_round x)
   5546   if (N0.getOpcode() == ISD::FP_ROUND) {
   5547     // This is a value preserving truncation if both round's are.
   5548     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
   5549                    N0.getNode()->getConstantOperandVal(1) == 1;
   5550     return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
   5551                        DAG.getIntPtrConstant(IsTrunc));
   5552   }
   5553 
   5554   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
   5555   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
   5556     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
   5557                               N0.getOperand(0), N1);
   5558     AddToWorkList(Tmp.getNode());
   5559     return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
   5560                        Tmp, N0.getOperand(1));
   5561   }
   5562 
   5563   return SDValue();
   5564 }
   5565 
   5566 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
   5567   SDValue N0 = N->getOperand(0);
   5568   EVT VT = N->getValueType(0);
   5569   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
   5570   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5571 
   5572   // fold (fp_round_inreg c1fp) -> c1fp
   5573   if (N0CFP && isTypeLegal(EVT)) {
   5574     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
   5575     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
   5576   }
   5577 
   5578   return SDValue();
   5579 }
   5580 
   5581 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
   5582   SDValue N0 = N->getOperand(0);
   5583   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5584   EVT VT = N->getValueType(0);
   5585 
   5586   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
   5587   if (N->hasOneUse() &&
   5588       N->use_begin()->getOpcode() == ISD::FP_ROUND)
   5589     return SDValue();
   5590 
   5591   // fold (fp_extend c1fp) -> c1fp
   5592   if (N0CFP && VT != MVT::ppcf128)
   5593     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
   5594 
   5595   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
   5596   // value of X.
   5597   if (N0.getOpcode() == ISD::FP_ROUND
   5598       && N0.getNode()->getConstantOperandVal(1) == 1) {
   5599     SDValue In = N0.getOperand(0);
   5600     if (In.getValueType() == VT) return In;
   5601     if (VT.bitsLT(In.getValueType()))
   5602       return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
   5603                          In, N0.getOperand(1));
   5604     return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
   5605   }
   5606 
   5607   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
   5608   if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
   5609       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
   5610        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
   5611     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
   5612     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
   5613                                      LN0->getChain(),
   5614                                      LN0->getBasePtr(), LN0->getPointerInfo(),
   5615                                      N0.getValueType(),
   5616                                      LN0->isVolatile(), LN0->isNonTemporal(),
   5617                                      LN0->getAlignment());
   5618     CombineTo(N, ExtLoad);
   5619     CombineTo(N0.getNode(),
   5620               DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
   5621                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
   5622               ExtLoad.getValue(1));
   5623     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5624   }
   5625 
   5626   return SDValue();
   5627 }
   5628 
   5629 SDValue DAGCombiner::visitFNEG(SDNode *N) {
   5630   SDValue N0 = N->getOperand(0);
   5631   EVT VT = N->getValueType(0);
   5632 
   5633   if (isNegatibleForFree(N0, LegalOperations))
   5634     return GetNegatedExpression(N0, DAG, LegalOperations);
   5635 
   5636   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
   5637   // constant pool values.
   5638   if (N0.getOpcode() == ISD::BITCAST &&
   5639       !VT.isVector() &&
   5640       N0.getNode()->hasOneUse() &&
   5641       N0.getOperand(0).getValueType().isInteger()) {
   5642     SDValue Int = N0.getOperand(0);
   5643     EVT IntVT = Int.getValueType();
   5644     if (IntVT.isInteger() && !IntVT.isVector()) {
   5645       Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
   5646               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
   5647       AddToWorkList(Int.getNode());
   5648       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
   5649                          VT, Int);
   5650     }
   5651   }
   5652 
   5653   return SDValue();
   5654 }
   5655 
   5656 SDValue DAGCombiner::visitFABS(SDNode *N) {
   5657   SDValue N0 = N->getOperand(0);
   5658   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
   5659   EVT VT = N->getValueType(0);
   5660 
   5661   // fold (fabs c1) -> fabs(c1)
   5662   if (N0CFP && VT != MVT::ppcf128)
   5663     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
   5664   // fold (fabs (fabs x)) -> (fabs x)
   5665   if (N0.getOpcode() == ISD::FABS)
   5666     return N->getOperand(0);
   5667   // fold (fabs (fneg x)) -> (fabs x)
   5668   // fold (fabs (fcopysign x, y)) -> (fabs x)
   5669   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
   5670     return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
   5671 
   5672   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
   5673   // constant pool values.
   5674   if (N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
   5675       N0.getOperand(0).getValueType().isInteger() &&
   5676       !N0.getOperand(0).getValueType().isVector()) {
   5677     SDValue Int = N0.getOperand(0);
   5678     EVT IntVT = Int.getValueType();
   5679     if (IntVT.isInteger() && !IntVT.isVector()) {
   5680       Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
   5681              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
   5682       AddToWorkList(Int.getNode());
   5683       return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
   5684                          N->getValueType(0), Int);
   5685     }
   5686   }
   5687 
   5688   return SDValue();
   5689 }
   5690 
   5691 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
   5692   SDValue Chain = N->getOperand(0);
   5693   SDValue N1 = N->getOperand(1);
   5694   SDValue N2 = N->getOperand(2);
   5695 
   5696   // If N is a constant we could fold this into a fallthrough or unconditional
   5697   // branch. However that doesn't happen very often in normal code, because
   5698   // Instcombine/SimplifyCFG should have handled the available opportunities.
   5699   // If we did this folding here, it would be necessary to update the
   5700   // MachineBasicBlock CFG, which is awkward.
   5701 
   5702   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
   5703   // on the target.
   5704   if (N1.getOpcode() == ISD::SETCC &&
   5705       TLI.isOperationLegalOrCustom(ISD::BR_CC, MVT::Other)) {
   5706     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
   5707                        Chain, N1.getOperand(2),
   5708                        N1.getOperand(0), N1.getOperand(1), N2);
   5709   }
   5710 
   5711   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
   5712       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
   5713        (N1.getOperand(0).hasOneUse() &&
   5714         N1.getOperand(0).getOpcode() == ISD::SRL))) {
   5715     SDNode *Trunc = 0;
   5716     if (N1.getOpcode() == ISD::TRUNCATE) {
   5717       // Look pass the truncate.
   5718       Trunc = N1.getNode();
   5719       N1 = N1.getOperand(0);
   5720     }
   5721 
   5722     // Match this pattern so that we can generate simpler code:
   5723     //
   5724     //   %a = ...
   5725     //   %b = and i32 %a, 2
   5726     //   %c = srl i32 %b, 1
   5727     //   brcond i32 %c ...
   5728     //
   5729     // into
   5730     //
   5731     //   %a = ...
   5732     //   %b = and i32 %a, 2
   5733     //   %c = setcc eq %b, 0
   5734     //   brcond %c ...
   5735     //
   5736     // This applies only when the AND constant value has one bit set and the
   5737     // SRL constant is equal to the log2 of the AND constant. The back-end is
   5738     // smart enough to convert the result into a TEST/JMP sequence.
   5739     SDValue Op0 = N1.getOperand(0);
   5740     SDValue Op1 = N1.getOperand(1);
   5741 
   5742     if (Op0.getOpcode() == ISD::AND &&
   5743         Op1.getOpcode() == ISD::Constant) {
   5744       SDValue AndOp1 = Op0.getOperand(1);
   5745 
   5746       if (AndOp1.getOpcode() == ISD::Constant) {
   5747         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
   5748 
   5749         if (AndConst.isPowerOf2() &&
   5750             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
   5751           SDValue SetCC =
   5752             DAG.getSetCC(N->getDebugLoc(),
   5753                          TLI.getSetCCResultType(Op0.getValueType()),
   5754                          Op0, DAG.getConstant(0, Op0.getValueType()),
   5755                          ISD::SETNE);
   5756 
   5757           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
   5758                                           MVT::Other, Chain, SetCC, N2);
   5759           // Don't add the new BRCond into the worklist or else SimplifySelectCC
   5760           // will convert it back to (X & C1) >> C2.
   5761           CombineTo(N, NewBRCond, false);
   5762           // Truncate is dead.
   5763           if (Trunc) {
   5764             removeFromWorkList(Trunc);
   5765             DAG.DeleteNode(Trunc);
   5766           }
   5767           // Replace the uses of SRL with SETCC
   5768           WorkListRemover DeadNodes(*this);
   5769           DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
   5770           removeFromWorkList(N1.getNode());
   5771           DAG.DeleteNode(N1.getNode());
   5772           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   5773         }
   5774       }
   5775     }
   5776 
   5777     if (Trunc)
   5778       // Restore N1 if the above transformation doesn't match.
   5779       N1 = N->getOperand(1);
   5780   }
   5781 
   5782   // Transform br(xor(x, y)) -> br(x != y)
   5783   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
   5784   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
   5785     SDNode *TheXor = N1.getNode();
   5786     SDValue Op0 = TheXor->getOperand(0);
   5787     SDValue Op1 = TheXor->getOperand(1);
   5788     if (Op0.getOpcode() == Op1.getOpcode()) {
   5789       // Avoid missing important xor optimizations.
   5790       SDValue Tmp = visitXOR(TheXor);
   5791       if (Tmp.getNode() && Tmp.getNode() != TheXor) {
   5792         DEBUG(dbgs() << "\nReplacing.8 ";
   5793               TheXor->dump(&DAG);
   5794               dbgs() << "\nWith: ";
   5795               Tmp.getNode()->dump(&DAG);
   5796               dbgs() << '\n');
   5797         WorkListRemover DeadNodes(*this);
   5798         DAG.ReplaceAllUsesOfValueWith(N1, Tmp, &DeadNodes);
   5799         removeFromWorkList(TheXor);
   5800         DAG.DeleteNode(TheXor);
   5801         return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
   5802                            MVT::Other, Chain, Tmp, N2);
   5803       }
   5804     }
   5805 
   5806     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
   5807       bool Equal = false;
   5808       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
   5809         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
   5810             Op0.getOpcode() == ISD::XOR) {
   5811           TheXor = Op0.getNode();
   5812           Equal = true;
   5813         }
   5814 
   5815       EVT SetCCVT = N1.getValueType();
   5816       if (LegalTypes)
   5817         SetCCVT = TLI.getSetCCResultType(SetCCVT);
   5818       SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
   5819                                    SetCCVT,
   5820                                    Op0, Op1,
   5821                                    Equal ? ISD::SETEQ : ISD::SETNE);
   5822       // Replace the uses of XOR with SETCC
   5823       WorkListRemover DeadNodes(*this);
   5824       DAG.ReplaceAllUsesOfValueWith(N1, SetCC, &DeadNodes);
   5825       removeFromWorkList(N1.getNode());
   5826       DAG.DeleteNode(N1.getNode());
   5827       return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
   5828                          MVT::Other, Chain, SetCC, N2);
   5829     }
   5830   }
   5831 
   5832   return SDValue();
   5833 }
   5834 
   5835 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
   5836 //
   5837 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
   5838   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
   5839   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
   5840 
   5841   // If N is a constant we could fold this into a fallthrough or unconditional
   5842   // branch. However that doesn't happen very often in normal code, because
   5843   // Instcombine/SimplifyCFG should have handled the available opportunities.
   5844   // If we did this folding here, it would be necessary to update the
   5845   // MachineBasicBlock CFG, which is awkward.
   5846 
   5847   // Use SimplifySetCC to simplify SETCC's.
   5848   SDValue Simp = SimplifySetCC(TLI.getSetCCResultType(CondLHS.getValueType()),
   5849                                CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
   5850                                false);
   5851   if (Simp.getNode()) AddToWorkList(Simp.getNode());
   5852 
   5853   // fold to a simpler setcc
   5854   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
   5855     return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
   5856                        N->getOperand(0), Simp.getOperand(2),
   5857                        Simp.getOperand(0), Simp.getOperand(1),
   5858                        N->getOperand(4));
   5859 
   5860   return SDValue();
   5861 }
   5862 
   5863 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
   5864 /// pre-indexed load / store when the base pointer is an add or subtract
   5865 /// and it has other uses besides the load / store. After the
   5866 /// transformation, the new indexed load / store has effectively folded
   5867 /// the add / subtract in and all of its other uses are redirected to the
   5868 /// new load / store.
   5869 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
   5870   if (!LegalOperations)
   5871     return false;
   5872 
   5873   bool isLoad = true;
   5874   SDValue Ptr;
   5875   EVT VT;
   5876   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
   5877     if (LD->isIndexed())
   5878       return false;
   5879     VT = LD->getMemoryVT();
   5880     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
   5881         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
   5882       return false;
   5883     Ptr = LD->getBasePtr();
   5884   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
   5885     if (ST->isIndexed())
   5886       return false;
   5887     VT = ST->getMemoryVT();
   5888     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
   5889         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
   5890       return false;
   5891     Ptr = ST->getBasePtr();
   5892     isLoad = false;
   5893   } else {
   5894     return false;
   5895   }
   5896 
   5897   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
   5898   // out.  There is no reason to make this a preinc/predec.
   5899   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
   5900       Ptr.getNode()->hasOneUse())
   5901     return false;
   5902 
   5903   // Ask the target to do addressing mode selection.
   5904   SDValue BasePtr;
   5905   SDValue Offset;
   5906   ISD::MemIndexedMode AM = ISD::UNINDEXED;
   5907   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
   5908     return false;
   5909   // Don't create a indexed load / store with zero offset.
   5910   if (isa<ConstantSDNode>(Offset) &&
   5911       cast<ConstantSDNode>(Offset)->isNullValue())
   5912     return false;
   5913 
   5914   // Try turning it into a pre-indexed load / store except when:
   5915   // 1) The new base ptr is a frame index.
   5916   // 2) If N is a store and the new base ptr is either the same as or is a
   5917   //    predecessor of the value being stored.
   5918   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
   5919   //    that would create a cycle.
   5920   // 4) All uses are load / store ops that use it as old base ptr.
   5921 
   5922   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
   5923   // (plus the implicit offset) to a register to preinc anyway.
   5924   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
   5925     return false;
   5926 
   5927   // Check #2.
   5928   if (!isLoad) {
   5929     SDValue Val = cast<StoreSDNode>(N)->getValue();
   5930     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
   5931       return false;
   5932   }
   5933 
   5934   // Now check for #3 and #4.
   5935   bool RealUse = false;
   5936 
   5937   // Caches for hasPredecessorHelper
   5938   SmallPtrSet<const SDNode *, 32> Visited;
   5939   SmallVector<const SDNode *, 16> Worklist;
   5940 
   5941   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
   5942          E = Ptr.getNode()->use_end(); I != E; ++I) {
   5943     SDNode *Use = *I;
   5944     if (Use == N)
   5945       continue;
   5946     if (N->hasPredecessorHelper(Use, Visited, Worklist))
   5947       return false;
   5948 
   5949     if (!((Use->getOpcode() == ISD::LOAD &&
   5950            cast<LoadSDNode>(Use)->getBasePtr() == Ptr) ||
   5951           (Use->getOpcode() == ISD::STORE &&
   5952            cast<StoreSDNode>(Use)->getBasePtr() == Ptr)))
   5953       RealUse = true;
   5954   }
   5955 
   5956   if (!RealUse)
   5957     return false;
   5958 
   5959   SDValue Result;
   5960   if (isLoad)
   5961     Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
   5962                                 BasePtr, Offset, AM);
   5963   else
   5964     Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
   5965                                  BasePtr, Offset, AM);
   5966   ++PreIndexedNodes;
   5967   ++NodesCombined;
   5968   DEBUG(dbgs() << "\nReplacing.4 ";
   5969         N->dump(&DAG);
   5970         dbgs() << "\nWith: ";
   5971         Result.getNode()->dump(&DAG);
   5972         dbgs() << '\n');
   5973   WorkListRemover DeadNodes(*this);
   5974   if (isLoad) {
   5975     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
   5976                                   &DeadNodes);
   5977     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
   5978                                   &DeadNodes);
   5979   } else {
   5980     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
   5981                                   &DeadNodes);
   5982   }
   5983 
   5984   // Finally, since the node is now dead, remove it from the graph.
   5985   DAG.DeleteNode(N);
   5986 
   5987   // Replace the uses of Ptr with uses of the updated base value.
   5988   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0),
   5989                                 &DeadNodes);
   5990   removeFromWorkList(Ptr.getNode());
   5991   DAG.DeleteNode(Ptr.getNode());
   5992 
   5993   return true;
   5994 }
   5995 
   5996 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
   5997 /// add / sub of the base pointer node into a post-indexed load / store.
   5998 /// The transformation folded the add / subtract into the new indexed
   5999 /// load / store effectively and all of its uses are redirected to the
   6000 /// new load / store.
   6001 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
   6002   if (!LegalOperations)
   6003     return false;
   6004 
   6005   bool isLoad = true;
   6006   SDValue Ptr;
   6007   EVT VT;
   6008   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
   6009     if (LD->isIndexed())
   6010       return false;
   6011     VT = LD->getMemoryVT();
   6012     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
   6013         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
   6014       return false;
   6015     Ptr = LD->getBasePtr();
   6016   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
   6017     if (ST->isIndexed())
   6018       return false;
   6019     VT = ST->getMemoryVT();
   6020     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
   6021         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
   6022       return false;
   6023     Ptr = ST->getBasePtr();
   6024     isLoad = false;
   6025   } else {
   6026     return false;
   6027   }
   6028 
   6029   if (Ptr.getNode()->hasOneUse())
   6030     return false;
   6031 
   6032   for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
   6033          E = Ptr.getNode()->use_end(); I != E; ++I) {
   6034     SDNode *Op = *I;
   6035     if (Op == N ||
   6036         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
   6037       continue;
   6038 
   6039     SDValue BasePtr;
   6040     SDValue Offset;
   6041     ISD::MemIndexedMode AM = ISD::UNINDEXED;
   6042     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
   6043       // Don't create a indexed load / store with zero offset.
   6044       if (isa<ConstantSDNode>(Offset) &&
   6045           cast<ConstantSDNode>(Offset)->isNullValue())
   6046         continue;
   6047 
   6048       // Try turning it into a post-indexed load / store except when
   6049       // 1) All uses are load / store ops that use it as base ptr.
   6050       // 2) Op must be independent of N, i.e. Op is neither a predecessor
   6051       //    nor a successor of N. Otherwise, if Op is folded that would
   6052       //    create a cycle.
   6053 
   6054       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
   6055         continue;
   6056 
   6057       // Check for #1.
   6058       bool TryNext = false;
   6059       for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
   6060              EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
   6061         SDNode *Use = *II;
   6062         if (Use == Ptr.getNode())
   6063           continue;
   6064 
   6065         // If all the uses are load / store addresses, then don't do the
   6066         // transformation.
   6067         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
   6068           bool RealUse = false;
   6069           for (SDNode::use_iterator III = Use->use_begin(),
   6070                  EEE = Use->use_end(); III != EEE; ++III) {
   6071             SDNode *UseUse = *III;
   6072             if (!((UseUse->getOpcode() == ISD::LOAD &&
   6073                    cast<LoadSDNode>(UseUse)->getBasePtr().getNode() == Use) ||
   6074                   (UseUse->getOpcode() == ISD::STORE &&
   6075                    cast<StoreSDNode>(UseUse)->getBasePtr().getNode() == Use)))
   6076               RealUse = true;
   6077           }
   6078 
   6079           if (!RealUse) {
   6080             TryNext = true;
   6081             break;
   6082           }
   6083         }
   6084       }
   6085 
   6086       if (TryNext)
   6087         continue;
   6088 
   6089       // Check for #2
   6090       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
   6091         SDValue Result = isLoad
   6092           ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
   6093                                BasePtr, Offset, AM)
   6094           : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
   6095                                 BasePtr, Offset, AM);
   6096         ++PostIndexedNodes;
   6097         ++NodesCombined;
   6098         DEBUG(dbgs() << "\nReplacing.5 ";
   6099               N->dump(&DAG);
   6100               dbgs() << "\nWith: ";
   6101               Result.getNode()->dump(&DAG);
   6102               dbgs() << '\n');
   6103         WorkListRemover DeadNodes(*this);
   6104         if (isLoad) {
   6105           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0),
   6106                                         &DeadNodes);
   6107           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2),
   6108                                         &DeadNodes);
   6109         } else {
   6110           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1),
   6111                                         &DeadNodes);
   6112         }
   6113 
   6114         // Finally, since the node is now dead, remove it from the graph.
   6115         DAG.DeleteNode(N);
   6116 
   6117         // Replace the uses of Use with uses of the updated base value.
   6118         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
   6119                                       Result.getValue(isLoad ? 1 : 0),
   6120                                       &DeadNodes);
   6121         removeFromWorkList(Op);
   6122         DAG.DeleteNode(Op);
   6123         return true;
   6124       }
   6125     }
   6126   }
   6127 
   6128   return false;
   6129 }
   6130 
   6131 SDValue DAGCombiner::visitLOAD(SDNode *N) {
   6132   LoadSDNode *LD  = cast<LoadSDNode>(N);
   6133   SDValue Chain = LD->getChain();
   6134   SDValue Ptr   = LD->getBasePtr();
   6135 
   6136   // If load is not volatile and there are no uses of the loaded value (and
   6137   // the updated indexed value in case of indexed loads), change uses of the
   6138   // chain value into uses of the chain input (i.e. delete the dead load).
   6139   if (!LD->isVolatile()) {
   6140     if (N->getValueType(1) == MVT::Other) {
   6141       // Unindexed loads.
   6142       if (N->hasNUsesOfValue(0, 0)) {
   6143         // It's not safe to use the two value CombineTo variant here. e.g.
   6144         // v1, chain2 = load chain1, loc
   6145         // v2, chain3 = load chain2, loc
   6146         // v3         = add v2, c
   6147         // Now we replace use of chain2 with chain1.  This makes the second load
   6148         // isomorphic to the one we are deleting, and thus makes this load live.
   6149         DEBUG(dbgs() << "\nReplacing.6 ";
   6150               N->dump(&DAG);
   6151               dbgs() << "\nWith chain: ";
   6152               Chain.getNode()->dump(&DAG);
   6153               dbgs() << "\n");
   6154         WorkListRemover DeadNodes(*this);
   6155         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain, &DeadNodes);
   6156 
   6157         if (N->use_empty()) {
   6158           removeFromWorkList(N);
   6159           DAG.DeleteNode(N);
   6160         }
   6161 
   6162         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6163       }
   6164     } else {
   6165       // Indexed loads.
   6166       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
   6167       if (N->hasNUsesOfValue(0, 0) && N->hasNUsesOfValue(0, 1)) {
   6168         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
   6169         DEBUG(dbgs() << "\nReplacing.7 ";
   6170               N->dump(&DAG);
   6171               dbgs() << "\nWith: ";
   6172               Undef.getNode()->dump(&DAG);
   6173               dbgs() << " and 2 other values\n");
   6174         WorkListRemover DeadNodes(*this);
   6175         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef, &DeadNodes);
   6176         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
   6177                                       DAG.getUNDEF(N->getValueType(1)),
   6178                                       &DeadNodes);
   6179         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain, &DeadNodes);
   6180         removeFromWorkList(N);
   6181         DAG.DeleteNode(N);
   6182         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
   6183       }
   6184     }
   6185   }
   6186 
   6187   // If this load is directly stored, replace the load value with the stored
   6188   // value.
   6189   // TODO: Handle store large -> read small portion.
   6190   // TODO: Handle TRUNCSTORE/LOADEXT
   6191   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
   6192     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
   6193       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
   6194       if (PrevST->getBasePtr() == Ptr &&
   6195           PrevST->getValue().getValueType() == N->getValueType(0))
   6196       return CombineTo(N, Chain.getOperand(1), Chain);
   6197     }
   6198   }
   6199 
   6200   // Try to infer better alignment information than the load already has.
   6201   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
   6202     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
   6203       if (Align > LD->getAlignment())
   6204         return DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
   6205                               LD->getValueType(0),
   6206                               Chain, Ptr, LD->getPointerInfo(),
   6207                               LD->getMemoryVT(),
   6208                               LD->isVolatile(), LD->isNonTemporal(), Align);
   6209     }
   6210   }
   6211 
   6212   if (CombinerAA) {
   6213     // Walk up chain skipping non-aliasing memory nodes.
   6214     SDValue BetterChain = FindBetterChain(N, Chain);
   6215 
   6216     // If there is a better chain.
   6217     if (Chain != BetterChain) {
   6218       SDValue ReplLoad;
   6219 
   6220       // Replace the chain to void dependency.
   6221       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
   6222         ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
   6223                                BetterChain, Ptr, LD->getPointerInfo(),
   6224                                LD->isVolatile(), LD->isNonTemporal(),
   6225                                LD->getAlignment());
   6226       } else {
   6227         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
   6228                                   LD->getValueType(0),
   6229                                   BetterChain, Ptr, LD->getPointerInfo(),
   6230                                   LD->getMemoryVT(),
   6231                                   LD->isVolatile(),
   6232                                   LD->isNonTemporal(),
   6233                                   LD->getAlignment());
   6234       }
   6235 
   6236       // Create token factor to keep old chain connected.
   6237       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
   6238                                   MVT::Other, Chain, ReplLoad.getValue(1));
   6239 
   6240       // Make sure the new and old chains are cleaned up.
   6241       AddToWorkList(Token.getNode());
   6242 
   6243       // Replace uses with load result and token factor. Don't add users
   6244       // to work list.
   6245       return CombineTo(N, ReplLoad.getValue(0), Token, false);
   6246     }
   6247   }
   6248 
   6249   // Try transforming N to an indexed load.
   6250   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
   6251     return SDValue(N, 0);
   6252 
   6253   return SDValue();
   6254 }
   6255 
   6256 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
   6257 /// load is having specific bytes cleared out.  If so, return the byte size
   6258 /// being masked out and the shift amount.
   6259 static std::pair<unsigned, unsigned>
   6260 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
   6261   std::pair<unsigned, unsigned> Result(0, 0);
   6262 
   6263   // Check for the structure we're looking for.
   6264   if (V->getOpcode() != ISD::AND ||
   6265       !isa<ConstantSDNode>(V->getOperand(1)) ||
   6266       !ISD::isNormalLoad(V->getOperand(0).getNode()))
   6267     return Result;
   6268 
   6269   // Check the chain and pointer.
   6270   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
   6271   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
   6272 
   6273   // The store should be chained directly to the load or be an operand of a
   6274   // tokenfactor.
   6275   if (LD == Chain.getNode())
   6276     ; // ok.
   6277   else if (Chain->getOpcode() != ISD::TokenFactor)
   6278     return Result; // Fail.
   6279   else {
   6280     bool isOk = false;
   6281     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
   6282       if (Chain->getOperand(i).getNode() == LD) {
   6283         isOk = true;
   6284         break;
   6285       }
   6286     if (!isOk) return Result;
   6287   }
   6288 
   6289   // This only handles simple types.
   6290   if (V.getValueType() != MVT::i16 &&
   6291       V.getValueType() != MVT::i32 &&
   6292       V.getValueType() != MVT::i64)
   6293     return Result;
   6294 
   6295   // Check the constant mask.  Invert it so that the bits being masked out are
   6296   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
   6297   // follow the sign bit for uniformity.
   6298   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
   6299   unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
   6300   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
   6301   unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
   6302   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
   6303   if (NotMaskLZ == 64) return Result;  // All zero mask.
   6304 
   6305   // See if we have a continuous run of bits.  If so, we have 0*1+0*
   6306   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
   6307     return Result;
   6308 
   6309   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
   6310   if (V.getValueType() != MVT::i64 && NotMaskLZ)
   6311     NotMaskLZ -= 64-V.getValueSizeInBits();
   6312 
   6313   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
   6314   switch (MaskedBytes) {
   6315   case 1:
   6316   case 2:
   6317   case 4: break;
   6318   default: return Result; // All one mask, or 5-byte mask.
   6319   }
   6320 
   6321   // Verify that the first bit starts at a multiple of mask so that the access
   6322   // is aligned the same as the access width.
   6323   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
   6324 
   6325   Result.first = MaskedBytes;
   6326   Result.second = NotMaskTZ/8;
   6327   return Result;
   6328 }
   6329 
   6330 
   6331 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
   6332 /// provides a value as specified by MaskInfo.  If so, replace the specified
   6333 /// store with a narrower store of truncated IVal.
   6334 static SDNode *
   6335 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
   6336                                 SDValue IVal, StoreSDNode *St,
   6337                                 DAGCombiner *DC) {
   6338   unsigned NumBytes = MaskInfo.first;
   6339   unsigned ByteShift = MaskInfo.second;
   6340   SelectionDAG &DAG = DC->getDAG();
   6341 
   6342   // Check to see if IVal is all zeros in the part being masked in by the 'or'
   6343   // that uses this.  If not, this is not a replacement.
   6344   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
   6345                                   ByteShift*8, (ByteShift+NumBytes)*8);
   6346   if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
   6347 
   6348   // Check that it is legal on the target to do this.  It is legal if the new
   6349   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
   6350   // legalization.
   6351   MVT VT = MVT::getIntegerVT(NumBytes*8);
   6352   if (!DC->isTypeLegal(VT))
   6353     return 0;
   6354 
   6355   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
   6356   // shifted by ByteShift and truncated down to NumBytes.
   6357   if (ByteShift)
   6358     IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
   6359                        DAG.getConstant(ByteShift*8,
   6360                                     DC->getShiftAmountTy(IVal.getValueType())));
   6361 
   6362   // Figure out the offset for the store and the alignment of the access.
   6363   unsigned StOffset;
   6364   unsigned NewAlign = St->getAlignment();
   6365 
   6366   if (DAG.getTargetLoweringInfo().isLittleEndian())
   6367     StOffset = ByteShift;
   6368   else
   6369     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
   6370 
   6371   SDValue Ptr = St->getBasePtr();
   6372   if (StOffset) {
   6373     Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
   6374                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
   6375     NewAlign = MinAlign(NewAlign, StOffset);
   6376   }
   6377 
   6378   // Truncate down to the new size.
   6379   IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
   6380 
   6381   ++OpsNarrowed;
   6382   return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
   6383                       St->getPointerInfo().getWithOffset(StOffset),
   6384                       false, false, NewAlign).getNode();
   6385 }
   6386 
   6387 
   6388 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
   6389 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
   6390 /// of the loaded bits, try narrowing the load and store if it would end up
   6391 /// being a win for performance or code size.
   6392 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
   6393   StoreSDNode *ST  = cast<StoreSDNode>(N);
   6394   if (ST->isVolatile())
   6395     return SDValue();
   6396 
   6397   SDValue Chain = ST->getChain();
   6398   SDValue Value = ST->getValue();
   6399   SDValue Ptr   = ST->getBasePtr();
   6400   EVT VT = Value.getValueType();
   6401 
   6402   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
   6403     return SDValue();
   6404 
   6405   unsigned Opc = Value.getOpcode();
   6406 
   6407   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
   6408   // is a byte mask indicating a consecutive number of bytes, check to see if
   6409   // Y is known to provide just those bytes.  If so, we try to replace the
   6410   // load + replace + store sequence with a single (narrower) store, which makes
   6411   // the load dead.
   6412   if (Opc == ISD::OR) {
   6413     std::pair<unsigned, unsigned> MaskedLoad;
   6414     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
   6415     if (MaskedLoad.first)
   6416       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
   6417                                                   Value.getOperand(1), ST,this))
   6418         return SDValue(NewST, 0);
   6419 
   6420     // Or is commutative, so try swapping X and Y.
   6421     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
   6422     if (MaskedLoad.first)
   6423       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
   6424                                                   Value.getOperand(0), ST,this))
   6425         return SDValue(NewST, 0);
   6426   }
   6427 
   6428   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
   6429       Value.getOperand(1).getOpcode() != ISD::Constant)
   6430     return SDValue();
   6431 
   6432   SDValue N0 = Value.getOperand(0);
   6433   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
   6434       Chain == SDValue(N0.getNode(), 1)) {
   6435     LoadSDNode *LD = cast<LoadSDNode>(N0);
   6436     if (LD->getBasePtr() != Ptr ||
   6437         LD->getPointerInfo().getAddrSpace() !=
   6438         ST->getPointerInfo().getAddrSpace())
   6439       return SDValue();
   6440 
   6441     // Find the type to narrow it the load / op / store to.
   6442     SDValue N1 = Value.getOperand(1);
   6443     unsigned BitWidth = N1.getValueSizeInBits();
   6444     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
   6445     if (Opc == ISD::AND)
   6446       Imm ^= APInt::getAllOnesValue(BitWidth);
   6447     if (Imm == 0 || Imm.isAllOnesValue())
   6448       return SDValue();
   6449     unsigned ShAmt = Imm.countTrailingZeros();
   6450     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
   6451     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
   6452     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
   6453     while (NewBW < BitWidth &&
   6454            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
   6455              TLI.isNarrowingProfitable(VT, NewVT))) {
   6456       NewBW = NextPowerOf2(NewBW);
   6457       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
   6458     }
   6459     if (NewBW >= BitWidth)
   6460       return SDValue();
   6461 
   6462     // If the lsb changed does not start at the type bitwidth boundary,
   6463     // start at the previous one.
   6464     if (ShAmt % NewBW)
   6465       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
   6466     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt, ShAmt + NewBW);
   6467     if ((Imm & Mask) == Imm) {
   6468       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
   6469       if (Opc == ISD::AND)
   6470         NewImm ^= APInt::getAllOnesValue(NewBW);
   6471       uint64_t PtrOff = ShAmt / 8;
   6472       // For big endian targets, we need to adjust the offset to the pointer to
   6473       // load the correct bytes.
   6474       if (TLI.isBigEndian())
   6475         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
   6476 
   6477       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
   6478       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
   6479       if (NewAlign < TLI.getTargetData()->getABITypeAlignment(NewVTTy))
   6480         return SDValue();
   6481 
   6482       SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
   6483                                    Ptr.getValueType(), Ptr,
   6484                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
   6485       SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
   6486                                   LD->getChain(), NewPtr,
   6487                                   LD->getPointerInfo().getWithOffset(PtrOff),
   6488                                   LD->isVolatile(), LD->isNonTemporal(),
   6489                                   NewAlign);
   6490       SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
   6491                                    DAG.getConstant(NewImm, NewVT));
   6492       SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
   6493                                    NewVal, NewPtr,
   6494                                    ST->getPointerInfo().getWithOffset(PtrOff),
   6495                                    false, false, NewAlign);
   6496 
   6497       AddToWorkList(NewPtr.getNode());
   6498       AddToWorkList(NewLD.getNode());
   6499       AddToWorkList(NewVal.getNode());
   6500       WorkListRemover DeadNodes(*this);
   6501       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1),
   6502                                     &DeadNodes);
   6503       ++OpsNarrowed;
   6504       return NewST;
   6505     }
   6506   }
   6507 
   6508   return SDValue();
   6509 }
   6510 
   6511 /// TransformFPLoadStorePair - For a given floating point load / store pair,
   6512 /// if the load value isn't used by any other operations, then consider
   6513 /// transforming the pair to integer load / store operations if the target
   6514 /// deems the transformation profitable.
   6515 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
   6516   StoreSDNode *ST  = cast<StoreSDNode>(N);
   6517   SDValue Chain = ST->getChain();
   6518   SDValue Value = ST->getValue();
   6519   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
   6520       Value.hasOneUse() &&
   6521       Chain == SDValue(Value.getNode(), 1)) {
   6522     LoadSDNode *LD = cast<LoadSDNode>(Value);
   6523     EVT VT = LD->getMemoryVT();
   6524     if (!VT.isFloatingPoint() ||
   6525         VT != ST->getMemoryVT() ||
   6526         LD->isNonTemporal() ||
   6527         ST->isNonTemporal() ||
   6528         LD->getPointerInfo().getAddrSpace() != 0 ||
   6529         ST->getPointerInfo().getAddrSpace() != 0)
   6530       return SDValue();
   6531 
   6532     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
   6533     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
   6534         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
   6535         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
   6536         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
   6537       return SDValue();
   6538 
   6539     unsigned LDAlign = LD->getAlignment();
   6540     unsigned STAlign = ST->getAlignment();
   6541     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
   6542     unsigned ABIAlign = TLI.getTargetData()->getABITypeAlignment(IntVTTy);
   6543     if (LDAlign < ABIAlign || STAlign < ABIAlign)
   6544       return SDValue();
   6545 
   6546     SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
   6547                                 LD->getChain(), LD->getBasePtr(),
   6548                                 LD->getPointerInfo(),
   6549                                 false, false, LDAlign);
   6550 
   6551     SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
   6552                                  NewLD, ST->getBasePtr(),
   6553                                  ST->getPointerInfo(),
   6554                                  false, false, STAlign);
   6555 
   6556     AddToWorkList(NewLD.getNode());
   6557     AddToWorkList(NewST.getNode());
   6558     WorkListRemover DeadNodes(*this);
   6559     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1),
   6560                                   &DeadNodes);
   6561     ++LdStFP2Int;
   6562     return NewST;
   6563   }
   6564 
   6565   return SDValue();
   6566 }
   6567 
   6568 SDValue DAGCombiner::visitSTORE(SDNode *N) {
   6569   StoreSDNode *ST  = cast<StoreSDNode>(N);
   6570   SDValue Chain = ST->getChain();
   6571   SDValue Value = ST->getValue();
   6572   SDValue Ptr   = ST->getBasePtr();
   6573 
   6574   // If this is a store of a bit convert, store the input value if the
   6575   // resultant store does not need a higher alignment than the original.
   6576   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
   6577       ST->isUnindexed()) {
   6578     unsigned OrigAlign = ST->getAlignment();
   6579     EVT SVT = Value.getOperand(0).getValueType();
   6580     unsigned Align = TLI.getTargetData()->
   6581       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
   6582     if (Align <= OrigAlign &&
   6583         ((!LegalOperations && !ST->isVolatile()) ||
   6584          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
   6585       return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
   6586                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
   6587                           ST->isNonTemporal(), OrigAlign);
   6588   }
   6589 
   6590   // Turn 'store undef, Ptr' -> nothing.
   6591   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
   6592     return Chain;
   6593 
   6594   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
   6595   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
   6596     // NOTE: If the original store is volatile, this transform must not increase
   6597     // the number of stores.  For example, on x86-32 an f64 can be stored in one
   6598     // processor operation but an i64 (which is not legal) requires two.  So the
   6599     // transform should not be done in this case.
   6600     if (Value.getOpcode() != ISD::TargetConstantFP) {
   6601       SDValue Tmp;
   6602       switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
   6603       default: llvm_unreachable("Unknown FP type");
   6604       case MVT::f80:    // We don't do this for these yet.
   6605       case MVT::f128:
   6606       case MVT::ppcf128:
   6607         break;
   6608       case MVT::f32:
   6609         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
   6610             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
   6611           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
   6612                               bitcastToAPInt().getZExtValue(), MVT::i32);
   6613           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
   6614                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
   6615                               ST->isNonTemporal(), ST->getAlignment());
   6616         }
   6617         break;
   6618       case MVT::f64:
   6619         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
   6620              !ST->isVolatile()) ||
   6621             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
   6622           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
   6623                                 getZExtValue(), MVT::i64);
   6624           return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
   6625                               Ptr, ST->getPointerInfo(), ST->isVolatile(),
   6626                               ST->isNonTemporal(), ST->getAlignment());
   6627         }
   6628 
   6629         if (!ST->isVolatile() &&
   6630             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
   6631           // Many FP stores are not made apparent until after legalize, e.g. for
   6632           // argument passing.  Since this is so common, custom legalize the
   6633           // 64-bit integer store into two 32-bit stores.
   6634           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
   6635           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
   6636           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
   6637           if (TLI.isBigEndian()) std::swap(Lo, Hi);
   6638 
   6639           unsigned Alignment = ST->getAlignment();
   6640           bool isVolatile = ST->isVolatile();
   6641           bool isNonTemporal = ST->isNonTemporal();
   6642 
   6643           SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
   6644                                      Ptr, ST->getPointerInfo(),
   6645                                      isVolatile, isNonTemporal,
   6646                                      ST->getAlignment());
   6647           Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
   6648                             DAG.getConstant(4, Ptr.getValueType()));
   6649           Alignment = MinAlign(Alignment, 4U);
   6650           SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
   6651                                      Ptr, ST->getPointerInfo().getWithOffset(4),
   6652                                      isVolatile, isNonTemporal,
   6653                                      Alignment);
   6654           return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
   6655                              St0, St1);
   6656         }
   6657 
   6658         break;
   6659       }
   6660     }
   6661   }
   6662 
   6663   // Try to infer better alignment information than the store already has.
   6664   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
   6665     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
   6666       if (Align > ST->getAlignment())
   6667         return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
   6668                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
   6669                                  ST->isVolatile(), ST->isNonTemporal(), Align);
   6670     }
   6671   }
   6672 
   6673   // Try transforming a pair floating point load / store ops to integer
   6674   // load / store ops.
   6675   SDValue NewST = TransformFPLoadStorePair(N);
   6676   if (NewST.getNode())
   6677     return NewST;
   6678 
   6679   if (CombinerAA) {
   6680     // Walk up chain skipping non-aliasing memory nodes.
   6681     SDValue BetterChain = FindBetterChain(N, Chain);
   6682 
   6683     // If there is a better chain.
   6684     if (Chain != BetterChain) {
   6685       SDValue ReplStore;
   6686 
   6687       // Replace the chain to avoid dependency.
   6688       if (ST->isTruncatingStore()) {
   6689         ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
   6690                                       ST->getPointerInfo(),
   6691                                       ST->getMemoryVT(), ST->isVolatile(),
   6692                                       ST->isNonTemporal(), ST->getAlignment());
   6693       } else {
   6694         ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
   6695                                  ST->getPointerInfo(),
   6696                                  ST->isVolatile(), ST->isNonTemporal(),
   6697                                  ST->getAlignment());
   6698       }
   6699 
   6700       // Create token to keep both nodes around.
   6701       SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
   6702                                   MVT::Other, Chain, ReplStore);
   6703 
   6704       // Make sure the new and old chains are cleaned up.
   6705       AddToWorkList(Token.getNode());
   6706 
   6707       // Don't add users to work list.
   6708       return CombineTo(N, Token, false);
   6709     }
   6710   }
   6711 
   6712   // Try transforming N to an indexed store.
   6713   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
   6714     return SDValue(N, 0);
   6715 
   6716   // FIXME: is there such a thing as a truncating indexed store?
   6717   if (ST->isTruncatingStore() && ST->isUnindexed() &&
   6718       Value.getValueType().isInteger()) {
   6719     // See if we can simplify the input to this truncstore with knowledge that
   6720     // only the low bits are being used.  For example:
   6721     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
   6722     SDValue Shorter =
   6723       GetDemandedBits(Value,
   6724                       APInt::getLowBitsSet(
   6725                         Value.getValueType().getScalarType().getSizeInBits(),
   6726                         ST->getMemoryVT().getScalarType().getSizeInBits()));
   6727     AddToWorkList(Value.getNode());
   6728     if (Shorter.getNode())
   6729       return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
   6730                                Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
   6731                                ST->isVolatile(), ST->isNonTemporal(),
   6732                                ST->getAlignment());
   6733 
   6734     // Otherwise, see if we can simplify the operation with
   6735     // SimplifyDemandedBits, which only works if the value has a single use.
   6736     if (SimplifyDemandedBits(Value,
   6737                         APInt::getLowBitsSet(
   6738                           Value.getValueType().getScalarType().getSizeInBits(),
   6739                           ST->getMemoryVT().getScalarType().getSizeInBits())))
   6740       return SDValue(N, 0);
   6741   }
   6742 
   6743   // If this is a load followed by a store to the same location, then the store
   6744   // is dead/noop.
   6745   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
   6746     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
   6747         ST->isUnindexed() && !ST->isVolatile() &&
   6748         // There can't be any side effects between the load and store, such as
   6749         // a call or store.
   6750         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
   6751       // The store is dead, remove it.
   6752       return Chain;
   6753     }
   6754   }
   6755 
   6756   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
   6757   // truncating store.  We can do this even if this is already a truncstore.
   6758   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
   6759       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
   6760       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
   6761                             ST->getMemoryVT())) {
   6762     return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
   6763                              Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
   6764                              ST->isVolatile(), ST->isNonTemporal(),
   6765                              ST->getAlignment());
   6766   }
   6767 
   6768   return ReduceLoadOpStoreWidth(N);
   6769 }
   6770 
   6771 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
   6772   SDValue InVec = N->getOperand(0);
   6773   SDValue InVal = N->getOperand(1);
   6774   SDValue EltNo = N->getOperand(2);
   6775   DebugLoc dl = N->getDebugLoc();
   6776 
   6777   // If the inserted element is an UNDEF, just use the input vector.
   6778   if (InVal.getOpcode() == ISD::UNDEF)
   6779     return InVec;
   6780 
   6781   EVT VT = InVec.getValueType();
   6782 
   6783   // If we can't generate a legal BUILD_VECTOR, exit
   6784   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
   6785     return SDValue();
   6786 
   6787   // Check that we know which element is being inserted
   6788   if (!isa<ConstantSDNode>(EltNo))
   6789     return SDValue();
   6790   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   6791 
   6792   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
   6793   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
   6794   // vector elements.
   6795   SmallVector<SDValue, 8> Ops;
   6796   if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
   6797     Ops.append(InVec.getNode()->op_begin(),
   6798                InVec.getNode()->op_end());
   6799   } else if (InVec.getOpcode() == ISD::UNDEF) {
   6800     unsigned NElts = VT.getVectorNumElements();
   6801     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
   6802   } else {
   6803     return SDValue();
   6804   }
   6805 
   6806   // Insert the element
   6807   if (Elt < Ops.size()) {
   6808     // All the operands of BUILD_VECTOR must have the same type;
   6809     // we enforce that here.
   6810     EVT OpVT = Ops[0].getValueType();
   6811     if (InVal.getValueType() != OpVT)
   6812       InVal = OpVT.bitsGT(InVal.getValueType()) ?
   6813                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
   6814                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
   6815     Ops[Elt] = InVal;
   6816   }
   6817 
   6818   // Return the new vector
   6819   return DAG.getNode(ISD::BUILD_VECTOR, dl,
   6820                      VT, &Ops[0], Ops.size());
   6821 }
   6822 
   6823 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
   6824   // (vextract (scalar_to_vector val, 0) -> val
   6825   SDValue InVec = N->getOperand(0);
   6826 
   6827   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
   6828     // Check if the result type doesn't match the inserted element type. A
   6829     // SCALAR_TO_VECTOR may truncate the inserted element and the
   6830     // EXTRACT_VECTOR_ELT may widen the extracted vector.
   6831     SDValue InOp = InVec.getOperand(0);
   6832     EVT NVT = N->getValueType(0);
   6833     if (InOp.getValueType() != NVT) {
   6834       assert(InOp.getValueType().isInteger() && NVT.isInteger());
   6835       return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
   6836     }
   6837     return InOp;
   6838   }
   6839 
   6840   // Perform only after legalization to ensure build_vector / vector_shuffle
   6841   // optimizations have already been done.
   6842   if (!LegalOperations) return SDValue();
   6843 
   6844   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
   6845   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
   6846   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
   6847   SDValue EltNo = N->getOperand(1);
   6848 
   6849   if (isa<ConstantSDNode>(EltNo)) {
   6850     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
   6851     bool NewLoad = false;
   6852     bool BCNumEltsChanged = false;
   6853     EVT VT = InVec.getValueType();
   6854     EVT ExtVT = VT.getVectorElementType();
   6855     EVT LVT = ExtVT;
   6856 
   6857     if (InVec.getOpcode() == ISD::BITCAST) {
   6858       EVT BCVT = InVec.getOperand(0).getValueType();
   6859       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
   6860         return SDValue();
   6861       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
   6862         BCNumEltsChanged = true;
   6863       InVec = InVec.getOperand(0);
   6864       ExtVT = BCVT.getVectorElementType();
   6865       NewLoad = true;
   6866     }
   6867 
   6868     LoadSDNode *LN0 = NULL;
   6869     const ShuffleVectorSDNode *SVN = NULL;
   6870     if (ISD::isNormalLoad(InVec.getNode())) {
   6871       LN0 = cast<LoadSDNode>(InVec);
   6872     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
   6873                InVec.getOperand(0).getValueType() == ExtVT &&
   6874                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
   6875       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
   6876     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
   6877       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
   6878       // =>
   6879       // (load $addr+1*size)
   6880 
   6881       // If the bit convert changed the number of elements, it is unsafe
   6882       // to examine the mask.
   6883       if (BCNumEltsChanged)
   6884         return SDValue();
   6885 
   6886       // Select the input vector, guarding against out of range extract vector.
   6887       unsigned NumElems = VT.getVectorNumElements();
   6888       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
   6889       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
   6890 
   6891       if (InVec.getOpcode() == ISD::BITCAST)
   6892         InVec = InVec.getOperand(0);
   6893       if (ISD::isNormalLoad(InVec.getNode())) {
   6894         LN0 = cast<LoadSDNode>(InVec);
   6895         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
   6896       }
   6897     }
   6898 
   6899     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
   6900       return SDValue();
   6901 
   6902     // If Idx was -1 above, Elt is going to be -1, so just return undef.
   6903     if (Elt == -1)
   6904       return DAG.getUNDEF(LVT);
   6905 
   6906     unsigned Align = LN0->getAlignment();
   6907     if (NewLoad) {
   6908       // Check the resultant load doesn't need a higher alignment than the
   6909       // original load.
   6910       unsigned NewAlign =
   6911         TLI.getTargetData()
   6912             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
   6913 
   6914       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
   6915         return SDValue();
   6916 
   6917       Align = NewAlign;
   6918     }
   6919 
   6920     SDValue NewPtr = LN0->getBasePtr();
   6921     unsigned PtrOff = 0;
   6922 
   6923     if (Elt) {
   6924       PtrOff = LVT.getSizeInBits() * Elt / 8;
   6925       EVT PtrType = NewPtr.getValueType();
   6926       if (TLI.isBigEndian())
   6927         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
   6928       NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
   6929                            DAG.getConstant(PtrOff, PtrType));
   6930     }
   6931 
   6932     return DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
   6933                        LN0->getPointerInfo().getWithOffset(PtrOff),
   6934                        LN0->isVolatile(), LN0->isNonTemporal(), Align);
   6935   }
   6936 
   6937   return SDValue();
   6938 }
   6939 
   6940 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
   6941   unsigned NumInScalars = N->getNumOperands();
   6942   EVT VT = N->getValueType(0);
   6943 
   6944   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
   6945   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
   6946   // at most two distinct vectors, turn this into a shuffle node.
   6947   SDValue VecIn1, VecIn2;
   6948   for (unsigned i = 0; i != NumInScalars; ++i) {
   6949     // Ignore undef inputs.
   6950     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
   6951 
   6952     // If this input is something other than a EXTRACT_VECTOR_ELT with a
   6953     // constant index, bail out.
   6954     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
   6955         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
   6956       VecIn1 = VecIn2 = SDValue(0, 0);
   6957       break;
   6958     }
   6959 
   6960     // If the input vector type disagrees with the result of the build_vector,
   6961     // we can't make a shuffle.
   6962     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
   6963     if (ExtractedFromVec.getValueType() != VT) {
   6964       VecIn1 = VecIn2 = SDValue(0, 0);
   6965       break;
   6966     }
   6967 
   6968     // Otherwise, remember this.  We allow up to two distinct input vectors.
   6969     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
   6970       continue;
   6971 
   6972     if (VecIn1.getNode() == 0) {
   6973       VecIn1 = ExtractedFromVec;
   6974     } else if (VecIn2.getNode() == 0) {
   6975       VecIn2 = ExtractedFromVec;
   6976     } else {
   6977       // Too many inputs.
   6978       VecIn1 = VecIn2 = SDValue(0, 0);
   6979       break;
   6980     }
   6981   }
   6982 
   6983   // If everything is good, we can make a shuffle operation.
   6984   if (VecIn1.getNode()) {
   6985     SmallVector<int, 8> Mask;
   6986     for (unsigned i = 0; i != NumInScalars; ++i) {
   6987       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
   6988         Mask.push_back(-1);
   6989         continue;
   6990       }
   6991 
   6992       // If extracting from the first vector, just use the index directly.
   6993       SDValue Extract = N->getOperand(i);
   6994       SDValue ExtVal = Extract.getOperand(1);
   6995       if (Extract.getOperand(0) == VecIn1) {
   6996         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
   6997         if (ExtIndex > VT.getVectorNumElements())
   6998           return SDValue();
   6999 
   7000         Mask.push_back(ExtIndex);
   7001         continue;
   7002       }
   7003 
   7004       // Otherwise, use InIdx + VecSize
   7005       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
   7006       Mask.push_back(Idx+NumInScalars);
   7007     }
   7008 
   7009     // Add count and size info.
   7010     if (!isTypeLegal(VT))
   7011       return SDValue();
   7012 
   7013     // Return the new VECTOR_SHUFFLE node.
   7014     SDValue Ops[2];
   7015     Ops[0] = VecIn1;
   7016     Ops[1] = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
   7017     return DAG.getVectorShuffle(VT, N->getDebugLoc(), Ops[0], Ops[1], &Mask[0]);
   7018   }
   7019 
   7020   return SDValue();
   7021 }
   7022 
   7023 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
   7024   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
   7025   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
   7026   // inputs come from at most two distinct vectors, turn this into a shuffle
   7027   // node.
   7028 
   7029   // If we only have one input vector, we don't need to do any concatenation.
   7030   if (N->getNumOperands() == 1)
   7031     return N->getOperand(0);
   7032 
   7033   return SDValue();
   7034 }
   7035 
   7036 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
   7037   EVT NVT = N->getValueType(0);
   7038   SDValue V = N->getOperand(0);
   7039 
   7040   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
   7041     // Handle only simple case where vector being inserted and vector
   7042     // being extracted are of same type, and are half size of larger vectors.
   7043     EVT BigVT = V->getOperand(0).getValueType();
   7044     EVT SmallVT = V->getOperand(1).getValueType();
   7045     if (NVT != SmallVT || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
   7046       return SDValue();
   7047 
   7048     // Combine:
   7049     //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
   7050     // Into:
   7051     //    indicies are equal => V1
   7052     //    otherwise => (extract_subvec V1, ExtIdx)
   7053     //
   7054     SDValue InsIdx = N->getOperand(1);
   7055     SDValue ExtIdx = V->getOperand(2);
   7056 
   7057     if (InsIdx == ExtIdx)
   7058       return V->getOperand(1);
   7059     return DAG.getNode(ISD::EXTRACT_SUBVECTOR, N->getDebugLoc(), NVT,
   7060                        V->getOperand(0), N->getOperand(1));
   7061   }
   7062 
   7063   return SDValue();
   7064 }
   7065 
   7066 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
   7067   EVT VT = N->getValueType(0);
   7068   unsigned NumElts = VT.getVectorNumElements();
   7069 
   7070   SDValue N0 = N->getOperand(0);
   7071 
   7072   assert(N0.getValueType().getVectorNumElements() == NumElts &&
   7073         "Vector shuffle must be normalized in DAG");
   7074 
   7075   // FIXME: implement canonicalizations from DAG.getVectorShuffle()
   7076 
   7077   // If it is a splat, check if the argument vector is another splat or a
   7078   // build_vector with all scalar elements the same.
   7079   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
   7080   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
   7081     SDNode *V = N0.getNode();
   7082 
   7083     // If this is a bit convert that changes the element type of the vector but
   7084     // not the number of vector elements, look through it.  Be careful not to
   7085     // look though conversions that change things like v4f32 to v2f64.
   7086     if (V->getOpcode() == ISD::BITCAST) {
   7087       SDValue ConvInput = V->getOperand(0);
   7088       if (ConvInput.getValueType().isVector() &&
   7089           ConvInput.getValueType().getVectorNumElements() == NumElts)
   7090         V = ConvInput.getNode();
   7091     }
   7092 
   7093     if (V->getOpcode() == ISD::BUILD_VECTOR) {
   7094       assert(V->getNumOperands() == NumElts &&
   7095              "BUILD_VECTOR has wrong number of operands");
   7096       SDValue Base;
   7097       bool AllSame = true;
   7098       for (unsigned i = 0; i != NumElts; ++i) {
   7099         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
   7100           Base = V->getOperand(i);
   7101           break;
   7102         }
   7103       }
   7104       // Splat of <u, u, u, u>, return <u, u, u, u>
   7105       if (!Base.getNode())
   7106         return N0;
   7107       for (unsigned i = 0; i != NumElts; ++i) {
   7108         if (V->getOperand(i) != Base) {
   7109           AllSame = false;
   7110           break;
   7111         }
   7112       }
   7113       // Splat of <x, x, x, x>, return <x, x, x, x>
   7114       if (AllSame)
   7115         return N0;
   7116     }
   7117   }
   7118   return SDValue();
   7119 }
   7120 
   7121 SDValue DAGCombiner::visitMEMBARRIER(SDNode* N) {
   7122   if (!TLI.getShouldFoldAtomicFences())
   7123     return SDValue();
   7124 
   7125   SDValue atomic = N->getOperand(0);
   7126   switch (atomic.getOpcode()) {
   7127     case ISD::ATOMIC_CMP_SWAP:
   7128     case ISD::ATOMIC_SWAP:
   7129     case ISD::ATOMIC_LOAD_ADD:
   7130     case ISD::ATOMIC_LOAD_SUB:
   7131     case ISD::ATOMIC_LOAD_AND:
   7132     case ISD::ATOMIC_LOAD_OR:
   7133     case ISD::ATOMIC_LOAD_XOR:
   7134     case ISD::ATOMIC_LOAD_NAND:
   7135     case ISD::ATOMIC_LOAD_MIN:
   7136     case ISD::ATOMIC_LOAD_MAX:
   7137     case ISD::ATOMIC_LOAD_UMIN:
   7138     case ISD::ATOMIC_LOAD_UMAX:
   7139       break;
   7140     default:
   7141       return SDValue();
   7142   }
   7143 
   7144   SDValue fence = atomic.getOperand(0);
   7145   if (fence.getOpcode() != ISD::MEMBARRIER)
   7146     return SDValue();
   7147 
   7148   switch (atomic.getOpcode()) {
   7149     case ISD::ATOMIC_CMP_SWAP:
   7150       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
   7151                                     fence.getOperand(0),
   7152                                     atomic.getOperand(1), atomic.getOperand(2),
   7153                                     atomic.getOperand(3)), atomic.getResNo());
   7154     case ISD::ATOMIC_SWAP:
   7155     case ISD::ATOMIC_LOAD_ADD:
   7156     case ISD::ATOMIC_LOAD_SUB:
   7157     case ISD::ATOMIC_LOAD_AND:
   7158     case ISD::ATOMIC_LOAD_OR:
   7159     case ISD::ATOMIC_LOAD_XOR:
   7160     case ISD::ATOMIC_LOAD_NAND:
   7161     case ISD::ATOMIC_LOAD_MIN:
   7162     case ISD::ATOMIC_LOAD_MAX:
   7163     case ISD::ATOMIC_LOAD_UMIN:
   7164     case ISD::ATOMIC_LOAD_UMAX:
   7165       return SDValue(DAG.UpdateNodeOperands(atomic.getNode(),
   7166                                     fence.getOperand(0),
   7167                                     atomic.getOperand(1), atomic.getOperand(2)),
   7168                      atomic.getResNo());
   7169     default:
   7170       return SDValue();
   7171   }
   7172 }
   7173 
   7174 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
   7175 /// an AND to a vector_shuffle with the destination vector and a zero vector.
   7176 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
   7177 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
   7178 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
   7179   EVT VT = N->getValueType(0);
   7180   DebugLoc dl = N->getDebugLoc();
   7181   SDValue LHS = N->getOperand(0);
   7182   SDValue RHS = N->getOperand(1);
   7183   if (N->getOpcode() == ISD::AND) {
   7184     if (RHS.getOpcode() == ISD::BITCAST)
   7185       RHS = RHS.getOperand(0);
   7186     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
   7187       SmallVector<int, 8> Indices;
   7188       unsigned NumElts = RHS.getNumOperands();
   7189       for (unsigned i = 0; i != NumElts; ++i) {
   7190         SDValue Elt = RHS.getOperand(i);
   7191         if (!isa<ConstantSDNode>(Elt))
   7192           return SDValue();
   7193         else if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
   7194           Indices.push_back(i);
   7195         else if (cast<ConstantSDNode>(Elt)->isNullValue())
   7196           Indices.push_back(NumElts);
   7197         else
   7198           return SDValue();
   7199       }
   7200 
   7201       // Let's see if the target supports this vector_shuffle.
   7202       EVT RVT = RHS.getValueType();
   7203       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
   7204         return SDValue();
   7205 
   7206       // Return the new VECTOR_SHUFFLE node.
   7207       EVT EltVT = RVT.getVectorElementType();
   7208       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
   7209                                      DAG.getConstant(0, EltVT));
   7210       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
   7211                                  RVT, &ZeroOps[0], ZeroOps.size());
   7212       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
   7213       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
   7214       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
   7215     }
   7216   }
   7217 
   7218   return SDValue();
   7219 }
   7220 
   7221 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
   7222 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
   7223   // After legalize, the target may be depending on adds and other
   7224   // binary ops to provide legal ways to construct constants or other
   7225   // things. Simplifying them may result in a loss of legality.
   7226   if (LegalOperations) return SDValue();
   7227 
   7228   assert(N->getValueType(0).isVector() &&
   7229          "SimplifyVBinOp only works on vectors!");
   7230 
   7231   SDValue LHS = N->getOperand(0);
   7232   SDValue RHS = N->getOperand(1);
   7233   SDValue Shuffle = XformToShuffleWithZero(N);
   7234   if (Shuffle.getNode()) return Shuffle;
   7235 
   7236   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
   7237   // this operation.
   7238   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
   7239       RHS.getOpcode() == ISD::BUILD_VECTOR) {
   7240     SmallVector<SDValue, 8> Ops;
   7241     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
   7242       SDValue LHSOp = LHS.getOperand(i);
   7243       SDValue RHSOp = RHS.getOperand(i);
   7244       // If these two elements can't be folded, bail out.
   7245       if ((LHSOp.getOpcode() != ISD::UNDEF &&
   7246            LHSOp.getOpcode() != ISD::Constant &&
   7247            LHSOp.getOpcode() != ISD::ConstantFP) ||
   7248           (RHSOp.getOpcode() != ISD::UNDEF &&
   7249            RHSOp.getOpcode() != ISD::Constant &&
   7250            RHSOp.getOpcode() != ISD::ConstantFP))
   7251         break;
   7252 
   7253       // Can't fold divide by zero.
   7254       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
   7255           N->getOpcode() == ISD::FDIV) {
   7256         if ((RHSOp.getOpcode() == ISD::Constant &&
   7257              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
   7258             (RHSOp.getOpcode() == ISD::ConstantFP &&
   7259              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
   7260           break;
   7261       }
   7262 
   7263       EVT VT = LHSOp.getValueType();
   7264       EVT RVT = RHSOp.getValueType();
   7265       if (RVT != VT) {
   7266         // Integer BUILD_VECTOR operands may have types larger than the element
   7267         // size (e.g., when the element type is not legal).  Prior to type
   7268         // legalization, the types may not match between the two BUILD_VECTORS.
   7269         // Truncate one of the operands to make them match.
   7270         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
   7271           RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
   7272         } else {
   7273           LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
   7274           VT = RVT;
   7275         }
   7276       }
   7277       SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
   7278                                    LHSOp, RHSOp);
   7279       if (FoldOp.getOpcode() != ISD::UNDEF &&
   7280           FoldOp.getOpcode() != ISD::Constant &&
   7281           FoldOp.getOpcode() != ISD::ConstantFP)
   7282         break;
   7283       Ops.push_back(FoldOp);
   7284       AddToWorkList(FoldOp.getNode());
   7285     }
   7286 
   7287     if (Ops.size() == LHS.getNumOperands())
   7288       return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
   7289                          LHS.getValueType(), &Ops[0], Ops.size());
   7290   }
   7291 
   7292   return SDValue();
   7293 }
   7294 
   7295 SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
   7296                                     SDValue N1, SDValue N2){
   7297   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
   7298 
   7299   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
   7300                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
   7301 
   7302   // If we got a simplified select_cc node back from SimplifySelectCC, then
   7303   // break it down into a new SETCC node, and a new SELECT node, and then return
   7304   // the SELECT node, since we were called with a SELECT node.
   7305   if (SCC.getNode()) {
   7306     // Check to see if we got a select_cc back (to turn into setcc/select).
   7307     // Otherwise, just return whatever node we got back, like fabs.
   7308     if (SCC.getOpcode() == ISD::SELECT_CC) {
   7309       SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
   7310                                   N0.getValueType(),
   7311                                   SCC.getOperand(0), SCC.getOperand(1),
   7312                                   SCC.getOperand(4));
   7313       AddToWorkList(SETCC.getNode());
   7314       return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
   7315                          SCC.getOperand(2), SCC.getOperand(3), SETCC);
   7316     }
   7317 
   7318     return SCC;
   7319   }
   7320   return SDValue();
   7321 }
   7322 
   7323 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
   7324 /// are the two values being selected between, see if we can simplify the
   7325 /// select.  Callers of this should assume that TheSelect is deleted if this
   7326 /// returns true.  As such, they should return the appropriate thing (e.g. the
   7327 /// node) back to the top-level of the DAG combiner loop to avoid it being
   7328 /// looked at.
   7329 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
   7330                                     SDValue RHS) {
   7331 
   7332   // Cannot simplify select with vector condition
   7333   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
   7334 
   7335   // If this is a select from two identical things, try to pull the operation
   7336   // through the select.
   7337   if (LHS.getOpcode() != RHS.getOpcode() ||
   7338       !LHS.hasOneUse() || !RHS.hasOneUse())
   7339     return false;
   7340 
   7341   // If this is a load and the token chain is identical, replace the select
   7342   // of two loads with a load through a select of the address to load from.
   7343   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
   7344   // constants have been dropped into the constant pool.
   7345   if (LHS.getOpcode() == ISD::LOAD) {
   7346     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
   7347     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
   7348 
   7349     // Token chains must be identical.
   7350     if (LHS.getOperand(0) != RHS.getOperand(0) ||
   7351         // Do not let this transformation reduce the number of volatile loads.
   7352         LLD->isVolatile() || RLD->isVolatile() ||
   7353         // If this is an EXTLOAD, the VT's must match.
   7354         LLD->getMemoryVT() != RLD->getMemoryVT() ||
   7355         // If this is an EXTLOAD, the kind of extension must match.
   7356         (LLD->getExtensionType() != RLD->getExtensionType() &&
   7357          // The only exception is if one of the extensions is anyext.
   7358          LLD->getExtensionType() != ISD::EXTLOAD &&
   7359          RLD->getExtensionType() != ISD::EXTLOAD) ||
   7360         // FIXME: this discards src value information.  This is
   7361         // over-conservative. It would be beneficial to be able to remember
   7362         // both potential memory locations.  Since we are discarding
   7363         // src value info, don't do the transformation if the memory
   7364         // locations are not in the default address space.
   7365         LLD->getPointerInfo().getAddrSpace() != 0 ||
   7366         RLD->getPointerInfo().getAddrSpace() != 0)
   7367       return false;
   7368 
   7369     // Check that the select condition doesn't reach either load.  If so,
   7370     // folding this will induce a cycle into the DAG.  If not, this is safe to
   7371     // xform, so create a select of the addresses.
   7372     SDValue Addr;
   7373     if (TheSelect->getOpcode() == ISD::SELECT) {
   7374       SDNode *CondNode = TheSelect->getOperand(0).getNode();
   7375       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
   7376           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
   7377         return false;
   7378       Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
   7379                          LLD->getBasePtr().getValueType(),
   7380                          TheSelect->getOperand(0), LLD->getBasePtr(),
   7381                          RLD->getBasePtr());
   7382     } else {  // Otherwise SELECT_CC
   7383       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
   7384       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
   7385 
   7386       if ((LLD->hasAnyUseOfValue(1) &&
   7387            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
   7388           (LLD->hasAnyUseOfValue(1) &&
   7389            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))))
   7390         return false;
   7391 
   7392       Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
   7393                          LLD->getBasePtr().getValueType(),
   7394                          TheSelect->getOperand(0),
   7395                          TheSelect->getOperand(1),
   7396                          LLD->getBasePtr(), RLD->getBasePtr(),
   7397                          TheSelect->getOperand(4));
   7398     }
   7399 
   7400     SDValue Load;
   7401     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
   7402       Load = DAG.getLoad(TheSelect->getValueType(0),
   7403                          TheSelect->getDebugLoc(),
   7404                          // FIXME: Discards pointer info.
   7405                          LLD->getChain(), Addr, MachinePointerInfo(),
   7406                          LLD->isVolatile(), LLD->isNonTemporal(),
   7407                          LLD->getAlignment());
   7408     } else {
   7409       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
   7410                             RLD->getExtensionType() : LLD->getExtensionType(),
   7411                             TheSelect->getDebugLoc(),
   7412                             TheSelect->getValueType(0),
   7413                             // FIXME: Discards pointer info.
   7414                             LLD->getChain(), Addr, MachinePointerInfo(),
   7415                             LLD->getMemoryVT(), LLD->isVolatile(),
   7416                             LLD->isNonTemporal(), LLD->getAlignment());
   7417     }
   7418 
   7419     // Users of the select now use the result of the load.
   7420     CombineTo(TheSelect, Load);
   7421 
   7422     // Users of the old loads now use the new load's chain.  We know the
   7423     // old-load value is dead now.
   7424     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
   7425     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
   7426     return true;
   7427   }
   7428 
   7429   return false;
   7430 }
   7431 
   7432 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
   7433 /// where 'cond' is the comparison specified by CC.
   7434 SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
   7435                                       SDValue N2, SDValue N3,
   7436                                       ISD::CondCode CC, bool NotExtCompare) {
   7437   // (x ? y : y) -> y.
   7438   if (N2 == N3) return N2;
   7439 
   7440   EVT VT = N2.getValueType();
   7441   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
   7442   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
   7443   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
   7444 
   7445   // Determine if the condition we're dealing with is constant
   7446   SDValue SCC = SimplifySetCC(TLI.getSetCCResultType(N0.getValueType()),
   7447                               N0, N1, CC, DL, false);
   7448   if (SCC.getNode()) AddToWorkList(SCC.getNode());
   7449   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
   7450 
   7451   // fold select_cc true, x, y -> x
   7452   if (SCCC && !SCCC->isNullValue())
   7453     return N2;
   7454   // fold select_cc false, x, y -> y
   7455   if (SCCC && SCCC->isNullValue())
   7456     return N3;
   7457 
   7458   // Check to see if we can simplify the select into an fabs node
   7459   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
   7460     // Allow either -0.0 or 0.0
   7461     if (CFP->getValueAPF().isZero()) {
   7462       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
   7463       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
   7464           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
   7465           N2 == N3.getOperand(0))
   7466         return DAG.getNode(ISD::FABS, DL, VT, N0);
   7467 
   7468       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
   7469       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
   7470           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
   7471           N2.getOperand(0) == N3)
   7472         return DAG.getNode(ISD::FABS, DL, VT, N3);
   7473     }
   7474   }
   7475 
   7476   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
   7477   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
   7478   // in it.  This is a win when the constant is not otherwise available because
   7479   // it replaces two constant pool loads with one.  We only do this if the FP
   7480   // type is known to be legal, because if it isn't, then we are before legalize
   7481   // types an we want the other legalization to happen first (e.g. to avoid
   7482   // messing with soft float) and if the ConstantFP is not legal, because if
   7483   // it is legal, we may not need to store the FP constant in a constant pool.
   7484   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
   7485     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
   7486       if (TLI.isTypeLegal(N2.getValueType()) &&
   7487           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
   7488            TargetLowering::Legal) &&
   7489           // If both constants have multiple uses, then we won't need to do an
   7490           // extra load, they are likely around in registers for other users.
   7491           (TV->hasOneUse() || FV->hasOneUse())) {
   7492         Constant *Elts[] = {
   7493           const_cast<ConstantFP*>(FV->getConstantFPValue()),
   7494           const_cast<ConstantFP*>(TV->getConstantFPValue())
   7495         };
   7496         Type *FPTy = Elts[0]->getType();
   7497         const TargetData &TD = *TLI.getTargetData();
   7498 
   7499         // Create a ConstantArray of the two constants.
   7500         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
   7501         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
   7502                                             TD.getPrefTypeAlignment(FPTy));
   7503         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
   7504 
   7505         // Get the offsets to the 0 and 1 element of the array so that we can
   7506         // select between them.
   7507         SDValue Zero = DAG.getIntPtrConstant(0);
   7508         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
   7509         SDValue One = DAG.getIntPtrConstant(EltSize);
   7510 
   7511         SDValue Cond = DAG.getSetCC(DL,
   7512                                     TLI.getSetCCResultType(N0.getValueType()),
   7513                                     N0, N1, CC);
   7514         AddToWorkList(Cond.getNode());
   7515         SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
   7516                                         Cond, One, Zero);
   7517         AddToWorkList(CstOffset.getNode());
   7518         CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
   7519                             CstOffset);
   7520         AddToWorkList(CPIdx.getNode());
   7521         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
   7522                            MachinePointerInfo::getConstantPool(), false,
   7523                            false, Alignment);
   7524 
   7525       }
   7526     }
   7527 
   7528   // Check to see if we can perform the "gzip trick", transforming
   7529   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
   7530   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
   7531       N0.getValueType().isInteger() &&
   7532       N2.getValueType().isInteger() &&
   7533       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
   7534        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
   7535     EVT XType = N0.getValueType();
   7536     EVT AType = N2.getValueType();
   7537     if (XType.bitsGE(AType)) {
   7538       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
   7539       // single-bit constant.
   7540       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
   7541         unsigned ShCtV = N2C->getAPIntValue().logBase2();
   7542         ShCtV = XType.getSizeInBits()-ShCtV-1;
   7543         SDValue ShCt = DAG.getConstant(ShCtV,
   7544                                        getShiftAmountTy(N0.getValueType()));
   7545         SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
   7546                                     XType, N0, ShCt);
   7547         AddToWorkList(Shift.getNode());
   7548 
   7549         if (XType.bitsGT(AType)) {
   7550           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
   7551           AddToWorkList(Shift.getNode());
   7552         }
   7553 
   7554         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
   7555       }
   7556 
   7557       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
   7558                                   XType, N0,
   7559                                   DAG.getConstant(XType.getSizeInBits()-1,
   7560                                          getShiftAmountTy(N0.getValueType())));
   7561       AddToWorkList(Shift.getNode());
   7562 
   7563       if (XType.bitsGT(AType)) {
   7564         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
   7565         AddToWorkList(Shift.getNode());
   7566       }
   7567 
   7568       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
   7569     }
   7570   }
   7571 
   7572   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
   7573   // where y is has a single bit set.
   7574   // A plaintext description would be, we can turn the SELECT_CC into an AND
   7575   // when the condition can be materialized as an all-ones register.  Any
   7576   // single bit-test can be materialized as an all-ones register with
   7577   // shift-left and shift-right-arith.
   7578   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
   7579       N0->getValueType(0) == VT &&
   7580       N1C && N1C->isNullValue() &&
   7581       N2C && N2C->isNullValue()) {
   7582     SDValue AndLHS = N0->getOperand(0);
   7583     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
   7584     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
   7585       // Shift the tested bit over the sign bit.
   7586       APInt AndMask = ConstAndRHS->getAPIntValue();
   7587       SDValue ShlAmt =
   7588         DAG.getConstant(AndMask.countLeadingZeros(),
   7589                         getShiftAmountTy(AndLHS.getValueType()));
   7590       SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
   7591 
   7592       // Now arithmetic right shift it all the way over, so the result is either
   7593       // all-ones, or zero.
   7594       SDValue ShrAmt =
   7595         DAG.getConstant(AndMask.getBitWidth()-1,
   7596                         getShiftAmountTy(Shl.getValueType()));
   7597       SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
   7598 
   7599       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
   7600     }
   7601   }
   7602 
   7603   // fold select C, 16, 0 -> shl C, 4
   7604   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
   7605     TLI.getBooleanContents(N0.getValueType().isVector()) ==
   7606       TargetLowering::ZeroOrOneBooleanContent) {
   7607 
   7608     // If the caller doesn't want us to simplify this into a zext of a compare,
   7609     // don't do it.
   7610     if (NotExtCompare && N2C->getAPIntValue() == 1)
   7611       return SDValue();
   7612 
   7613     // Get a SetCC of the condition
   7614     // FIXME: Should probably make sure that setcc is legal if we ever have a
   7615     // target where it isn't.
   7616     SDValue Temp, SCC;
   7617     // cast from setcc result type to select result type
   7618     if (LegalTypes) {
   7619       SCC  = DAG.getSetCC(DL, TLI.getSetCCResultType(N0.getValueType()),
   7620                           N0, N1, CC);
   7621       if (N2.getValueType().bitsLT(SCC.getValueType()))
   7622         Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(), N2.getValueType());
   7623       else
   7624         Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
   7625                            N2.getValueType(), SCC);
   7626     } else {
   7627       SCC  = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
   7628       Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
   7629                          N2.getValueType(), SCC);
   7630     }
   7631 
   7632     AddToWorkList(SCC.getNode());
   7633     AddToWorkList(Temp.getNode());
   7634 
   7635     if (N2C->getAPIntValue() == 1)
   7636       return Temp;
   7637 
   7638     // shl setcc result by log2 n2c
   7639     return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
   7640                        DAG.getConstant(N2C->getAPIntValue().logBase2(),
   7641                                        getShiftAmountTy(Temp.getValueType())));
   7642   }
   7643 
   7644   // Check to see if this is the equivalent of setcc
   7645   // FIXME: Turn all of these into setcc if setcc if setcc is legal
   7646   // otherwise, go ahead with the folds.
   7647   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
   7648     EVT XType = N0.getValueType();
   7649     if (!LegalOperations ||
   7650         TLI.isOperationLegal(ISD::SETCC, TLI.getSetCCResultType(XType))) {
   7651       SDValue Res = DAG.getSetCC(DL, TLI.getSetCCResultType(XType), N0, N1, CC);
   7652       if (Res.getValueType() != VT)
   7653         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
   7654       return Res;
   7655     }
   7656 
   7657     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
   7658     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
   7659         (!LegalOperations ||
   7660          TLI.isOperationLegal(ISD::CTLZ, XType))) {
   7661       SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
   7662       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
   7663                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
   7664                                        getShiftAmountTy(Ctlz.getValueType())));
   7665     }
   7666     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
   7667     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
   7668       SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
   7669                                   XType, DAG.getConstant(0, XType), N0);
   7670       SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
   7671       return DAG.getNode(ISD::SRL, DL, XType,
   7672                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
   7673                          DAG.getConstant(XType.getSizeInBits()-1,
   7674                                          getShiftAmountTy(XType)));
   7675     }
   7676     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
   7677     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
   7678       SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
   7679                                  DAG.getConstant(XType.getSizeInBits()-1,
   7680                                          getShiftAmountTy(N0.getValueType())));
   7681       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
   7682     }
   7683   }
   7684 
   7685   // Check to see if this is an integer abs.
   7686   // select_cc setg[te] X,  0,  X, -X ->
   7687   // select_cc setgt    X, -1,  X, -X ->
   7688   // select_cc setl[te] X,  0, -X,  X ->
   7689   // select_cc setlt    X,  1, -X,  X ->
   7690   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
   7691   if (N1C) {
   7692     ConstantSDNode *SubC = NULL;
   7693     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
   7694          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
   7695         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
   7696       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
   7697     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
   7698               (N1C->isOne() && CC == ISD::SETLT)) &&
   7699              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
   7700       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
   7701 
   7702     EVT XType = N0.getValueType();
   7703     if (SubC && SubC->isNullValue() && XType.isInteger()) {
   7704       SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
   7705                                   N0,
   7706                                   DAG.getConstant(XType.getSizeInBits()-1,
   7707                                          getShiftAmountTy(N0.getValueType())));
   7708       SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
   7709                                 XType, N0, Shift);
   7710       AddToWorkList(Shift.getNode());
   7711       AddToWorkList(Add.getNode());
   7712       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
   7713     }
   7714   }
   7715 
   7716   return SDValue();
   7717 }
   7718 
   7719 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
   7720 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
   7721                                    SDValue N1, ISD::CondCode Cond,
   7722                                    DebugLoc DL, bool foldBooleans) {
   7723   TargetLowering::DAGCombinerInfo
   7724     DagCombineInfo(DAG, !LegalTypes, !LegalOperations, false, this);
   7725   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
   7726 }
   7727 
   7728 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
   7729 /// return a DAG expression to select that will generate the same value by
   7730 /// multiplying by a magic number.  See:
   7731 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
   7732 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
   7733   std::vector<SDNode*> Built;
   7734   SDValue S = TLI.BuildSDIV(N, DAG, &Built);
   7735 
   7736   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
   7737        ii != ee; ++ii)
   7738     AddToWorkList(*ii);
   7739   return S;
   7740 }
   7741 
   7742 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
   7743 /// return a DAG expression to select that will generate the same value by
   7744 /// multiplying by a magic number.  See:
   7745 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
   7746 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
   7747   std::vector<SDNode*> Built;
   7748   SDValue S = TLI.BuildUDIV(N, DAG, &Built);
   7749 
   7750   for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
   7751        ii != ee; ++ii)
   7752     AddToWorkList(*ii);
   7753   return S;
   7754 }
   7755 
   7756 /// FindBaseOffset - Return true if base is a frame index, which is known not
   7757 // to alias with anything but itself.  Provides base object and offset as
   7758 // results.
   7759 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
   7760                            const GlobalValue *&GV, void *&CV) {
   7761   // Assume it is a primitive operation.
   7762   Base = Ptr; Offset = 0; GV = 0; CV = 0;
   7763 
   7764   // If it's an adding a simple constant then integrate the offset.
   7765   if (Base.getOpcode() == ISD::ADD) {
   7766     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
   7767       Base = Base.getOperand(0);
   7768       Offset += C->getZExtValue();
   7769     }
   7770   }
   7771 
   7772   // Return the underlying GlobalValue, and update the Offset.  Return false
   7773   // for GlobalAddressSDNode since the same GlobalAddress may be represented
   7774   // by multiple nodes with different offsets.
   7775   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
   7776     GV = G->getGlobal();
   7777     Offset += G->getOffset();
   7778     return false;
   7779   }
   7780 
   7781   // Return the underlying Constant value, and update the Offset.  Return false
   7782   // for ConstantSDNodes since the same constant pool entry may be represented
   7783   // by multiple nodes with different offsets.
   7784   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
   7785     CV = C->isMachineConstantPoolEntry() ? (void *)C->getMachineCPVal()
   7786                                          : (void *)C->getConstVal();
   7787     Offset += C->getOffset();
   7788     return false;
   7789   }
   7790   // If it's any of the following then it can't alias with anything but itself.
   7791   return isa<FrameIndexSDNode>(Base);
   7792 }
   7793 
   7794 /// isAlias - Return true if there is any possibility that the two addresses
   7795 /// overlap.
   7796 bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
   7797                           const Value *SrcValue1, int SrcValueOffset1,
   7798                           unsigned SrcValueAlign1,
   7799                           const MDNode *TBAAInfo1,
   7800                           SDValue Ptr2, int64_t Size2,
   7801                           const Value *SrcValue2, int SrcValueOffset2,
   7802                           unsigned SrcValueAlign2,
   7803                           const MDNode *TBAAInfo2) const {
   7804   // If they are the same then they must be aliases.
   7805   if (Ptr1 == Ptr2) return true;
   7806 
   7807   // Gather base node and offset information.
   7808   SDValue Base1, Base2;
   7809   int64_t Offset1, Offset2;
   7810   const GlobalValue *GV1, *GV2;
   7811   void *CV1, *CV2;
   7812   bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
   7813   bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
   7814 
   7815   // If they have a same base address then check to see if they overlap.
   7816   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
   7817     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
   7818 
   7819   // It is possible for different frame indices to alias each other, mostly
   7820   // when tail call optimization reuses return address slots for arguments.
   7821   // To catch this case, look up the actual index of frame indices to compute
   7822   // the real alias relationship.
   7823   if (isFrameIndex1 && isFrameIndex2) {
   7824     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
   7825     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
   7826     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
   7827     return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
   7828   }
   7829 
   7830   // Otherwise, if we know what the bases are, and they aren't identical, then
   7831   // we know they cannot alias.
   7832   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
   7833     return false;
   7834 
   7835   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
   7836   // compared to the size and offset of the access, we may be able to prove they
   7837   // do not alias.  This check is conservative for now to catch cases created by
   7838   // splitting vector types.
   7839   if ((SrcValueAlign1 == SrcValueAlign2) &&
   7840       (SrcValueOffset1 != SrcValueOffset2) &&
   7841       (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
   7842     int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
   7843     int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
   7844 
   7845     // There is no overlap between these relatively aligned accesses of similar
   7846     // size, return no alias.
   7847     if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
   7848       return false;
   7849   }
   7850 
   7851   if (CombinerGlobalAA) {
   7852     // Use alias analysis information.
   7853     int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
   7854     int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
   7855     int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
   7856     AliasAnalysis::AliasResult AAResult =
   7857       AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
   7858                AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
   7859     if (AAResult == AliasAnalysis::NoAlias)
   7860       return false;
   7861   }
   7862 
   7863   // Otherwise we have to assume they alias.
   7864   return true;
   7865 }
   7866 
   7867 /// FindAliasInfo - Extracts the relevant alias information from the memory
   7868 /// node.  Returns true if the operand was a load.
   7869 bool DAGCombiner::FindAliasInfo(SDNode *N,
   7870                         SDValue &Ptr, int64_t &Size,
   7871                         const Value *&SrcValue,
   7872                         int &SrcValueOffset,
   7873                         unsigned &SrcValueAlign,
   7874                         const MDNode *&TBAAInfo) const {
   7875   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
   7876     Ptr = LD->getBasePtr();
   7877     Size = LD->getMemoryVT().getSizeInBits() >> 3;
   7878     SrcValue = LD->getSrcValue();
   7879     SrcValueOffset = LD->getSrcValueOffset();
   7880     SrcValueAlign = LD->getOriginalAlignment();
   7881     TBAAInfo = LD->getTBAAInfo();
   7882     return true;
   7883   }
   7884   if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
   7885     Ptr = ST->getBasePtr();
   7886     Size = ST->getMemoryVT().getSizeInBits() >> 3;
   7887     SrcValue = ST->getSrcValue();
   7888     SrcValueOffset = ST->getSrcValueOffset();
   7889     SrcValueAlign = ST->getOriginalAlignment();
   7890     TBAAInfo = ST->getTBAAInfo();
   7891     return false;
   7892   }
   7893   llvm_unreachable("FindAliasInfo expected a memory operand");
   7894 }
   7895 
   7896 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
   7897 /// looking for aliasing nodes and adding them to the Aliases vector.
   7898 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
   7899                                    SmallVector<SDValue, 8> &Aliases) {
   7900   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
   7901   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
   7902 
   7903   // Get alias information for node.
   7904   SDValue Ptr;
   7905   int64_t Size;
   7906   const Value *SrcValue;
   7907   int SrcValueOffset;
   7908   unsigned SrcValueAlign;
   7909   const MDNode *SrcTBAAInfo;
   7910   bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
   7911                               SrcValueAlign, SrcTBAAInfo);
   7912 
   7913   // Starting off.
   7914   Chains.push_back(OriginalChain);
   7915   unsigned Depth = 0;
   7916 
   7917   // Look at each chain and determine if it is an alias.  If so, add it to the
   7918   // aliases list.  If not, then continue up the chain looking for the next
   7919   // candidate.
   7920   while (!Chains.empty()) {
   7921     SDValue Chain = Chains.back();
   7922     Chains.pop_back();
   7923 
   7924     // For TokenFactor nodes, look at each operand and only continue up the
   7925     // chain until we find two aliases.  If we've seen two aliases, assume we'll
   7926     // find more and revert to original chain since the xform is unlikely to be
   7927     // profitable.
   7928     //
   7929     // FIXME: The depth check could be made to return the last non-aliasing
   7930     // chain we found before we hit a tokenfactor rather than the original
   7931     // chain.
   7932     if (Depth > 6 || Aliases.size() == 2) {
   7933       Aliases.clear();
   7934       Aliases.push_back(OriginalChain);
   7935       break;
   7936     }
   7937 
   7938     // Don't bother if we've been before.
   7939     if (!Visited.insert(Chain.getNode()))
   7940       continue;
   7941 
   7942     switch (Chain.getOpcode()) {
   7943     case ISD::EntryToken:
   7944       // Entry token is ideal chain operand, but handled in FindBetterChain.
   7945       break;
   7946 
   7947     case ISD::LOAD:
   7948     case ISD::STORE: {
   7949       // Get alias information for Chain.
   7950       SDValue OpPtr;
   7951       int64_t OpSize;
   7952       const Value *OpSrcValue;
   7953       int OpSrcValueOffset;
   7954       unsigned OpSrcValueAlign;
   7955       const MDNode *OpSrcTBAAInfo;
   7956       bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
   7957                                     OpSrcValue, OpSrcValueOffset,
   7958                                     OpSrcValueAlign,
   7959                                     OpSrcTBAAInfo);
   7960 
   7961       // If chain is alias then stop here.
   7962       if (!(IsLoad && IsOpLoad) &&
   7963           isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
   7964                   SrcTBAAInfo,
   7965                   OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
   7966                   OpSrcValueAlign, OpSrcTBAAInfo)) {
   7967         Aliases.push_back(Chain);
   7968       } else {
   7969         // Look further up the chain.
   7970         Chains.push_back(Chain.getOperand(0));
   7971         ++Depth;
   7972       }
   7973       break;
   7974     }
   7975 
   7976     case ISD::TokenFactor:
   7977       // We have to check each of the operands of the token factor for "small"
   7978       // token factors, so we queue them up.  Adding the operands to the queue
   7979       // (stack) in reverse order maintains the original order and increases the
   7980       // likelihood that getNode will find a matching token factor (CSE.)
   7981       if (Chain.getNumOperands() > 16) {
   7982         Aliases.push_back(Chain);
   7983         break;
   7984       }
   7985       for (unsigned n = Chain.getNumOperands(); n;)
   7986         Chains.push_back(Chain.getOperand(--n));
   7987       ++Depth;
   7988       break;
   7989 
   7990     default:
   7991       // For all other instructions we will just have to take what we can get.
   7992       Aliases.push_back(Chain);
   7993       break;
   7994     }
   7995   }
   7996 }
   7997 
   7998 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
   7999 /// for a better chain (aliasing node.)
   8000 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
   8001   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
   8002 
   8003   // Accumulate all the aliases to this node.
   8004   GatherAllAliases(N, OldChain, Aliases);
   8005 
   8006   // If no operands then chain to entry token.
   8007   if (Aliases.size() == 0)
   8008     return DAG.getEntryNode();
   8009 
   8010   // If a single operand then chain to it.  We don't need to revisit it.
   8011   if (Aliases.size() == 1)
   8012     return Aliases[0];
   8013 
   8014   // Construct a custom tailored token factor.
   8015   return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
   8016                      &Aliases[0], Aliases.size());
   8017 }
   8018 
   8019 // SelectionDAG::Combine - This is the entry point for the file.
   8020 //
   8021 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
   8022                            CodeGenOpt::Level OptLevel) {
   8023   /// run - This is the main entry point to this class.
   8024   ///
   8025   DAGCombiner(*this, AA, OptLevel).Run(Level);
   8026 }
   8027