LLVM API Documentation

DAGCombiner.cpp
Go to the documentation of this file.
00001 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
00011 // both before and after the DAG is legalized.
00012 //
00013 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
00014 // primarily intended to handle simplification opportunities that are implicit
00015 // in the LLVM IR and exposed by the various codegen lowering phases.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/CodeGen/SelectionDAG.h"
00020 #include "llvm/ADT/SmallPtrSet.h"
00021 #include "llvm/ADT/SetVector.h"
00022 #include "llvm/ADT/Statistic.h"
00023 #include "llvm/Analysis/AliasAnalysis.h"
00024 #include "llvm/CodeGen/MachineFrameInfo.h"
00025 #include "llvm/CodeGen/MachineFunction.h"
00026 #include "llvm/IR/DataLayout.h"
00027 #include "llvm/IR/DerivedTypes.h"
00028 #include "llvm/IR/Function.h"
00029 #include "llvm/IR/LLVMContext.h"
00030 #include "llvm/Support/CommandLine.h"
00031 #include "llvm/Support/Debug.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/MathExtras.h"
00034 #include "llvm/Support/raw_ostream.h"
00035 #include "llvm/Target/TargetLowering.h"
00036 #include "llvm/Target/TargetMachine.h"
00037 #include "llvm/Target/TargetOptions.h"
00038 #include "llvm/Target/TargetRegisterInfo.h"
00039 #include "llvm/Target/TargetSubtargetInfo.h"
00040 #include <algorithm>
00041 using namespace llvm;
00042 
00043 #define DEBUG_TYPE "dagcombine"
00044 
00045 STATISTIC(NodesCombined   , "Number of dag nodes combined");
00046 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
00047 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
00048 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
00049 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
00050 STATISTIC(SlicedLoads, "Number of load sliced");
00051 
00052 namespace {
00053   static cl::opt<bool>
00054     CombinerAA("combiner-alias-analysis", cl::Hidden,
00055                cl::desc("Enable DAG combiner alias-analysis heuristics"));
00056 
00057   static cl::opt<bool>
00058     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
00059                cl::desc("Enable DAG combiner's use of IR alias analysis"));
00060 
00061   static cl::opt<bool>
00062     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
00063                cl::desc("Enable DAG combiner's use of TBAA"));
00064 
00065 #ifndef NDEBUG
00066   static cl::opt<std::string>
00067     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
00068                cl::desc("Only use DAG-combiner alias analysis in this"
00069                         " function"));
00070 #endif
00071 
00072   /// Hidden option to stress test load slicing, i.e., when this option
00073   /// is enabled, load slicing bypasses most of its profitability guards.
00074   static cl::opt<bool>
00075   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
00076                     cl::desc("Bypass the profitability model of load "
00077                              "slicing"),
00078                     cl::init(false));
00079 
00080   static cl::opt<bool>
00081     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
00082                       cl::desc("DAG combiner may split indexing from loads"));
00083 
00084 //------------------------------ DAGCombiner ---------------------------------//
00085 
00086   class DAGCombiner {
00087     SelectionDAG &DAG;
00088     const TargetLowering &TLI;
00089     CombineLevel Level;
00090     CodeGenOpt::Level OptLevel;
00091     bool LegalOperations;
00092     bool LegalTypes;
00093     bool ForCodeSize;
00094 
00095     /// \brief Worklist of all of the nodes that need to be simplified.
00096     ///
00097     /// This must behave as a stack -- new nodes to process are pushed onto the
00098     /// back and when processing we pop off of the back.
00099     ///
00100     /// The worklist will not contain duplicates but may contain null entries
00101     /// due to nodes being deleted from the underlying DAG.
00102     SmallVector<SDNode *, 64> Worklist;
00103 
00104     /// \brief Mapping from an SDNode to its position on the worklist.
00105     ///
00106     /// This is used to find and remove nodes from the worklist (by nulling
00107     /// them) when they are deleted from the underlying DAG. It relies on
00108     /// stable indices of nodes within the worklist.
00109     DenseMap<SDNode *, unsigned> WorklistMap;
00110 
00111     /// \brief Set of nodes which have been combined (at least once).
00112     ///
00113     /// This is used to allow us to reliably add any operands of a DAG node
00114     /// which have not yet been combined to the worklist.
00115     SmallPtrSet<SDNode *, 64> CombinedNodes;
00116 
00117     // AA - Used for DAG load/store alias analysis.
00118     AliasAnalysis &AA;
00119 
00120     /// When an instruction is simplified, add all users of the instruction to
00121     /// the work lists because they might get more simplified now.
00122     void AddUsersToWorklist(SDNode *N) {
00123       for (SDNode *Node : N->uses())
00124         AddToWorklist(Node);
00125     }
00126 
00127     /// Call the node-specific routine that folds each particular type of node.
00128     SDValue visit(SDNode *N);
00129 
00130   public:
00131     /// Add to the worklist making sure its instance is at the back (next to be
00132     /// processed.)
00133     void AddToWorklist(SDNode *N) {
00134       // Skip handle nodes as they can't usefully be combined and confuse the
00135       // zero-use deletion strategy.
00136       if (N->getOpcode() == ISD::HANDLENODE)
00137         return;
00138 
00139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
00140         Worklist.push_back(N);
00141     }
00142 
00143     /// Remove all instances of N from the worklist.
00144     void removeFromWorklist(SDNode *N) {
00145       CombinedNodes.erase(N);
00146 
00147       auto It = WorklistMap.find(N);
00148       if (It == WorklistMap.end())
00149         return; // Not in the worklist.
00150 
00151       // Null out the entry rather than erasing it to avoid a linear operation.
00152       Worklist[It->second] = nullptr;
00153       WorklistMap.erase(It);
00154     }
00155 
00156     void deleteAndRecombine(SDNode *N);
00157     bool recursivelyDeleteUnusedNodes(SDNode *N);
00158 
00159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00160                       bool AddTo = true);
00161 
00162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
00163       return CombineTo(N, &Res, 1, AddTo);
00164     }
00165 
00166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
00167                       bool AddTo = true) {
00168       SDValue To[] = { Res0, Res1 };
00169       return CombineTo(N, To, 2, AddTo);
00170     }
00171 
00172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
00173 
00174   private:
00175 
00176     /// Check the specified integer node value to see if it can be simplified or
00177     /// if things it uses can be simplified by bit propagation.
00178     /// If so, return true.
00179     bool SimplifyDemandedBits(SDValue Op) {
00180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
00181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
00182       return SimplifyDemandedBits(Op, Demanded);
00183     }
00184 
00185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
00186 
00187     bool CombineToPreIndexedLoadStore(SDNode *N);
00188     bool CombineToPostIndexedLoadStore(SDNode *N);
00189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
00190     bool SliceUpLoad(SDNode *N);
00191 
00192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
00193     ///   load.
00194     ///
00195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
00196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
00197     /// \param EltNo index of the vector element to load.
00198     /// \param OriginalLoad load that EVE came from to be replaced.
00199     /// \returns EVE on success SDValue() on failure.
00200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
00201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
00202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
00203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
00204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
00205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
00206     SDValue PromoteIntBinOp(SDValue Op);
00207     SDValue PromoteIntShiftOp(SDValue Op);
00208     SDValue PromoteExtend(SDValue Op);
00209     bool PromoteLoad(SDValue Op);
00210 
00211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
00212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
00213                          ISD::NodeType ExtType);
00214 
00215     /// Call the node-specific routine that knows how to fold each
00216     /// particular type of node. If that doesn't do anything, try the
00217     /// target-specific DAG combines.
00218     SDValue combine(SDNode *N);
00219 
00220     // Visitation implementation - Implement dag node combining for different
00221     // node types.  The semantics are as follows:
00222     // Return Value:
00223     //   SDValue.getNode() == 0 - No change was made
00224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
00225     //   otherwise              - N should be replaced by the returned Operand.
00226     //
00227     SDValue visitTokenFactor(SDNode *N);
00228     SDValue visitMERGE_VALUES(SDNode *N);
00229     SDValue visitADD(SDNode *N);
00230     SDValue visitSUB(SDNode *N);
00231     SDValue visitADDC(SDNode *N);
00232     SDValue visitSUBC(SDNode *N);
00233     SDValue visitADDE(SDNode *N);
00234     SDValue visitSUBE(SDNode *N);
00235     SDValue visitMUL(SDNode *N);
00236     SDValue visitSDIV(SDNode *N);
00237     SDValue visitUDIV(SDNode *N);
00238     SDValue visitSREM(SDNode *N);
00239     SDValue visitUREM(SDNode *N);
00240     SDValue visitMULHU(SDNode *N);
00241     SDValue visitMULHS(SDNode *N);
00242     SDValue visitSMUL_LOHI(SDNode *N);
00243     SDValue visitUMUL_LOHI(SDNode *N);
00244     SDValue visitSMULO(SDNode *N);
00245     SDValue visitUMULO(SDNode *N);
00246     SDValue visitSDIVREM(SDNode *N);
00247     SDValue visitUDIVREM(SDNode *N);
00248     SDValue visitAND(SDNode *N);
00249     SDValue visitOR(SDNode *N);
00250     SDValue visitXOR(SDNode *N);
00251     SDValue SimplifyVBinOp(SDNode *N);
00252     SDValue SimplifyVUnaryOp(SDNode *N);
00253     SDValue visitSHL(SDNode *N);
00254     SDValue visitSRA(SDNode *N);
00255     SDValue visitSRL(SDNode *N);
00256     SDValue visitRotate(SDNode *N);
00257     SDValue visitCTLZ(SDNode *N);
00258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
00259     SDValue visitCTTZ(SDNode *N);
00260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
00261     SDValue visitCTPOP(SDNode *N);
00262     SDValue visitSELECT(SDNode *N);
00263     SDValue visitVSELECT(SDNode *N);
00264     SDValue visitSELECT_CC(SDNode *N);
00265     SDValue visitSETCC(SDNode *N);
00266     SDValue visitSIGN_EXTEND(SDNode *N);
00267     SDValue visitZERO_EXTEND(SDNode *N);
00268     SDValue visitANY_EXTEND(SDNode *N);
00269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
00270     SDValue visitTRUNCATE(SDNode *N);
00271     SDValue visitBITCAST(SDNode *N);
00272     SDValue visitBUILD_PAIR(SDNode *N);
00273     SDValue visitFADD(SDNode *N);
00274     SDValue visitFSUB(SDNode *N);
00275     SDValue visitFMUL(SDNode *N);
00276     SDValue visitFMA(SDNode *N);
00277     SDValue visitFDIV(SDNode *N);
00278     SDValue visitFREM(SDNode *N);
00279     SDValue visitFCOPYSIGN(SDNode *N);
00280     SDValue visitSINT_TO_FP(SDNode *N);
00281     SDValue visitUINT_TO_FP(SDNode *N);
00282     SDValue visitFP_TO_SINT(SDNode *N);
00283     SDValue visitFP_TO_UINT(SDNode *N);
00284     SDValue visitFP_ROUND(SDNode *N);
00285     SDValue visitFP_ROUND_INREG(SDNode *N);
00286     SDValue visitFP_EXTEND(SDNode *N);
00287     SDValue visitFNEG(SDNode *N);
00288     SDValue visitFABS(SDNode *N);
00289     SDValue visitFCEIL(SDNode *N);
00290     SDValue visitFTRUNC(SDNode *N);
00291     SDValue visitFFLOOR(SDNode *N);
00292     SDValue visitBRCOND(SDNode *N);
00293     SDValue visitBR_CC(SDNode *N);
00294     SDValue visitLOAD(SDNode *N);
00295     SDValue visitSTORE(SDNode *N);
00296     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
00297     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
00298     SDValue visitBUILD_VECTOR(SDNode *N);
00299     SDValue visitCONCAT_VECTORS(SDNode *N);
00300     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
00301     SDValue visitVECTOR_SHUFFLE(SDNode *N);
00302     SDValue visitINSERT_SUBVECTOR(SDNode *N);
00303 
00304     SDValue XformToShuffleWithZero(SDNode *N);
00305     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
00306 
00307     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
00308 
00309     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
00310     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
00311     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
00312     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
00313                              SDValue N3, ISD::CondCode CC,
00314                              bool NotExtCompare = false);
00315     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
00316                           SDLoc DL, bool foldBooleans = true);
00317 
00318     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
00319                            SDValue &CC) const;
00320     bool isOneUseSetCC(SDValue N) const;
00321 
00322     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
00323                                          unsigned HiOp);
00324     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
00325     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
00326     SDValue BuildSDIV(SDNode *N);
00327     SDValue BuildSDIVPow2(SDNode *N);
00328     SDValue BuildUDIV(SDNode *N);
00329     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
00330                                bool DemandHighBits = true);
00331     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
00332     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
00333                               SDValue InnerPos, SDValue InnerNeg,
00334                               unsigned PosOpcode, unsigned NegOpcode,
00335                               SDLoc DL);
00336     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
00337     SDValue ReduceLoadWidth(SDNode *N);
00338     SDValue ReduceLoadOpStoreWidth(SDNode *N);
00339     SDValue TransformFPLoadStorePair(SDNode *N);
00340     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
00341     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
00342 
00343     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
00344 
00345     /// Walk up chain skipping non-aliasing memory nodes,
00346     /// looking for aliasing nodes and adding them to the Aliases vector.
00347     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
00348                           SmallVectorImpl<SDValue> &Aliases);
00349 
00350     /// Return true if there is any possibility that the two addresses overlap.
00351     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
00352 
00353     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
00354     /// chain (aliasing node.)
00355     SDValue FindBetterChain(SDNode *N, SDValue Chain);
00356 
00357     /// Merge consecutive store operations into a wide store.
00358     /// This optimization uses wide integers or vectors when possible.
00359     /// \return True if some memory operations were changed.
00360     bool MergeConsecutiveStores(StoreSDNode *N);
00361 
00362     /// \brief Try to transform a truncation where C is a constant:
00363     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
00364     ///
00365     /// \p N needs to be a truncation and its first operand an AND. Other
00366     /// requirements are checked by the function (e.g. that trunc is
00367     /// single-use) and if missed an empty SDValue is returned.
00368     SDValue distributeTruncateThroughAnd(SDNode *N);
00369 
00370   public:
00371     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
00372         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
00373           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
00374       AttributeSet FnAttrs =
00375           DAG.getMachineFunction().getFunction()->getAttributes();
00376       ForCodeSize =
00377           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
00378                                Attribute::OptimizeForSize) ||
00379           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
00380     }
00381 
00382     /// Runs the dag combiner on all nodes in the work list
00383     void Run(CombineLevel AtLevel);
00384 
00385     SelectionDAG &getDAG() const { return DAG; }
00386 
00387     /// Returns a type large enough to hold any valid shift amount - before type
00388     /// legalization these can be huge.
00389     EVT getShiftAmountTy(EVT LHSTy) {
00390       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
00391       if (LHSTy.isVector())
00392         return LHSTy;
00393       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
00394                         : TLI.getPointerTy();
00395     }
00396 
00397     /// This method returns true if we are running before type legalization or
00398     /// if the specified VT is legal.
00399     bool isTypeLegal(const EVT &VT) {
00400       if (!LegalTypes) return true;
00401       return TLI.isTypeLegal(VT);
00402     }
00403 
00404     /// Convenience wrapper around TargetLowering::getSetCCResultType
00405     EVT getSetCCResultType(EVT VT) const {
00406       return TLI.getSetCCResultType(*DAG.getContext(), VT);
00407     }
00408   };
00409 }
00410 
00411 
00412 namespace {
00413 /// This class is a DAGUpdateListener that removes any deleted
00414 /// nodes from the worklist.
00415 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
00416   DAGCombiner &DC;
00417 public:
00418   explicit WorklistRemover(DAGCombiner &dc)
00419     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
00420 
00421   void NodeDeleted(SDNode *N, SDNode *E) override {
00422     DC.removeFromWorklist(N);
00423   }
00424 };
00425 }
00426 
00427 //===----------------------------------------------------------------------===//
00428 //  TargetLowering::DAGCombinerInfo implementation
00429 //===----------------------------------------------------------------------===//
00430 
00431 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
00432   ((DAGCombiner*)DC)->AddToWorklist(N);
00433 }
00434 
00435 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
00436   ((DAGCombiner*)DC)->removeFromWorklist(N);
00437 }
00438 
00439 SDValue TargetLowering::DAGCombinerInfo::
00440 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
00441   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
00442 }
00443 
00444 SDValue TargetLowering::DAGCombinerInfo::
00445 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
00446   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
00447 }
00448 
00449 
00450 SDValue TargetLowering::DAGCombinerInfo::
00451 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
00452   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
00453 }
00454 
00455 void TargetLowering::DAGCombinerInfo::
00456 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
00457   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
00458 }
00459 
00460 //===----------------------------------------------------------------------===//
00461 // Helper Functions
00462 //===----------------------------------------------------------------------===//
00463 
00464 void DAGCombiner::deleteAndRecombine(SDNode *N) {
00465   removeFromWorklist(N);
00466 
00467   // If the operands of this node are only used by the node, they will now be
00468   // dead. Make sure to re-visit them and recursively delete dead nodes.
00469   for (const SDValue &Op : N->ops())
00470     // For an operand generating multiple values, one of the values may
00471     // become dead allowing further simplification (e.g. split index
00472     // arithmetic from an indexed load).
00473     if (Op->hasOneUse() || Op->getNumValues() > 1)
00474       AddToWorklist(Op.getNode());
00475 
00476   DAG.DeleteNode(N);
00477 }
00478 
00479 /// Return 1 if we can compute the negated form of the specified expression for
00480 /// the same cost as the expression itself, or 2 if we can compute the negated
00481 /// form more cheaply than the expression itself.
00482 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
00483                                const TargetLowering &TLI,
00484                                const TargetOptions *Options,
00485                                unsigned Depth = 0) {
00486   // fneg is removable even if it has multiple uses.
00487   if (Op.getOpcode() == ISD::FNEG) return 2;
00488 
00489   // Don't allow anything with multiple uses.
00490   if (!Op.hasOneUse()) return 0;
00491 
00492   // Don't recurse exponentially.
00493   if (Depth > 6) return 0;
00494 
00495   switch (Op.getOpcode()) {
00496   default: return false;
00497   case ISD::ConstantFP:
00498     // Don't invert constant FP values after legalize.  The negated constant
00499     // isn't necessarily legal.
00500     return LegalOperations ? 0 : 1;
00501   case ISD::FADD:
00502     // FIXME: determine better conditions for this xform.
00503     if (!Options->UnsafeFPMath) return 0;
00504 
00505     // After operation legalization, it might not be legal to create new FSUBs.
00506     if (LegalOperations &&
00507         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
00508       return 0;
00509 
00510     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
00511     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
00512                                     Options, Depth + 1))
00513       return V;
00514     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00515     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
00516                               Depth + 1);
00517   case ISD::FSUB:
00518     // We can't turn -(A-B) into B-A when we honor signed zeros.
00519     if (!Options->UnsafeFPMath) return 0;
00520 
00521     // fold (fneg (fsub A, B)) -> (fsub B, A)
00522     return 1;
00523 
00524   case ISD::FMUL:
00525   case ISD::FDIV:
00526     if (Options->HonorSignDependentRoundingFPMath()) return 0;
00527 
00528     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
00529     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
00530                                     Options, Depth + 1))
00531       return V;
00532 
00533     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
00534                               Depth + 1);
00535 
00536   case ISD::FP_EXTEND:
00537   case ISD::FP_ROUND:
00538   case ISD::FSIN:
00539     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
00540                               Depth + 1);
00541   }
00542 }
00543 
00544 /// If isNegatibleForFree returns true, return the newly negated expression.
00545 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
00546                                     bool LegalOperations, unsigned Depth = 0) {
00547   const TargetOptions &Options = DAG.getTarget().Options;
00548   // fneg is removable even if it has multiple uses.
00549   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
00550 
00551   // Don't allow anything with multiple uses.
00552   assert(Op.hasOneUse() && "Unknown reuse!");
00553 
00554   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
00555   switch (Op.getOpcode()) {
00556   default: llvm_unreachable("Unknown code");
00557   case ISD::ConstantFP: {
00558     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
00559     V.changeSign();
00560     return DAG.getConstantFP(V, Op.getValueType());
00561   }
00562   case ISD::FADD:
00563     // FIXME: determine better conditions for this xform.
00564     assert(Options.UnsafeFPMath);
00565 
00566     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
00567     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
00568                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
00569       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
00570                          GetNegatedExpression(Op.getOperand(0), DAG,
00571                                               LegalOperations, Depth+1),
00572                          Op.getOperand(1));
00573     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
00574     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
00575                        GetNegatedExpression(Op.getOperand(1), DAG,
00576                                             LegalOperations, Depth+1),
00577                        Op.getOperand(0));
00578   case ISD::FSUB:
00579     // We can't turn -(A-B) into B-A when we honor signed zeros.
00580     assert(Options.UnsafeFPMath);
00581 
00582     // fold (fneg (fsub 0, B)) -> B
00583     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
00584       if (N0CFP->getValueAPF().isZero())
00585         return Op.getOperand(1);
00586 
00587     // fold (fneg (fsub A, B)) -> (fsub B, A)
00588     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
00589                        Op.getOperand(1), Op.getOperand(0));
00590 
00591   case ISD::FMUL:
00592   case ISD::FDIV:
00593     assert(!Options.HonorSignDependentRoundingFPMath());
00594 
00595     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
00596     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
00597                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
00598       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
00599                          GetNegatedExpression(Op.getOperand(0), DAG,
00600                                               LegalOperations, Depth+1),
00601                          Op.getOperand(1));
00602 
00603     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
00604     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
00605                        Op.getOperand(0),
00606                        GetNegatedExpression(Op.getOperand(1), DAG,
00607                                             LegalOperations, Depth+1));
00608 
00609   case ISD::FP_EXTEND:
00610   case ISD::FSIN:
00611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
00612                        GetNegatedExpression(Op.getOperand(0), DAG,
00613                                             LegalOperations, Depth+1));
00614   case ISD::FP_ROUND:
00615       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
00616                          GetNegatedExpression(Op.getOperand(0), DAG,
00617                                               LegalOperations, Depth+1),
00618                          Op.getOperand(1));
00619   }
00620 }
00621 
00622 // Return true if this node is a setcc, or is a select_cc
00623 // that selects between the target values used for true and false, making it
00624 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
00625 // the appropriate nodes based on the type of node we are checking. This
00626 // simplifies life a bit for the callers.
00627 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
00628                                     SDValue &CC) const {
00629   if (N.getOpcode() == ISD::SETCC) {
00630     LHS = N.getOperand(0);
00631     RHS = N.getOperand(1);
00632     CC  = N.getOperand(2);
00633     return true;
00634   }
00635 
00636   if (N.getOpcode() != ISD::SELECT_CC ||
00637       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
00638       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
00639     return false;
00640 
00641   LHS = N.getOperand(0);
00642   RHS = N.getOperand(1);
00643   CC  = N.getOperand(4);
00644   return true;
00645 }
00646 
00647 /// Return true if this is a SetCC-equivalent operation with only one use.
00648 /// If this is true, it allows the users to invert the operation for free when
00649 /// it is profitable to do so.
00650 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
00651   SDValue N0, N1, N2;
00652   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
00653     return true;
00654   return false;
00655 }
00656 
00657 /// Returns true if N is a BUILD_VECTOR node whose
00658 /// elements are all the same constant or undefined.
00659 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
00660   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
00661   if (!C)
00662     return false;
00663 
00664   APInt SplatUndef;
00665   unsigned SplatBitSize;
00666   bool HasAnyUndefs;
00667   EVT EltVT = N->getValueType(0).getVectorElementType();
00668   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
00669                              HasAnyUndefs) &&
00670           EltVT.getSizeInBits() >= SplatBitSize);
00671 }
00672 
00673 // \brief Returns the SDNode if it is a constant BuildVector or constant.
00674 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
00675   if (isa<ConstantSDNode>(N))
00676     return N.getNode();
00677   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
00678   if (BV && BV->isConstant())
00679     return BV;
00680   return nullptr;
00681 }
00682 
00683 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
00684 // int.
00685 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
00686   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
00687     return CN;
00688 
00689   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
00690     BitVector UndefElements;
00691     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
00692 
00693     // BuildVectors can truncate their operands. Ignore that case here.
00694     // FIXME: We blindly ignore splats which include undef which is overly
00695     // pessimistic.
00696     if (CN && UndefElements.none() &&
00697         CN->getValueType(0) == N.getValueType().getScalarType())
00698       return CN;
00699   }
00700 
00701   return nullptr;
00702 }
00703 
00704 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
00705 // float.
00706 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
00707   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
00708     return CN;
00709 
00710   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
00711     BitVector UndefElements;
00712     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
00713 
00714     if (CN && UndefElements.none())
00715       return CN;
00716   }
00717 
00718   return nullptr;
00719 }
00720 
00721 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
00722                                     SDValue N0, SDValue N1) {
00723   EVT VT = N0.getValueType();
00724   if (N0.getOpcode() == Opc) {
00725     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
00726       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
00727         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
00728         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
00729         if (!OpNode.getNode())
00730           return SDValue();
00731         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
00732       }
00733       if (N0.hasOneUse()) {
00734         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
00735         // use
00736         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
00737         if (!OpNode.getNode())
00738           return SDValue();
00739         AddToWorklist(OpNode.getNode());
00740         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
00741       }
00742     }
00743   }
00744 
00745   if (N1.getOpcode() == Opc) {
00746     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
00747       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
00748         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
00749         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
00750         if (!OpNode.getNode())
00751           return SDValue();
00752         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
00753       }
00754       if (N1.hasOneUse()) {
00755         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
00756         // use
00757         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
00758         if (!OpNode.getNode())
00759           return SDValue();
00760         AddToWorklist(OpNode.getNode());
00761         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
00762       }
00763     }
00764   }
00765 
00766   return SDValue();
00767 }
00768 
00769 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
00770                                bool AddTo) {
00771   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
00772   ++NodesCombined;
00773   DEBUG(dbgs() << "\nReplacing.1 ";
00774         N->dump(&DAG);
00775         dbgs() << "\nWith: ";
00776         To[0].getNode()->dump(&DAG);
00777         dbgs() << " and " << NumTo-1 << " other values\n";
00778         for (unsigned i = 0, e = NumTo; i != e; ++i)
00779           assert((!To[i].getNode() ||
00780                   N->getValueType(i) == To[i].getValueType()) &&
00781                  "Cannot combine value to value of different type!"));
00782   WorklistRemover DeadNodes(*this);
00783   DAG.ReplaceAllUsesWith(N, To);
00784   if (AddTo) {
00785     // Push the new nodes and any users onto the worklist
00786     for (unsigned i = 0, e = NumTo; i != e; ++i) {
00787       if (To[i].getNode()) {
00788         AddToWorklist(To[i].getNode());
00789         AddUsersToWorklist(To[i].getNode());
00790       }
00791     }
00792   }
00793 
00794   // Finally, if the node is now dead, remove it from the graph.  The node
00795   // may not be dead if the replacement process recursively simplified to
00796   // something else needing this node.
00797   if (N->use_empty())
00798     deleteAndRecombine(N);
00799   return SDValue(N, 0);
00800 }
00801 
00802 void DAGCombiner::
00803 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
00804   // Replace all uses.  If any nodes become isomorphic to other nodes and
00805   // are deleted, make sure to remove them from our worklist.
00806   WorklistRemover DeadNodes(*this);
00807   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
00808 
00809   // Push the new node and any (possibly new) users onto the worklist.
00810   AddToWorklist(TLO.New.getNode());
00811   AddUsersToWorklist(TLO.New.getNode());
00812 
00813   // Finally, if the node is now dead, remove it from the graph.  The node
00814   // may not be dead if the replacement process recursively simplified to
00815   // something else needing this node.
00816   if (TLO.Old.getNode()->use_empty())
00817     deleteAndRecombine(TLO.Old.getNode());
00818 }
00819 
00820 /// Check the specified integer node value to see if it can be simplified or if
00821 /// things it uses can be simplified by bit propagation. If so, return true.
00822 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
00823   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
00824   APInt KnownZero, KnownOne;
00825   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
00826     return false;
00827 
00828   // Revisit the node.
00829   AddToWorklist(Op.getNode());
00830 
00831   // Replace the old value with the new one.
00832   ++NodesCombined;
00833   DEBUG(dbgs() << "\nReplacing.2 ";
00834         TLO.Old.getNode()->dump(&DAG);
00835         dbgs() << "\nWith: ";
00836         TLO.New.getNode()->dump(&DAG);
00837         dbgs() << '\n');
00838 
00839   CommitTargetLoweringOpt(TLO);
00840   return true;
00841 }
00842 
00843 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
00844   SDLoc dl(Load);
00845   EVT VT = Load->getValueType(0);
00846   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
00847 
00848   DEBUG(dbgs() << "\nReplacing.9 ";
00849         Load->dump(&DAG);
00850         dbgs() << "\nWith: ";
00851         Trunc.getNode()->dump(&DAG);
00852         dbgs() << '\n');
00853   WorklistRemover DeadNodes(*this);
00854   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
00855   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
00856   deleteAndRecombine(Load);
00857   AddToWorklist(Trunc.getNode());
00858 }
00859 
00860 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
00861   Replace = false;
00862   SDLoc dl(Op);
00863   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
00864     EVT MemVT = LD->getMemoryVT();
00865     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
00866       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
00867                                                   : ISD::EXTLOAD)
00868       : LD->getExtensionType();
00869     Replace = true;
00870     return DAG.getExtLoad(ExtType, dl, PVT,
00871                           LD->getChain(), LD->getBasePtr(),
00872                           MemVT, LD->getMemOperand());
00873   }
00874 
00875   unsigned Opc = Op.getOpcode();
00876   switch (Opc) {
00877   default: break;
00878   case ISD::AssertSext:
00879     return DAG.getNode(ISD::AssertSext, dl, PVT,
00880                        SExtPromoteOperand(Op.getOperand(0), PVT),
00881                        Op.getOperand(1));
00882   case ISD::AssertZext:
00883     return DAG.getNode(ISD::AssertZext, dl, PVT,
00884                        ZExtPromoteOperand(Op.getOperand(0), PVT),
00885                        Op.getOperand(1));
00886   case ISD::Constant: {
00887     unsigned ExtOpc =
00888       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
00889     return DAG.getNode(ExtOpc, dl, PVT, Op);
00890   }
00891   }
00892 
00893   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
00894     return SDValue();
00895   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
00896 }
00897 
00898 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
00899   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
00900     return SDValue();
00901   EVT OldVT = Op.getValueType();
00902   SDLoc dl(Op);
00903   bool Replace = false;
00904   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
00905   if (!NewOp.getNode())
00906     return SDValue();
00907   AddToWorklist(NewOp.getNode());
00908 
00909   if (Replace)
00910     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
00911   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
00912                      DAG.getValueType(OldVT));
00913 }
00914 
00915 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
00916   EVT OldVT = Op.getValueType();
00917   SDLoc dl(Op);
00918   bool Replace = false;
00919   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
00920   if (!NewOp.getNode())
00921     return SDValue();
00922   AddToWorklist(NewOp.getNode());
00923 
00924   if (Replace)
00925     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
00926   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
00927 }
00928 
00929 /// Promote the specified integer binary operation if the target indicates it is
00930 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
00931 /// i32 since i16 instructions are longer.
00932 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
00933   if (!LegalOperations)
00934     return SDValue();
00935 
00936   EVT VT = Op.getValueType();
00937   if (VT.isVector() || !VT.isInteger())
00938     return SDValue();
00939 
00940   // If operation type is 'undesirable', e.g. i16 on x86, consider
00941   // promoting it.
00942   unsigned Opc = Op.getOpcode();
00943   if (TLI.isTypeDesirableForOp(Opc, VT))
00944     return SDValue();
00945 
00946   EVT PVT = VT;
00947   // Consult target whether it is a good idea to promote this operation and
00948   // what's the right type to promote it to.
00949   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
00950     assert(PVT != VT && "Don't know what type to promote to!");
00951 
00952     bool Replace0 = false;
00953     SDValue N0 = Op.getOperand(0);
00954     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
00955     if (!NN0.getNode())
00956       return SDValue();
00957 
00958     bool Replace1 = false;
00959     SDValue N1 = Op.getOperand(1);
00960     SDValue NN1;
00961     if (N0 == N1)
00962       NN1 = NN0;
00963     else {
00964       NN1 = PromoteOperand(N1, PVT, Replace1);
00965       if (!NN1.getNode())
00966         return SDValue();
00967     }
00968 
00969     AddToWorklist(NN0.getNode());
00970     if (NN1.getNode())
00971       AddToWorklist(NN1.getNode());
00972 
00973     if (Replace0)
00974       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
00975     if (Replace1)
00976       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
00977 
00978     DEBUG(dbgs() << "\nPromoting ";
00979           Op.getNode()->dump(&DAG));
00980     SDLoc dl(Op);
00981     return DAG.getNode(ISD::TRUNCATE, dl, VT,
00982                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
00983   }
00984   return SDValue();
00985 }
00986 
00987 /// Promote the specified integer shift operation if the target indicates it is
00988 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
00989 /// i32 since i16 instructions are longer.
00990 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
00991   if (!LegalOperations)
00992     return SDValue();
00993 
00994   EVT VT = Op.getValueType();
00995   if (VT.isVector() || !VT.isInteger())
00996     return SDValue();
00997 
00998   // If operation type is 'undesirable', e.g. i16 on x86, consider
00999   // promoting it.
01000   unsigned Opc = Op.getOpcode();
01001   if (TLI.isTypeDesirableForOp(Opc, VT))
01002     return SDValue();
01003 
01004   EVT PVT = VT;
01005   // Consult target whether it is a good idea to promote this operation and
01006   // what's the right type to promote it to.
01007   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
01008     assert(PVT != VT && "Don't know what type to promote to!");
01009 
01010     bool Replace = false;
01011     SDValue N0 = Op.getOperand(0);
01012     if (Opc == ISD::SRA)
01013       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
01014     else if (Opc == ISD::SRL)
01015       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
01016     else
01017       N0 = PromoteOperand(N0, PVT, Replace);
01018     if (!N0.getNode())
01019       return SDValue();
01020 
01021     AddToWorklist(N0.getNode());
01022     if (Replace)
01023       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
01024 
01025     DEBUG(dbgs() << "\nPromoting ";
01026           Op.getNode()->dump(&DAG));
01027     SDLoc dl(Op);
01028     return DAG.getNode(ISD::TRUNCATE, dl, VT,
01029                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
01030   }
01031   return SDValue();
01032 }
01033 
01034 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
01035   if (!LegalOperations)
01036     return SDValue();
01037 
01038   EVT VT = Op.getValueType();
01039   if (VT.isVector() || !VT.isInteger())
01040     return SDValue();
01041 
01042   // If operation type is 'undesirable', e.g. i16 on x86, consider
01043   // promoting it.
01044   unsigned Opc = Op.getOpcode();
01045   if (TLI.isTypeDesirableForOp(Opc, VT))
01046     return SDValue();
01047 
01048   EVT PVT = VT;
01049   // Consult target whether it is a good idea to promote this operation and
01050   // what's the right type to promote it to.
01051   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
01052     assert(PVT != VT && "Don't know what type to promote to!");
01053     // fold (aext (aext x)) -> (aext x)
01054     // fold (aext (zext x)) -> (zext x)
01055     // fold (aext (sext x)) -> (sext x)
01056     DEBUG(dbgs() << "\nPromoting ";
01057           Op.getNode()->dump(&DAG));
01058     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
01059   }
01060   return SDValue();
01061 }
01062 
01063 bool DAGCombiner::PromoteLoad(SDValue Op) {
01064   if (!LegalOperations)
01065     return false;
01066 
01067   EVT VT = Op.getValueType();
01068   if (VT.isVector() || !VT.isInteger())
01069     return false;
01070 
01071   // If operation type is 'undesirable', e.g. i16 on x86, consider
01072   // promoting it.
01073   unsigned Opc = Op.getOpcode();
01074   if (TLI.isTypeDesirableForOp(Opc, VT))
01075     return false;
01076 
01077   EVT PVT = VT;
01078   // Consult target whether it is a good idea to promote this operation and
01079   // what's the right type to promote it to.
01080   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
01081     assert(PVT != VT && "Don't know what type to promote to!");
01082 
01083     SDLoc dl(Op);
01084     SDNode *N = Op.getNode();
01085     LoadSDNode *LD = cast<LoadSDNode>(N);
01086     EVT MemVT = LD->getMemoryVT();
01087     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
01088       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
01089                                                   : ISD::EXTLOAD)
01090       : LD->getExtensionType();
01091     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
01092                                    LD->getChain(), LD->getBasePtr(),
01093                                    MemVT, LD->getMemOperand());
01094     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
01095 
01096     DEBUG(dbgs() << "\nPromoting ";
01097           N->dump(&DAG);
01098           dbgs() << "\nTo: ";
01099           Result.getNode()->dump(&DAG);
01100           dbgs() << '\n');
01101     WorklistRemover DeadNodes(*this);
01102     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
01103     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
01104     deleteAndRecombine(N);
01105     AddToWorklist(Result.getNode());
01106     return true;
01107   }
01108   return false;
01109 }
01110 
01111 /// \brief Recursively delete a node which has no uses and any operands for
01112 /// which it is the only use.
01113 ///
01114 /// Note that this both deletes the nodes and removes them from the worklist.
01115 /// It also adds any nodes who have had a user deleted to the worklist as they
01116 /// may now have only one use and subject to other combines.
01117 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
01118   if (!N->use_empty())
01119     return false;
01120 
01121   SmallSetVector<SDNode *, 16> Nodes;
01122   Nodes.insert(N);
01123   do {
01124     N = Nodes.pop_back_val();
01125     if (!N)
01126       continue;
01127 
01128     if (N->use_empty()) {
01129       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01130         Nodes.insert(N->getOperand(i).getNode());
01131 
01132       removeFromWorklist(N);
01133       DAG.DeleteNode(N);
01134     } else {
01135       AddToWorklist(N);
01136     }
01137   } while (!Nodes.empty());
01138   return true;
01139 }
01140 
01141 //===----------------------------------------------------------------------===//
01142 //  Main DAG Combiner implementation
01143 //===----------------------------------------------------------------------===//
01144 
01145 void DAGCombiner::Run(CombineLevel AtLevel) {
01146   // set the instance variables, so that the various visit routines may use it.
01147   Level = AtLevel;
01148   LegalOperations = Level >= AfterLegalizeVectorOps;
01149   LegalTypes = Level >= AfterLegalizeTypes;
01150 
01151   // Add all the dag nodes to the worklist.
01152   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
01153        E = DAG.allnodes_end(); I != E; ++I)
01154     AddToWorklist(I);
01155 
01156   // Create a dummy node (which is not added to allnodes), that adds a reference
01157   // to the root node, preventing it from being deleted, and tracking any
01158   // changes of the root.
01159   HandleSDNode Dummy(DAG.getRoot());
01160 
01161   // while the worklist isn't empty, find a node and
01162   // try and combine it.
01163   while (!WorklistMap.empty()) {
01164     SDNode *N;
01165     // The Worklist holds the SDNodes in order, but it may contain null entries.
01166     do {
01167       N = Worklist.pop_back_val();
01168     } while (!N);
01169 
01170     bool GoodWorklistEntry = WorklistMap.erase(N);
01171     (void)GoodWorklistEntry;
01172     assert(GoodWorklistEntry &&
01173            "Found a worklist entry without a corresponding map entry!");
01174 
01175     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
01176     // N is deleted from the DAG, since they too may now be dead or may have a
01177     // reduced number of uses, allowing other xforms.
01178     if (recursivelyDeleteUnusedNodes(N))
01179       continue;
01180 
01181     WorklistRemover DeadNodes(*this);
01182 
01183     // If this combine is running after legalizing the DAG, re-legalize any
01184     // nodes pulled off the worklist.
01185     if (Level == AfterLegalizeDAG) {
01186       SmallSetVector<SDNode *, 16> UpdatedNodes;
01187       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
01188 
01189       for (SDNode *LN : UpdatedNodes) {
01190         AddToWorklist(LN);
01191         AddUsersToWorklist(LN);
01192       }
01193       if (!NIsValid)
01194         continue;
01195     }
01196 
01197     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
01198 
01199     // Add any operands of the new node which have not yet been combined to the
01200     // worklist as well. Because the worklist uniques things already, this
01201     // won't repeatedly process the same operand.
01202     CombinedNodes.insert(N);
01203     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01204       if (!CombinedNodes.count(N->getOperand(i).getNode()))
01205         AddToWorklist(N->getOperand(i).getNode());
01206 
01207     SDValue RV = combine(N);
01208 
01209     if (!RV.getNode())
01210       continue;
01211 
01212     ++NodesCombined;
01213 
01214     // If we get back the same node we passed in, rather than a new node or
01215     // zero, we know that the node must have defined multiple values and
01216     // CombineTo was used.  Since CombineTo takes care of the worklist
01217     // mechanics for us, we have no work to do in this case.
01218     if (RV.getNode() == N)
01219       continue;
01220 
01221     assert(N->getOpcode() != ISD::DELETED_NODE &&
01222            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
01223            "Node was deleted but visit returned new node!");
01224 
01225     DEBUG(dbgs() << " ... into: ";
01226           RV.getNode()->dump(&DAG));
01227 
01228     // Transfer debug value.
01229     DAG.TransferDbgValues(SDValue(N, 0), RV);
01230     if (N->getNumValues() == RV.getNode()->getNumValues())
01231       DAG.ReplaceAllUsesWith(N, RV.getNode());
01232     else {
01233       assert(N->getValueType(0) == RV.getValueType() &&
01234              N->getNumValues() == 1 && "Type mismatch");
01235       SDValue OpV = RV;
01236       DAG.ReplaceAllUsesWith(N, &OpV);
01237     }
01238 
01239     // Push the new node and any users onto the worklist
01240     AddToWorklist(RV.getNode());
01241     AddUsersToWorklist(RV.getNode());
01242 
01243     // Finally, if the node is now dead, remove it from the graph.  The node
01244     // may not be dead if the replacement process recursively simplified to
01245     // something else needing this node. This will also take care of adding any
01246     // operands which have lost a user to the worklist.
01247     recursivelyDeleteUnusedNodes(N);
01248   }
01249 
01250   // If the root changed (e.g. it was a dead load, update the root).
01251   DAG.setRoot(Dummy.getValue());
01252   DAG.RemoveDeadNodes();
01253 }
01254 
01255 SDValue DAGCombiner::visit(SDNode *N) {
01256   switch (N->getOpcode()) {
01257   default: break;
01258   case ISD::TokenFactor:        return visitTokenFactor(N);
01259   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
01260   case ISD::ADD:                return visitADD(N);
01261   case ISD::SUB:                return visitSUB(N);
01262   case ISD::ADDC:               return visitADDC(N);
01263   case ISD::SUBC:               return visitSUBC(N);
01264   case ISD::ADDE:               return visitADDE(N);
01265   case ISD::SUBE:               return visitSUBE(N);
01266   case ISD::MUL:                return visitMUL(N);
01267   case ISD::SDIV:               return visitSDIV(N);
01268   case ISD::UDIV:               return visitUDIV(N);
01269   case ISD::SREM:               return visitSREM(N);
01270   case ISD::UREM:               return visitUREM(N);
01271   case ISD::MULHU:              return visitMULHU(N);
01272   case ISD::MULHS:              return visitMULHS(N);
01273   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
01274   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
01275   case ISD::SMULO:              return visitSMULO(N);
01276   case ISD::UMULO:              return visitUMULO(N);
01277   case ISD::SDIVREM:            return visitSDIVREM(N);
01278   case ISD::UDIVREM:            return visitUDIVREM(N);
01279   case ISD::AND:                return visitAND(N);
01280   case ISD::OR:                 return visitOR(N);
01281   case ISD::XOR:                return visitXOR(N);
01282   case ISD::SHL:                return visitSHL(N);
01283   case ISD::SRA:                return visitSRA(N);
01284   case ISD::SRL:                return visitSRL(N);
01285   case ISD::ROTR:
01286   case ISD::ROTL:               return visitRotate(N);
01287   case ISD::CTLZ:               return visitCTLZ(N);
01288   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
01289   case ISD::CTTZ:               return visitCTTZ(N);
01290   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
01291   case ISD::CTPOP:              return visitCTPOP(N);
01292   case ISD::SELECT:             return visitSELECT(N);
01293   case ISD::VSELECT:            return visitVSELECT(N);
01294   case ISD::SELECT_CC:          return visitSELECT_CC(N);
01295   case ISD::SETCC:              return visitSETCC(N);
01296   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
01297   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
01298   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
01299   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
01300   case ISD::TRUNCATE:           return visitTRUNCATE(N);
01301   case ISD::BITCAST:            return visitBITCAST(N);
01302   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
01303   case ISD::FADD:               return visitFADD(N);
01304   case ISD::FSUB:               return visitFSUB(N);
01305   case ISD::FMUL:               return visitFMUL(N);
01306   case ISD::FMA:                return visitFMA(N);
01307   case ISD::FDIV:               return visitFDIV(N);
01308   case ISD::FREM:               return visitFREM(N);
01309   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
01310   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
01311   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
01312   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
01313   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
01314   case ISD::FP_ROUND:           return visitFP_ROUND(N);
01315   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
01316   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
01317   case ISD::FNEG:               return visitFNEG(N);
01318   case ISD::FABS:               return visitFABS(N);
01319   case ISD::FFLOOR:             return visitFFLOOR(N);
01320   case ISD::FCEIL:              return visitFCEIL(N);
01321   case ISD::FTRUNC:             return visitFTRUNC(N);
01322   case ISD::BRCOND:             return visitBRCOND(N);
01323   case ISD::BR_CC:              return visitBR_CC(N);
01324   case ISD::LOAD:               return visitLOAD(N);
01325   case ISD::STORE:              return visitSTORE(N);
01326   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
01327   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
01328   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
01329   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
01330   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
01331   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
01332   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
01333   }
01334   return SDValue();
01335 }
01336 
01337 SDValue DAGCombiner::combine(SDNode *N) {
01338   SDValue RV = visit(N);
01339 
01340   // If nothing happened, try a target-specific DAG combine.
01341   if (!RV.getNode()) {
01342     assert(N->getOpcode() != ISD::DELETED_NODE &&
01343            "Node was deleted but visit returned NULL!");
01344 
01345     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
01346         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
01347 
01348       // Expose the DAG combiner to the target combiner impls.
01349       TargetLowering::DAGCombinerInfo
01350         DagCombineInfo(DAG, Level, false, this);
01351 
01352       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
01353     }
01354   }
01355 
01356   // If nothing happened still, try promoting the operation.
01357   if (!RV.getNode()) {
01358     switch (N->getOpcode()) {
01359     default: break;
01360     case ISD::ADD:
01361     case ISD::SUB:
01362     case ISD::MUL:
01363     case ISD::AND:
01364     case ISD::OR:
01365     case ISD::XOR:
01366       RV = PromoteIntBinOp(SDValue(N, 0));
01367       break;
01368     case ISD::SHL:
01369     case ISD::SRA:
01370     case ISD::SRL:
01371       RV = PromoteIntShiftOp(SDValue(N, 0));
01372       break;
01373     case ISD::SIGN_EXTEND:
01374     case ISD::ZERO_EXTEND:
01375     case ISD::ANY_EXTEND:
01376       RV = PromoteExtend(SDValue(N, 0));
01377       break;
01378     case ISD::LOAD:
01379       if (PromoteLoad(SDValue(N, 0)))
01380         RV = SDValue(N, 0);
01381       break;
01382     }
01383   }
01384 
01385   // If N is a commutative binary node, try commuting it to enable more
01386   // sdisel CSE.
01387   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
01388       N->getNumValues() == 1) {
01389     SDValue N0 = N->getOperand(0);
01390     SDValue N1 = N->getOperand(1);
01391 
01392     // Constant operands are canonicalized to RHS.
01393     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
01394       SDValue Ops[] = {N1, N0};
01395       SDNode *CSENode;
01396       if (const BinaryWithFlagsSDNode *BinNode =
01397               dyn_cast<BinaryWithFlagsSDNode>(N)) {
01398         CSENode = DAG.getNodeIfExists(
01399             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
01400             BinNode->hasNoSignedWrap(), BinNode->isExact());
01401       } else {
01402         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
01403       }
01404       if (CSENode)
01405         return SDValue(CSENode, 0);
01406     }
01407   }
01408 
01409   return RV;
01410 }
01411 
01412 /// Given a node, return its input chain if it has one, otherwise return a null
01413 /// sd operand.
01414 static SDValue getInputChainForNode(SDNode *N) {
01415   if (unsigned NumOps = N->getNumOperands()) {
01416     if (N->getOperand(0).getValueType() == MVT::Other)
01417       return N->getOperand(0);
01418     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
01419       return N->getOperand(NumOps-1);
01420     for (unsigned i = 1; i < NumOps-1; ++i)
01421       if (N->getOperand(i).getValueType() == MVT::Other)
01422         return N->getOperand(i);
01423   }
01424   return SDValue();
01425 }
01426 
01427 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
01428   // If N has two operands, where one has an input chain equal to the other,
01429   // the 'other' chain is redundant.
01430   if (N->getNumOperands() == 2) {
01431     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
01432       return N->getOperand(0);
01433     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
01434       return N->getOperand(1);
01435   }
01436 
01437   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
01438   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
01439   SmallPtrSet<SDNode*, 16> SeenOps;
01440   bool Changed = false;             // If we should replace this token factor.
01441 
01442   // Start out with this token factor.
01443   TFs.push_back(N);
01444 
01445   // Iterate through token factors.  The TFs grows when new token factors are
01446   // encountered.
01447   for (unsigned i = 0; i < TFs.size(); ++i) {
01448     SDNode *TF = TFs[i];
01449 
01450     // Check each of the operands.
01451     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
01452       SDValue Op = TF->getOperand(i);
01453 
01454       switch (Op.getOpcode()) {
01455       case ISD::EntryToken:
01456         // Entry tokens don't need to be added to the list. They are
01457         // rededundant.
01458         Changed = true;
01459         break;
01460 
01461       case ISD::TokenFactor:
01462         if (Op.hasOneUse() &&
01463             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
01464           // Queue up for processing.
01465           TFs.push_back(Op.getNode());
01466           // Clean up in case the token factor is removed.
01467           AddToWorklist(Op.getNode());
01468           Changed = true;
01469           break;
01470         }
01471         // Fall thru
01472 
01473       default:
01474         // Only add if it isn't already in the list.
01475         if (SeenOps.insert(Op.getNode()))
01476           Ops.push_back(Op);
01477         else
01478           Changed = true;
01479         break;
01480       }
01481     }
01482   }
01483 
01484   SDValue Result;
01485 
01486   // If we've change things around then replace token factor.
01487   if (Changed) {
01488     if (Ops.empty()) {
01489       // The entry token is the only possible outcome.
01490       Result = DAG.getEntryNode();
01491     } else {
01492       // New and improved token factor.
01493       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
01494     }
01495 
01496     // Don't add users to work list.
01497     return CombineTo(N, Result, false);
01498   }
01499 
01500   return Result;
01501 }
01502 
01503 /// MERGE_VALUES can always be eliminated.
01504 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
01505   WorklistRemover DeadNodes(*this);
01506   // Replacing results may cause a different MERGE_VALUES to suddenly
01507   // be CSE'd with N, and carry its uses with it. Iterate until no
01508   // uses remain, to ensure that the node can be safely deleted.
01509   // First add the users of this node to the work list so that they
01510   // can be tried again once they have new operands.
01511   AddUsersToWorklist(N);
01512   do {
01513     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
01514       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
01515   } while (!N->use_empty());
01516   deleteAndRecombine(N);
01517   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
01518 }
01519 
01520 SDValue DAGCombiner::visitADD(SDNode *N) {
01521   SDValue N0 = N->getOperand(0);
01522   SDValue N1 = N->getOperand(1);
01523   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01524   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01525   EVT VT = N0.getValueType();
01526 
01527   // fold vector ops
01528   if (VT.isVector()) {
01529     SDValue FoldedVOp = SimplifyVBinOp(N);
01530     if (FoldedVOp.getNode()) return FoldedVOp;
01531 
01532     // fold (add x, 0) -> x, vector edition
01533     if (ISD::isBuildVectorAllZeros(N1.getNode()))
01534       return N0;
01535     if (ISD::isBuildVectorAllZeros(N0.getNode()))
01536       return N1;
01537   }
01538 
01539   // fold (add x, undef) -> undef
01540   if (N0.getOpcode() == ISD::UNDEF)
01541     return N0;
01542   if (N1.getOpcode() == ISD::UNDEF)
01543     return N1;
01544   // fold (add c1, c2) -> c1+c2
01545   if (N0C && N1C)
01546     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
01547   // canonicalize constant to RHS
01548   if (N0C && !N1C)
01549     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
01550   // fold (add x, 0) -> x
01551   if (N1C && N1C->isNullValue())
01552     return N0;
01553   // fold (add Sym, c) -> Sym+c
01554   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
01555     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
01556         GA->getOpcode() == ISD::GlobalAddress)
01557       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
01558                                   GA->getOffset() +
01559                                     (uint64_t)N1C->getSExtValue());
01560   // fold ((c1-A)+c2) -> (c1+c2)-A
01561   if (N1C && N0.getOpcode() == ISD::SUB)
01562     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
01563       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
01564                          DAG.getConstant(N1C->getAPIntValue()+
01565                                          N0C->getAPIntValue(), VT),
01566                          N0.getOperand(1));
01567   // reassociate add
01568   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
01569   if (RADD.getNode())
01570     return RADD;
01571   // fold ((0-A) + B) -> B-A
01572   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
01573       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
01574     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
01575   // fold (A + (0-B)) -> A-B
01576   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
01577       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
01578     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
01579   // fold (A+(B-A)) -> B
01580   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
01581     return N1.getOperand(0);
01582   // fold ((B-A)+A) -> B
01583   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
01584     return N0.getOperand(0);
01585   // fold (A+(B-(A+C))) to (B-C)
01586   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01587       N0 == N1.getOperand(1).getOperand(0))
01588     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
01589                        N1.getOperand(1).getOperand(1));
01590   // fold (A+(B-(C+A))) to (B-C)
01591   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
01592       N0 == N1.getOperand(1).getOperand(1))
01593     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
01594                        N1.getOperand(1).getOperand(0));
01595   // fold (A+((B-A)+or-C)) to (B+or-C)
01596   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
01597       N1.getOperand(0).getOpcode() == ISD::SUB &&
01598       N0 == N1.getOperand(0).getOperand(1))
01599     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
01600                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
01601 
01602   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
01603   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
01604     SDValue N00 = N0.getOperand(0);
01605     SDValue N01 = N0.getOperand(1);
01606     SDValue N10 = N1.getOperand(0);
01607     SDValue N11 = N1.getOperand(1);
01608 
01609     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
01610       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
01611                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
01612                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
01613   }
01614 
01615   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
01616     return SDValue(N, 0);
01617 
01618   // fold (a+b) -> (a|b) iff a and b share no bits.
01619   if (VT.isInteger() && !VT.isVector()) {
01620     APInt LHSZero, LHSOne;
01621     APInt RHSZero, RHSOne;
01622     DAG.computeKnownBits(N0, LHSZero, LHSOne);
01623 
01624     if (LHSZero.getBoolValue()) {
01625       DAG.computeKnownBits(N1, RHSZero, RHSOne);
01626 
01627       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01628       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01629       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
01630         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
01631           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
01632       }
01633     }
01634   }
01635 
01636   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
01637   if (N1.getOpcode() == ISD::SHL &&
01638       N1.getOperand(0).getOpcode() == ISD::SUB)
01639     if (ConstantSDNode *C =
01640           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
01641       if (C->getAPIntValue() == 0)
01642         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
01643                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
01644                                        N1.getOperand(0).getOperand(1),
01645                                        N1.getOperand(1)));
01646   if (N0.getOpcode() == ISD::SHL &&
01647       N0.getOperand(0).getOpcode() == ISD::SUB)
01648     if (ConstantSDNode *C =
01649           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
01650       if (C->getAPIntValue() == 0)
01651         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
01652                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
01653                                        N0.getOperand(0).getOperand(1),
01654                                        N0.getOperand(1)));
01655 
01656   if (N1.getOpcode() == ISD::AND) {
01657     SDValue AndOp0 = N1.getOperand(0);
01658     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
01659     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
01660     unsigned DestBits = VT.getScalarType().getSizeInBits();
01661 
01662     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
01663     // and similar xforms where the inner op is either ~0 or 0.
01664     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
01665       SDLoc DL(N);
01666       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
01667     }
01668   }
01669 
01670   // add (sext i1), X -> sub X, (zext i1)
01671   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
01672       N0.getOperand(0).getValueType() == MVT::i1 &&
01673       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
01674     SDLoc DL(N);
01675     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
01676     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
01677   }
01678 
01679   return SDValue();
01680 }
01681 
01682 SDValue DAGCombiner::visitADDC(SDNode *N) {
01683   SDValue N0 = N->getOperand(0);
01684   SDValue N1 = N->getOperand(1);
01685   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01686   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01687   EVT VT = N0.getValueType();
01688 
01689   // If the flag result is dead, turn this into an ADD.
01690   if (!N->hasAnyUseOfValue(1))
01691     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
01692                      DAG.getNode(ISD::CARRY_FALSE,
01693                                  SDLoc(N), MVT::Glue));
01694 
01695   // canonicalize constant to RHS.
01696   if (N0C && !N1C)
01697     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
01698 
01699   // fold (addc x, 0) -> x + no carry out
01700   if (N1C && N1C->isNullValue())
01701     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
01702                                         SDLoc(N), MVT::Glue));
01703 
01704   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
01705   APInt LHSZero, LHSOne;
01706   APInt RHSZero, RHSOne;
01707   DAG.computeKnownBits(N0, LHSZero, LHSOne);
01708 
01709   if (LHSZero.getBoolValue()) {
01710     DAG.computeKnownBits(N1, RHSZero, RHSOne);
01711 
01712     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
01713     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
01714     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
01715       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
01716                        DAG.getNode(ISD::CARRY_FALSE,
01717                                    SDLoc(N), MVT::Glue));
01718   }
01719 
01720   return SDValue();
01721 }
01722 
01723 SDValue DAGCombiner::visitADDE(SDNode *N) {
01724   SDValue N0 = N->getOperand(0);
01725   SDValue N1 = N->getOperand(1);
01726   SDValue CarryIn = N->getOperand(2);
01727   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01728   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01729 
01730   // canonicalize constant to RHS
01731   if (N0C && !N1C)
01732     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
01733                        N1, N0, CarryIn);
01734 
01735   // fold (adde x, y, false) -> (addc x, y)
01736   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
01737     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
01738 
01739   return SDValue();
01740 }
01741 
01742 // Since it may not be valid to emit a fold to zero for vector initializers
01743 // check if we can before folding.
01744 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
01745                              SelectionDAG &DAG,
01746                              bool LegalOperations, bool LegalTypes) {
01747   if (!VT.isVector())
01748     return DAG.getConstant(0, VT);
01749   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
01750     return DAG.getConstant(0, VT);
01751   return SDValue();
01752 }
01753 
01754 SDValue DAGCombiner::visitSUB(SDNode *N) {
01755   SDValue N0 = N->getOperand(0);
01756   SDValue N1 = N->getOperand(1);
01757   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
01758   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
01759   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
01760     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
01761   EVT VT = N0.getValueType();
01762 
01763   // fold vector ops
01764   if (VT.isVector()) {
01765     SDValue FoldedVOp = SimplifyVBinOp(N);
01766     if (FoldedVOp.getNode()) return FoldedVOp;
01767 
01768     // fold (sub x, 0) -> x, vector edition
01769     if (ISD::isBuildVectorAllZeros(N1.getNode()))
01770       return N0;
01771   }
01772 
01773   // fold (sub x, x) -> 0
01774   // FIXME: Refactor this and xor and other similar operations together.
01775   if (N0 == N1)
01776     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
01777   // fold (sub c1, c2) -> c1-c2
01778   if (N0C && N1C)
01779     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
01780   // fold (sub x, c) -> (add x, -c)
01781   if (N1C)
01782     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
01783                        DAG.getConstant(-N1C->getAPIntValue(), VT));
01784   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
01785   if (N0C && N0C->isAllOnesValue())
01786     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
01787   // fold A-(A-B) -> B
01788   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
01789     return N1.getOperand(1);
01790   // fold (A+B)-A -> B
01791   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
01792     return N0.getOperand(1);
01793   // fold (A+B)-B -> A
01794   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
01795     return N0.getOperand(0);
01796   // fold C2-(A+C1) -> (C2-C1)-A
01797   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
01798     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
01799                                    VT);
01800     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
01801                        N1.getOperand(0));
01802   }
01803   // fold ((A+(B+or-C))-B) -> A+or-C
01804   if (N0.getOpcode() == ISD::ADD &&
01805       (N0.getOperand(1).getOpcode() == ISD::SUB ||
01806        N0.getOperand(1).getOpcode() == ISD::ADD) &&
01807       N0.getOperand(1).getOperand(0) == N1)
01808     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
01809                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
01810   // fold ((A+(C+B))-B) -> A+C
01811   if (N0.getOpcode() == ISD::ADD &&
01812       N0.getOperand(1).getOpcode() == ISD::ADD &&
01813       N0.getOperand(1).getOperand(1) == N1)
01814     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
01815                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01816   // fold ((A-(B-C))-C) -> A-B
01817   if (N0.getOpcode() == ISD::SUB &&
01818       N0.getOperand(1).getOpcode() == ISD::SUB &&
01819       N0.getOperand(1).getOperand(1) == N1)
01820     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
01821                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
01822 
01823   // If either operand of a sub is undef, the result is undef
01824   if (N0.getOpcode() == ISD::UNDEF)
01825     return N0;
01826   if (N1.getOpcode() == ISD::UNDEF)
01827     return N1;
01828 
01829   // If the relocation model supports it, consider symbol offsets.
01830   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
01831     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
01832       // fold (sub Sym, c) -> Sym-c
01833       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
01834         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
01835                                     GA->getOffset() -
01836                                       (uint64_t)N1C->getSExtValue());
01837       // fold (sub Sym+c1, Sym+c2) -> c1-c2
01838       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
01839         if (GA->getGlobal() == GB->getGlobal())
01840           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
01841                                  VT);
01842     }
01843 
01844   return SDValue();
01845 }
01846 
01847 SDValue DAGCombiner::visitSUBC(SDNode *N) {
01848   SDValue N0 = N->getOperand(0);
01849   SDValue N1 = N->getOperand(1);
01850   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
01851   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
01852   EVT VT = N0.getValueType();
01853 
01854   // If the flag result is dead, turn this into an SUB.
01855   if (!N->hasAnyUseOfValue(1))
01856     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
01857                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
01858                                  MVT::Glue));
01859 
01860   // fold (subc x, x) -> 0 + no borrow
01861   if (N0 == N1)
01862     return CombineTo(N, DAG.getConstant(0, VT),
01863                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
01864                                  MVT::Glue));
01865 
01866   // fold (subc x, 0) -> x + no borrow
01867   if (N1C && N1C->isNullValue())
01868     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
01869                                         MVT::Glue));
01870 
01871   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
01872   if (N0C && N0C->isAllOnesValue())
01873     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
01874                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
01875                                  MVT::Glue));
01876 
01877   return SDValue();
01878 }
01879 
01880 SDValue DAGCombiner::visitSUBE(SDNode *N) {
01881   SDValue N0 = N->getOperand(0);
01882   SDValue N1 = N->getOperand(1);
01883   SDValue CarryIn = N->getOperand(2);
01884 
01885   // fold (sube x, y, false) -> (subc x, y)
01886   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
01887     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
01888 
01889   return SDValue();
01890 }
01891 
01892 SDValue DAGCombiner::visitMUL(SDNode *N) {
01893   SDValue N0 = N->getOperand(0);
01894   SDValue N1 = N->getOperand(1);
01895   EVT VT = N0.getValueType();
01896 
01897   // fold (mul x, undef) -> 0
01898   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
01899     return DAG.getConstant(0, VT);
01900 
01901   bool N0IsConst = false;
01902   bool N1IsConst = false;
01903   APInt ConstValue0, ConstValue1;
01904   // fold vector ops
01905   if (VT.isVector()) {
01906     SDValue FoldedVOp = SimplifyVBinOp(N);
01907     if (FoldedVOp.getNode()) return FoldedVOp;
01908 
01909     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
01910     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
01911   } else {
01912     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
01913     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
01914                             : APInt();
01915     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
01916     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
01917                             : APInt();
01918   }
01919 
01920   // fold (mul c1, c2) -> c1*c2
01921   if (N0IsConst && N1IsConst)
01922     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
01923 
01924   // canonicalize constant to RHS
01925   if (N0IsConst && !N1IsConst)
01926     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
01927   // fold (mul x, 0) -> 0
01928   if (N1IsConst && ConstValue1 == 0)
01929     return N1;
01930   // We require a splat of the entire scalar bit width for non-contiguous
01931   // bit patterns.
01932   bool IsFullSplat =
01933     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
01934   // fold (mul x, 1) -> x
01935   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
01936     return N0;
01937   // fold (mul x, -1) -> 0-x
01938   if (N1IsConst && ConstValue1.isAllOnesValue())
01939     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
01940                        DAG.getConstant(0, VT), N0);
01941   // fold (mul x, (1 << c)) -> x << c
01942   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
01943     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
01944                        DAG.getConstant(ConstValue1.logBase2(),
01945                                        getShiftAmountTy(N0.getValueType())));
01946   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
01947   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
01948     unsigned Log2Val = (-ConstValue1).logBase2();
01949     // FIXME: If the input is something that is easily negated (e.g. a
01950     // single-use add), we should put the negate there.
01951     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
01952                        DAG.getConstant(0, VT),
01953                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
01954                             DAG.getConstant(Log2Val,
01955                                       getShiftAmountTy(N0.getValueType()))));
01956   }
01957 
01958   APInt Val;
01959   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
01960   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
01961       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
01962                      isa<ConstantSDNode>(N0.getOperand(1)))) {
01963     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
01964                              N1, N0.getOperand(1));
01965     AddToWorklist(C3.getNode());
01966     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
01967                        N0.getOperand(0), C3);
01968   }
01969 
01970   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
01971   // use.
01972   {
01973     SDValue Sh(nullptr,0), Y(nullptr,0);
01974     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
01975     if (N0.getOpcode() == ISD::SHL &&
01976         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
01977                        isa<ConstantSDNode>(N0.getOperand(1))) &&
01978         N0.getNode()->hasOneUse()) {
01979       Sh = N0; Y = N1;
01980     } else if (N1.getOpcode() == ISD::SHL &&
01981                isa<ConstantSDNode>(N1.getOperand(1)) &&
01982                N1.getNode()->hasOneUse()) {
01983       Sh = N1; Y = N0;
01984     }
01985 
01986     if (Sh.getNode()) {
01987       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
01988                                 Sh.getOperand(0), Y);
01989       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
01990                          Mul, Sh.getOperand(1));
01991     }
01992   }
01993 
01994   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
01995   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
01996       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
01997                      isa<ConstantSDNode>(N0.getOperand(1))))
01998     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
01999                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
02000                                    N0.getOperand(0), N1),
02001                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
02002                                    N0.getOperand(1), N1));
02003 
02004   // reassociate mul
02005   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
02006   if (RMUL.getNode())
02007     return RMUL;
02008 
02009   return SDValue();
02010 }
02011 
02012 SDValue DAGCombiner::visitSDIV(SDNode *N) {
02013   SDValue N0 = N->getOperand(0);
02014   SDValue N1 = N->getOperand(1);
02015   ConstantSDNode *N0C = isConstOrConstSplat(N0);
02016   ConstantSDNode *N1C = isConstOrConstSplat(N1);
02017   EVT VT = N->getValueType(0);
02018 
02019   // fold vector ops
02020   if (VT.isVector()) {
02021     SDValue FoldedVOp = SimplifyVBinOp(N);
02022     if (FoldedVOp.getNode()) return FoldedVOp;
02023   }
02024 
02025   // fold (sdiv c1, c2) -> c1/c2
02026   if (N0C && N1C && !N1C->isNullValue())
02027     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
02028   // fold (sdiv X, 1) -> X
02029   if (N1C && N1C->getAPIntValue() == 1LL)
02030     return N0;
02031   // fold (sdiv X, -1) -> 0-X
02032   if (N1C && N1C->isAllOnesValue())
02033     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
02034                        DAG.getConstant(0, VT), N0);
02035   // If we know the sign bits of both operands are zero, strength reduce to a
02036   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
02037   if (!VT.isVector()) {
02038     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
02039       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
02040                          N0, N1);
02041   }
02042 
02043   // fold (sdiv X, pow2) -> simple ops after legalize
02044   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
02045                                      (-N1C->getAPIntValue()).isPowerOf2())) {
02046     // If dividing by powers of two is cheap, then don't perform the following
02047     // fold.
02048     if (TLI.isPow2SDivCheap())
02049       return SDValue();
02050 
02051     // Target-specific implementation of sdiv x, pow2.
02052     SDValue Res = BuildSDIVPow2(N);
02053     if (Res.getNode())
02054       return Res;
02055 
02056     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
02057 
02058     // Splat the sign bit into the register
02059     SDValue SGN =
02060         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
02061                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
02062                                     getShiftAmountTy(N0.getValueType())));
02063     AddToWorklist(SGN.getNode());
02064 
02065     // Add (N0 < 0) ? abs2 - 1 : 0;
02066     SDValue SRL =
02067         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
02068                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
02069                                     getShiftAmountTy(SGN.getValueType())));
02070     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
02071     AddToWorklist(SRL.getNode());
02072     AddToWorklist(ADD.getNode());    // Divide by pow2
02073     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
02074                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
02075 
02076     // If we're dividing by a positive value, we're done.  Otherwise, we must
02077     // negate the result.
02078     if (N1C->getAPIntValue().isNonNegative())
02079       return SRA;
02080 
02081     AddToWorklist(SRA.getNode());
02082     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
02083   }
02084 
02085   // if integer divide is expensive and we satisfy the requirements, emit an
02086   // alternate sequence.
02087   if (N1C && !TLI.isIntDivCheap()) {
02088     SDValue Op = BuildSDIV(N);
02089     if (Op.getNode()) return Op;
02090   }
02091 
02092   // undef / X -> 0
02093   if (N0.getOpcode() == ISD::UNDEF)
02094     return DAG.getConstant(0, VT);
02095   // X / undef -> undef
02096   if (N1.getOpcode() == ISD::UNDEF)
02097     return N1;
02098 
02099   return SDValue();
02100 }
02101 
02102 SDValue DAGCombiner::visitUDIV(SDNode *N) {
02103   SDValue N0 = N->getOperand(0);
02104   SDValue N1 = N->getOperand(1);
02105   ConstantSDNode *N0C = isConstOrConstSplat(N0);
02106   ConstantSDNode *N1C = isConstOrConstSplat(N1);
02107   EVT VT = N->getValueType(0);
02108 
02109   // fold vector ops
02110   if (VT.isVector()) {
02111     SDValue FoldedVOp = SimplifyVBinOp(N);
02112     if (FoldedVOp.getNode()) return FoldedVOp;
02113   }
02114 
02115   // fold (udiv c1, c2) -> c1/c2
02116   if (N0C && N1C && !N1C->isNullValue())
02117     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
02118   // fold (udiv x, (1 << c)) -> x >>u c
02119   if (N1C && N1C->getAPIntValue().isPowerOf2())
02120     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
02121                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
02122                                        getShiftAmountTy(N0.getValueType())));
02123   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
02124   if (N1.getOpcode() == ISD::SHL) {
02125     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
02126       if (SHC->getAPIntValue().isPowerOf2()) {
02127         EVT ADDVT = N1.getOperand(1).getValueType();
02128         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
02129                                   N1.getOperand(1),
02130                                   DAG.getConstant(SHC->getAPIntValue()
02131                                                                   .logBase2(),
02132                                                   ADDVT));
02133         AddToWorklist(Add.getNode());
02134         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
02135       }
02136     }
02137   }
02138   // fold (udiv x, c) -> alternate
02139   if (N1C && !TLI.isIntDivCheap()) {
02140     SDValue Op = BuildUDIV(N);
02141     if (Op.getNode()) return Op;
02142   }
02143 
02144   // undef / X -> 0
02145   if (N0.getOpcode() == ISD::UNDEF)
02146     return DAG.getConstant(0, VT);
02147   // X / undef -> undef
02148   if (N1.getOpcode() == ISD::UNDEF)
02149     return N1;
02150 
02151   return SDValue();
02152 }
02153 
02154 SDValue DAGCombiner::visitSREM(SDNode *N) {
02155   SDValue N0 = N->getOperand(0);
02156   SDValue N1 = N->getOperand(1);
02157   ConstantSDNode *N0C = isConstOrConstSplat(N0);
02158   ConstantSDNode *N1C = isConstOrConstSplat(N1);
02159   EVT VT = N->getValueType(0);
02160 
02161   // fold (srem c1, c2) -> c1%c2
02162   if (N0C && N1C && !N1C->isNullValue())
02163     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
02164   // If we know the sign bits of both operands are zero, strength reduce to a
02165   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
02166   if (!VT.isVector()) {
02167     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
02168       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
02169   }
02170 
02171   // If X/C can be simplified by the division-by-constant logic, lower
02172   // X%C to the equivalent of X-X/C*C.
02173   if (N1C && !N1C->isNullValue()) {
02174     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
02175     AddToWorklist(Div.getNode());
02176     SDValue OptimizedDiv = combine(Div.getNode());
02177     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
02178       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
02179                                 OptimizedDiv, N1);
02180       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
02181       AddToWorklist(Mul.getNode());
02182       return Sub;
02183     }
02184   }
02185 
02186   // undef % X -> 0
02187   if (N0.getOpcode() == ISD::UNDEF)
02188     return DAG.getConstant(0, VT);
02189   // X % undef -> undef
02190   if (N1.getOpcode() == ISD::UNDEF)
02191     return N1;
02192 
02193   return SDValue();
02194 }
02195 
02196 SDValue DAGCombiner::visitUREM(SDNode *N) {
02197   SDValue N0 = N->getOperand(0);
02198   SDValue N1 = N->getOperand(1);
02199   ConstantSDNode *N0C = isConstOrConstSplat(N0);
02200   ConstantSDNode *N1C = isConstOrConstSplat(N1);
02201   EVT VT = N->getValueType(0);
02202 
02203   // fold (urem c1, c2) -> c1%c2
02204   if (N0C && N1C && !N1C->isNullValue())
02205     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
02206   // fold (urem x, pow2) -> (and x, pow2-1)
02207   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
02208     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
02209                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
02210   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
02211   if (N1.getOpcode() == ISD::SHL) {
02212     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
02213       if (SHC->getAPIntValue().isPowerOf2()) {
02214         SDValue Add =
02215           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
02216                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
02217                                  VT));
02218         AddToWorklist(Add.getNode());
02219         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
02220       }
02221     }
02222   }
02223 
02224   // If X/C can be simplified by the division-by-constant logic, lower
02225   // X%C to the equivalent of X-X/C*C.
02226   if (N1C && !N1C->isNullValue()) {
02227     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
02228     AddToWorklist(Div.getNode());
02229     SDValue OptimizedDiv = combine(Div.getNode());
02230     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
02231       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
02232                                 OptimizedDiv, N1);
02233       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
02234       AddToWorklist(Mul.getNode());
02235       return Sub;
02236     }
02237   }
02238 
02239   // undef % X -> 0
02240   if (N0.getOpcode() == ISD::UNDEF)
02241     return DAG.getConstant(0, VT);
02242   // X % undef -> undef
02243   if (N1.getOpcode() == ISD::UNDEF)
02244     return N1;
02245 
02246   return SDValue();
02247 }
02248 
02249 SDValue DAGCombiner::visitMULHS(SDNode *N) {
02250   SDValue N0 = N->getOperand(0);
02251   SDValue N1 = N->getOperand(1);
02252   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02253   EVT VT = N->getValueType(0);
02254   SDLoc DL(N);
02255 
02256   // fold (mulhs x, 0) -> 0
02257   if (N1C && N1C->isNullValue())
02258     return N1;
02259   // fold (mulhs x, 1) -> (sra x, size(x)-1)
02260   if (N1C && N1C->getAPIntValue() == 1)
02261     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
02262                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
02263                                        getShiftAmountTy(N0.getValueType())));
02264   // fold (mulhs x, undef) -> 0
02265   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
02266     return DAG.getConstant(0, VT);
02267 
02268   // If the type twice as wide is legal, transform the mulhs to a wider multiply
02269   // plus a shift.
02270   if (VT.isSimple() && !VT.isVector()) {
02271     MVT Simple = VT.getSimpleVT();
02272     unsigned SimpleSize = Simple.getSizeInBits();
02273     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
02274     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
02275       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
02276       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
02277       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
02278       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
02279             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
02280       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
02281     }
02282   }
02283 
02284   return SDValue();
02285 }
02286 
02287 SDValue DAGCombiner::visitMULHU(SDNode *N) {
02288   SDValue N0 = N->getOperand(0);
02289   SDValue N1 = N->getOperand(1);
02290   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02291   EVT VT = N->getValueType(0);
02292   SDLoc DL(N);
02293 
02294   // fold (mulhu x, 0) -> 0
02295   if (N1C && N1C->isNullValue())
02296     return N1;
02297   // fold (mulhu x, 1) -> 0
02298   if (N1C && N1C->getAPIntValue() == 1)
02299     return DAG.getConstant(0, N0.getValueType());
02300   // fold (mulhu x, undef) -> 0
02301   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
02302     return DAG.getConstant(0, VT);
02303 
02304   // If the type twice as wide is legal, transform the mulhu to a wider multiply
02305   // plus a shift.
02306   if (VT.isSimple() && !VT.isVector()) {
02307     MVT Simple = VT.getSimpleVT();
02308     unsigned SimpleSize = Simple.getSizeInBits();
02309     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
02310     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
02311       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
02312       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
02313       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
02314       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
02315             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
02316       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
02317     }
02318   }
02319 
02320   return SDValue();
02321 }
02322 
02323 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
02324 /// give the opcodes for the two computations that are being performed. Return
02325 /// true if a simplification was made.
02326 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
02327                                                 unsigned HiOp) {
02328   // If the high half is not needed, just compute the low half.
02329   bool HiExists = N->hasAnyUseOfValue(1);
02330   if (!HiExists &&
02331       (!LegalOperations ||
02332        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
02333     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
02334     return CombineTo(N, Res, Res);
02335   }
02336 
02337   // If the low half is not needed, just compute the high half.
02338   bool LoExists = N->hasAnyUseOfValue(0);
02339   if (!LoExists &&
02340       (!LegalOperations ||
02341        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
02342     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
02343     return CombineTo(N, Res, Res);
02344   }
02345 
02346   // If both halves are used, return as it is.
02347   if (LoExists && HiExists)
02348     return SDValue();
02349 
02350   // If the two computed results can be simplified separately, separate them.
02351   if (LoExists) {
02352     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
02353     AddToWorklist(Lo.getNode());
02354     SDValue LoOpt = combine(Lo.getNode());
02355     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
02356         (!LegalOperations ||
02357          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
02358       return CombineTo(N, LoOpt, LoOpt);
02359   }
02360 
02361   if (HiExists) {
02362     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
02363     AddToWorklist(Hi.getNode());
02364     SDValue HiOpt = combine(Hi.getNode());
02365     if (HiOpt.getNode() && HiOpt != Hi &&
02366         (!LegalOperations ||
02367          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
02368       return CombineTo(N, HiOpt, HiOpt);
02369   }
02370 
02371   return SDValue();
02372 }
02373 
02374 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
02375   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
02376   if (Res.getNode()) return Res;
02377 
02378   EVT VT = N->getValueType(0);
02379   SDLoc DL(N);
02380 
02381   // If the type twice as wide is legal, transform the mulhu to a wider multiply
02382   // plus a shift.
02383   if (VT.isSimple() && !VT.isVector()) {
02384     MVT Simple = VT.getSimpleVT();
02385     unsigned SimpleSize = Simple.getSizeInBits();
02386     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
02387     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
02388       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
02389       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
02390       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
02391       // Compute the high part as N1.
02392       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
02393             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
02394       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
02395       // Compute the low part as N0.
02396       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
02397       return CombineTo(N, Lo, Hi);
02398     }
02399   }
02400 
02401   return SDValue();
02402 }
02403 
02404 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
02405   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
02406   if (Res.getNode()) return Res;
02407 
02408   EVT VT = N->getValueType(0);
02409   SDLoc DL(N);
02410 
02411   // If the type twice as wide is legal, transform the mulhu to a wider multiply
02412   // plus a shift.
02413   if (VT.isSimple() && !VT.isVector()) {
02414     MVT Simple = VT.getSimpleVT();
02415     unsigned SimpleSize = Simple.getSizeInBits();
02416     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
02417     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
02418       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
02419       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
02420       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
02421       // Compute the high part as N1.
02422       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
02423             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
02424       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
02425       // Compute the low part as N0.
02426       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
02427       return CombineTo(N, Lo, Hi);
02428     }
02429   }
02430 
02431   return SDValue();
02432 }
02433 
02434 SDValue DAGCombiner::visitSMULO(SDNode *N) {
02435   // (smulo x, 2) -> (saddo x, x)
02436   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
02437     if (C2->getAPIntValue() == 2)
02438       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
02439                          N->getOperand(0), N->getOperand(0));
02440 
02441   return SDValue();
02442 }
02443 
02444 SDValue DAGCombiner::visitUMULO(SDNode *N) {
02445   // (umulo x, 2) -> (uaddo x, x)
02446   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
02447     if (C2->getAPIntValue() == 2)
02448       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
02449                          N->getOperand(0), N->getOperand(0));
02450 
02451   return SDValue();
02452 }
02453 
02454 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
02455   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
02456   if (Res.getNode()) return Res;
02457 
02458   return SDValue();
02459 }
02460 
02461 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
02462   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
02463   if (Res.getNode()) return Res;
02464 
02465   return SDValue();
02466 }
02467 
02468 /// If this is a binary operator with two operands of the same opcode, try to
02469 /// simplify it.
02470 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
02471   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
02472   EVT VT = N0.getValueType();
02473   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
02474 
02475   // Bail early if none of these transforms apply.
02476   if (N0.getNode()->getNumOperands() == 0) return SDValue();
02477 
02478   // For each of OP in AND/OR/XOR:
02479   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
02480   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
02481   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
02482   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
02483   //
02484   // do not sink logical op inside of a vector extend, since it may combine
02485   // into a vsetcc.
02486   EVT Op0VT = N0.getOperand(0).getValueType();
02487   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
02488        N0.getOpcode() == ISD::SIGN_EXTEND ||
02489        // Avoid infinite looping with PromoteIntBinOp.
02490        (N0.getOpcode() == ISD::ANY_EXTEND &&
02491         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
02492        (N0.getOpcode() == ISD::TRUNCATE &&
02493         (!TLI.isZExtFree(VT, Op0VT) ||
02494          !TLI.isTruncateFree(Op0VT, VT)) &&
02495         TLI.isTypeLegal(Op0VT))) &&
02496       !VT.isVector() &&
02497       Op0VT == N1.getOperand(0).getValueType() &&
02498       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
02499     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
02500                                  N0.getOperand(0).getValueType(),
02501                                  N0.getOperand(0), N1.getOperand(0));
02502     AddToWorklist(ORNode.getNode());
02503     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
02504   }
02505 
02506   // For each of OP in SHL/SRL/SRA/AND...
02507   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
02508   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
02509   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
02510   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
02511        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
02512       N0.getOperand(1) == N1.getOperand(1)) {
02513     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
02514                                  N0.getOperand(0).getValueType(),
02515                                  N0.getOperand(0), N1.getOperand(0));
02516     AddToWorklist(ORNode.getNode());
02517     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
02518                        ORNode, N0.getOperand(1));
02519   }
02520 
02521   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
02522   // Only perform this optimization after type legalization and before
02523   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
02524   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
02525   // we don't want to undo this promotion.
02526   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
02527   // on scalars.
02528   if ((N0.getOpcode() == ISD::BITCAST ||
02529        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
02530       Level == AfterLegalizeTypes) {
02531     SDValue In0 = N0.getOperand(0);
02532     SDValue In1 = N1.getOperand(0);
02533     EVT In0Ty = In0.getValueType();
02534     EVT In1Ty = In1.getValueType();
02535     SDLoc DL(N);
02536     // If both incoming values are integers, and the original types are the
02537     // same.
02538     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
02539       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
02540       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
02541       AddToWorklist(Op.getNode());
02542       return BC;
02543     }
02544   }
02545 
02546   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
02547   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
02548   // If both shuffles use the same mask, and both shuffle within a single
02549   // vector, then it is worthwhile to move the swizzle after the operation.
02550   // The type-legalizer generates this pattern when loading illegal
02551   // vector types from memory. In many cases this allows additional shuffle
02552   // optimizations.
02553   // There are other cases where moving the shuffle after the xor/and/or
02554   // is profitable even if shuffles don't perform a swizzle.
02555   // If both shuffles use the same mask, and both shuffles have the same first
02556   // or second operand, then it might still be profitable to move the shuffle
02557   // after the xor/and/or operation.
02558   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
02559     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
02560     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
02561 
02562     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
02563            "Inputs to shuffles are not the same type");
02564 
02565     // Check that both shuffles use the same mask. The masks are known to be of
02566     // the same length because the result vector type is the same.
02567     // Check also that shuffles have only one use to avoid introducing extra
02568     // instructions.
02569     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
02570         SVN0->getMask().equals(SVN1->getMask())) {
02571       SDValue ShOp = N0->getOperand(1);
02572 
02573       // Don't try to fold this node if it requires introducing a
02574       // build vector of all zeros that might be illegal at this stage.
02575       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
02576         if (!LegalTypes)
02577           ShOp = DAG.getConstant(0, VT);
02578         else
02579           ShOp = SDValue();
02580       }
02581 
02582       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
02583       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
02584       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
02585       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
02586         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
02587                                       N0->getOperand(0), N1->getOperand(0));
02588         AddToWorklist(NewNode.getNode());
02589         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
02590                                     &SVN0->getMask()[0]);
02591       }
02592 
02593       // Don't try to fold this node if it requires introducing a
02594       // build vector of all zeros that might be illegal at this stage.
02595       ShOp = N0->getOperand(0);
02596       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
02597         if (!LegalTypes)
02598           ShOp = DAG.getConstant(0, VT);
02599         else
02600           ShOp = SDValue();
02601       }
02602 
02603       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
02604       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
02605       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
02606       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
02607         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
02608                                       N0->getOperand(1), N1->getOperand(1));
02609         AddToWorklist(NewNode.getNode());
02610         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
02611                                     &SVN0->getMask()[0]);
02612       }
02613     }
02614   }
02615 
02616   return SDValue();
02617 }
02618 
02619 SDValue DAGCombiner::visitAND(SDNode *N) {
02620   SDValue N0 = N->getOperand(0);
02621   SDValue N1 = N->getOperand(1);
02622   SDValue LL, LR, RL, RR, CC0, CC1;
02623   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
02624   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
02625   EVT VT = N1.getValueType();
02626   unsigned BitWidth = VT.getScalarType().getSizeInBits();
02627 
02628   // fold vector ops
02629   if (VT.isVector()) {
02630     SDValue FoldedVOp = SimplifyVBinOp(N);
02631     if (FoldedVOp.getNode()) return FoldedVOp;
02632 
02633     // fold (and x, 0) -> 0, vector edition
02634     if (ISD::isBuildVectorAllZeros(N0.getNode()))
02635       // do not return N0, because undef node may exist in N0
02636       return DAG.getConstant(
02637           APInt::getNullValue(
02638               N0.getValueType().getScalarType().getSizeInBits()),
02639           N0.getValueType());
02640     if (ISD::isBuildVectorAllZeros(N1.getNode()))
02641       // do not return N1, because undef node may exist in N1
02642       return DAG.getConstant(
02643           APInt::getNullValue(
02644               N1.getValueType().getScalarType().getSizeInBits()),
02645           N1.getValueType());
02646 
02647     // fold (and x, -1) -> x, vector edition
02648     if (ISD::isBuildVectorAllOnes(N0.getNode()))
02649       return N1;
02650     if (ISD::isBuildVectorAllOnes(N1.getNode()))
02651       return N0;
02652   }
02653 
02654   // fold (and x, undef) -> 0
02655   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
02656     return DAG.getConstant(0, VT);
02657   // fold (and c1, c2) -> c1&c2
02658   if (N0C && N1C)
02659     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
02660   // canonicalize constant to RHS
02661   if (N0C && !N1C)
02662     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
02663   // fold (and x, -1) -> x
02664   if (N1C && N1C->isAllOnesValue())
02665     return N0;
02666   // if (and x, c) is known to be zero, return 0
02667   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
02668                                    APInt::getAllOnesValue(BitWidth)))
02669     return DAG.getConstant(0, VT);
02670   // reassociate and
02671   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
02672   if (RAND.getNode())
02673     return RAND;
02674   // fold (and (or x, C), D) -> D if (C & D) == D
02675   if (N1C && N0.getOpcode() == ISD::OR)
02676     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
02677       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
02678         return N1;
02679   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
02680   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
02681     SDValue N0Op0 = N0.getOperand(0);
02682     APInt Mask = ~N1C->getAPIntValue();
02683     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
02684     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
02685       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
02686                                  N0.getValueType(), N0Op0);
02687 
02688       // Replace uses of the AND with uses of the Zero extend node.
02689       CombineTo(N, Zext);
02690 
02691       // We actually want to replace all uses of the any_extend with the
02692       // zero_extend, to avoid duplicating things.  This will later cause this
02693       // AND to be folded.
02694       CombineTo(N0.getNode(), Zext);
02695       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02696     }
02697   }
02698   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
02699   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
02700   // already be zero by virtue of the width of the base type of the load.
02701   //
02702   // the 'X' node here can either be nothing or an extract_vector_elt to catch
02703   // more cases.
02704   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
02705        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
02706       N0.getOpcode() == ISD::LOAD) {
02707     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
02708                                          N0 : N0.getOperand(0) );
02709 
02710     // Get the constant (if applicable) the zero'th operand is being ANDed with.
02711     // This can be a pure constant or a vector splat, in which case we treat the
02712     // vector as a scalar and use the splat value.
02713     APInt Constant = APInt::getNullValue(1);
02714     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
02715       Constant = C->getAPIntValue();
02716     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
02717       APInt SplatValue, SplatUndef;
02718       unsigned SplatBitSize;
02719       bool HasAnyUndefs;
02720       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
02721                                              SplatBitSize, HasAnyUndefs);
02722       if (IsSplat) {
02723         // Undef bits can contribute to a possible optimisation if set, so
02724         // set them.
02725         SplatValue |= SplatUndef;
02726 
02727         // The splat value may be something like "0x00FFFFFF", which means 0 for
02728         // the first vector value and FF for the rest, repeating. We need a mask
02729         // that will apply equally to all members of the vector, so AND all the
02730         // lanes of the constant together.
02731         EVT VT = Vector->getValueType(0);
02732         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
02733 
02734         // If the splat value has been compressed to a bitlength lower
02735         // than the size of the vector lane, we need to re-expand it to
02736         // the lane size.
02737         if (BitWidth > SplatBitSize)
02738           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
02739                SplatBitSize < BitWidth;
02740                SplatBitSize = SplatBitSize * 2)
02741             SplatValue |= SplatValue.shl(SplatBitSize);
02742 
02743         Constant = APInt::getAllOnesValue(BitWidth);
02744         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
02745           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
02746       }
02747     }
02748 
02749     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
02750     // actually legal and isn't going to get expanded, else this is a false
02751     // optimisation.
02752     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
02753                                                     Load->getMemoryVT());
02754 
02755     // Resize the constant to the same size as the original memory access before
02756     // extension. If it is still the AllOnesValue then this AND is completely
02757     // unneeded.
02758     Constant =
02759       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
02760 
02761     bool B;
02762     switch (Load->getExtensionType()) {
02763     default: B = false; break;
02764     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
02765     case ISD::ZEXTLOAD:
02766     case ISD::NON_EXTLOAD: B = true; break;
02767     }
02768 
02769     if (B && Constant.isAllOnesValue()) {
02770       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
02771       // preserve semantics once we get rid of the AND.
02772       SDValue NewLoad(Load, 0);
02773       if (Load->getExtensionType() == ISD::EXTLOAD) {
02774         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
02775                               Load->getValueType(0), SDLoc(Load),
02776                               Load->getChain(), Load->getBasePtr(),
02777                               Load->getOffset(), Load->getMemoryVT(),
02778                               Load->getMemOperand());
02779         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
02780         if (Load->getNumValues() == 3) {
02781           // PRE/POST_INC loads have 3 values.
02782           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
02783                            NewLoad.getValue(2) };
02784           CombineTo(Load, To, 3, true);
02785         } else {
02786           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
02787         }
02788       }
02789 
02790       // Fold the AND away, taking care not to fold to the old load node if we
02791       // replaced it.
02792       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
02793 
02794       return SDValue(N, 0); // Return N so it doesn't get rechecked!
02795     }
02796   }
02797   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
02798   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
02799     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
02800     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
02801 
02802     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
02803         LL.getValueType().isInteger()) {
02804       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
02805       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
02806         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
02807                                      LR.getValueType(), LL, RL);
02808         AddToWorklist(ORNode.getNode());
02809         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
02810       }
02811       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
02812       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
02813         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
02814                                       LR.getValueType(), LL, RL);
02815         AddToWorklist(ANDNode.getNode());
02816         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
02817       }
02818       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
02819       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
02820         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
02821                                      LR.getValueType(), LL, RL);
02822         AddToWorklist(ORNode.getNode());
02823         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
02824       }
02825     }
02826     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
02827     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
02828         Op0 == Op1 && LL.getValueType().isInteger() &&
02829       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
02830                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
02831                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
02832                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
02833       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
02834                                     LL, DAG.getConstant(1, LL.getValueType()));
02835       AddToWorklist(ADDNode.getNode());
02836       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
02837                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
02838     }
02839     // canonicalize equivalent to ll == rl
02840     if (LL == RR && LR == RL) {
02841       Op1 = ISD::getSetCCSwappedOperands(Op1);
02842       std::swap(RL, RR);
02843     }
02844     if (LL == RL && LR == RR) {
02845       bool isInteger = LL.getValueType().isInteger();
02846       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
02847       if (Result != ISD::SETCC_INVALID &&
02848           (!LegalOperations ||
02849            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
02850             TLI.isOperationLegal(ISD::SETCC,
02851                             getSetCCResultType(N0.getSimpleValueType())))))
02852         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
02853                             LL, LR, Result);
02854     }
02855   }
02856 
02857   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
02858   if (N0.getOpcode() == N1.getOpcode()) {
02859     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
02860     if (Tmp.getNode()) return Tmp;
02861   }
02862 
02863   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
02864   // fold (and (sra)) -> (and (srl)) when possible.
02865   if (!VT.isVector() &&
02866       SimplifyDemandedBits(SDValue(N, 0)))
02867     return SDValue(N, 0);
02868 
02869   // fold (zext_inreg (extload x)) -> (zextload x)
02870   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
02871     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
02872     EVT MemVT = LN0->getMemoryVT();
02873     // If we zero all the possible extended bits, then we can turn this into
02874     // a zextload if we are running before legalize or the operation is legal.
02875     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
02876     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
02877                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
02878         ((!LegalOperations && !LN0->isVolatile()) ||
02879          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
02880       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
02881                                        LN0->getChain(), LN0->getBasePtr(),
02882                                        MemVT, LN0->getMemOperand());
02883       AddToWorklist(N);
02884       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
02885       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02886     }
02887   }
02888   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
02889   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
02890       N0.hasOneUse()) {
02891     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
02892     EVT MemVT = LN0->getMemoryVT();
02893     // If we zero all the possible extended bits, then we can turn this into
02894     // a zextload if we are running before legalize or the operation is legal.
02895     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
02896     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
02897                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
02898         ((!LegalOperations && !LN0->isVolatile()) ||
02899          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
02900       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
02901                                        LN0->getChain(), LN0->getBasePtr(),
02902                                        MemVT, LN0->getMemOperand());
02903       AddToWorklist(N);
02904       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
02905       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02906     }
02907   }
02908 
02909   // fold (and (load x), 255) -> (zextload x, i8)
02910   // fold (and (extload x, i16), 255) -> (zextload x, i8)
02911   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
02912   if (N1C && (N0.getOpcode() == ISD::LOAD ||
02913               (N0.getOpcode() == ISD::ANY_EXTEND &&
02914                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
02915     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
02916     LoadSDNode *LN0 = HasAnyExt
02917       ? cast<LoadSDNode>(N0.getOperand(0))
02918       : cast<LoadSDNode>(N0);
02919     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
02920         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
02921       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
02922       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
02923         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
02924         EVT LoadedVT = LN0->getMemoryVT();
02925 
02926         if (ExtVT == LoadedVT &&
02927             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
02928           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
02929 
02930           SDValue NewLoad =
02931             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
02932                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
02933                            LN0->getMemOperand());
02934           AddToWorklist(N);
02935           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
02936           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02937         }
02938 
02939         // Do not change the width of a volatile load.
02940         // Do not generate loads of non-round integer types since these can
02941         // be expensive (and would be wrong if the type is not byte sized).
02942         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
02943             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
02944           EVT PtrType = LN0->getOperand(1).getValueType();
02945 
02946           unsigned Alignment = LN0->getAlignment();
02947           SDValue NewPtr = LN0->getBasePtr();
02948 
02949           // For big endian targets, we need to add an offset to the pointer
02950           // to load the correct bytes.  For little endian systems, we merely
02951           // need to read fewer bytes from the same pointer.
02952           if (TLI.isBigEndian()) {
02953             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
02954             unsigned EVTStoreBytes = ExtVT.getStoreSize();
02955             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
02956             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
02957                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
02958             Alignment = MinAlign(Alignment, PtrOff);
02959           }
02960 
02961           AddToWorklist(NewPtr.getNode());
02962 
02963           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
02964           SDValue Load =
02965             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
02966                            LN0->getChain(), NewPtr,
02967                            LN0->getPointerInfo(),
02968                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
02969                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
02970           AddToWorklist(N);
02971           CombineTo(LN0, Load, Load.getValue(1));
02972           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
02973         }
02974       }
02975     }
02976   }
02977 
02978   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
02979       VT.getSizeInBits() <= 64) {
02980     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
02981       APInt ADDC = ADDI->getAPIntValue();
02982       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
02983         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
02984         // immediate for an add, but it is legal if its top c2 bits are set,
02985         // transform the ADD so the immediate doesn't need to be materialized
02986         // in a register.
02987         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
02988           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
02989                                              SRLI->getZExtValue());
02990           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
02991             ADDC |= Mask;
02992             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
02993               SDValue NewAdd =
02994                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
02995                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
02996               CombineTo(N0.getNode(), NewAdd);
02997               return SDValue(N, 0); // Return N so it doesn't get rechecked!
02998             }
02999           }
03000         }
03001       }
03002     }
03003   }
03004 
03005   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
03006   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
03007     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
03008                                        N0.getOperand(1), false);
03009     if (BSwap.getNode())
03010       return BSwap;
03011   }
03012 
03013   return SDValue();
03014 }
03015 
03016 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
03017 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
03018                                         bool DemandHighBits) {
03019   if (!LegalOperations)
03020     return SDValue();
03021 
03022   EVT VT = N->getValueType(0);
03023   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
03024     return SDValue();
03025   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
03026     return SDValue();
03027 
03028   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
03029   bool LookPassAnd0 = false;
03030   bool LookPassAnd1 = false;
03031   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
03032       std::swap(N0, N1);
03033   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
03034       std::swap(N0, N1);
03035   if (N0.getOpcode() == ISD::AND) {
03036     if (!N0.getNode()->hasOneUse())
03037       return SDValue();
03038     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
03039     if (!N01C || N01C->getZExtValue() != 0xFF00)
03040       return SDValue();
03041     N0 = N0.getOperand(0);
03042     LookPassAnd0 = true;
03043   }
03044 
03045   if (N1.getOpcode() == ISD::AND) {
03046     if (!N1.getNode()->hasOneUse())
03047       return SDValue();
03048     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
03049     if (!N11C || N11C->getZExtValue() != 0xFF)
03050       return SDValue();
03051     N1 = N1.getOperand(0);
03052     LookPassAnd1 = true;
03053   }
03054 
03055   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
03056     std::swap(N0, N1);
03057   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
03058     return SDValue();
03059   if (!N0.getNode()->hasOneUse() ||
03060       !N1.getNode()->hasOneUse())
03061     return SDValue();
03062 
03063   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
03064   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
03065   if (!N01C || !N11C)
03066     return SDValue();
03067   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
03068     return SDValue();
03069 
03070   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
03071   SDValue N00 = N0->getOperand(0);
03072   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
03073     if (!N00.getNode()->hasOneUse())
03074       return SDValue();
03075     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
03076     if (!N001C || N001C->getZExtValue() != 0xFF)
03077       return SDValue();
03078     N00 = N00.getOperand(0);
03079     LookPassAnd0 = true;
03080   }
03081 
03082   SDValue N10 = N1->getOperand(0);
03083   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
03084     if (!N10.getNode()->hasOneUse())
03085       return SDValue();
03086     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
03087     if (!N101C || N101C->getZExtValue() != 0xFF00)
03088       return SDValue();
03089     N10 = N10.getOperand(0);
03090     LookPassAnd1 = true;
03091   }
03092 
03093   if (N00 != N10)
03094     return SDValue();
03095 
03096   // Make sure everything beyond the low halfword gets set to zero since the SRL
03097   // 16 will clear the top bits.
03098   unsigned OpSizeInBits = VT.getSizeInBits();
03099   if (DemandHighBits && OpSizeInBits > 16) {
03100     // If the left-shift isn't masked out then the only way this is a bswap is
03101     // if all bits beyond the low 8 are 0. In that case the entire pattern
03102     // reduces to a left shift anyway: leave it for other parts of the combiner.
03103     if (!LookPassAnd0)
03104       return SDValue();
03105 
03106     // However, if the right shift isn't masked out then it might be because
03107     // it's not needed. See if we can spot that too.
03108     if (!LookPassAnd1 &&
03109         !DAG.MaskedValueIsZero(
03110             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
03111       return SDValue();
03112   }
03113 
03114   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
03115   if (OpSizeInBits > 16)
03116     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
03117                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
03118   return Res;
03119 }
03120 
03121 /// Return true if the specified node is an element that makes up a 32-bit
03122 /// packed halfword byteswap.
03123 /// ((x & 0x000000ff) << 8) |
03124 /// ((x & 0x0000ff00) >> 8) |
03125 /// ((x & 0x00ff0000) << 8) |
03126 /// ((x & 0xff000000) >> 8)
03127 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
03128   if (!N.getNode()->hasOneUse())
03129     return false;
03130 
03131   unsigned Opc = N.getOpcode();
03132   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
03133     return false;
03134 
03135   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
03136   if (!N1C)
03137     return false;
03138 
03139   unsigned Num;
03140   switch (N1C->getZExtValue()) {
03141   default:
03142     return false;
03143   case 0xFF:       Num = 0; break;
03144   case 0xFF00:     Num = 1; break;
03145   case 0xFF0000:   Num = 2; break;
03146   case 0xFF000000: Num = 3; break;
03147   }
03148 
03149   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
03150   SDValue N0 = N.getOperand(0);
03151   if (Opc == ISD::AND) {
03152     if (Num == 0 || Num == 2) {
03153       // (x >> 8) & 0xff
03154       // (x >> 8) & 0xff0000
03155       if (N0.getOpcode() != ISD::SRL)
03156         return false;
03157       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
03158       if (!C || C->getZExtValue() != 8)
03159         return false;
03160     } else {
03161       // (x << 8) & 0xff00
03162       // (x << 8) & 0xff000000
03163       if (N0.getOpcode() != ISD::SHL)
03164         return false;
03165       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
03166       if (!C || C->getZExtValue() != 8)
03167         return false;
03168     }
03169   } else if (Opc == ISD::SHL) {
03170     // (x & 0xff) << 8
03171     // (x & 0xff0000) << 8
03172     if (Num != 0 && Num != 2)
03173       return false;
03174     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
03175     if (!C || C->getZExtValue() != 8)
03176       return false;
03177   } else { // Opc == ISD::SRL
03178     // (x & 0xff00) >> 8
03179     // (x & 0xff000000) >> 8
03180     if (Num != 1 && Num != 3)
03181       return false;
03182     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
03183     if (!C || C->getZExtValue() != 8)
03184       return false;
03185   }
03186 
03187   if (Parts[Num])
03188     return false;
03189 
03190   Parts[Num] = N0.getOperand(0).getNode();
03191   return true;
03192 }
03193 
03194 /// Match a 32-bit packed halfword bswap. That is
03195 /// ((x & 0x000000ff) << 8) |
03196 /// ((x & 0x0000ff00) >> 8) |
03197 /// ((x & 0x00ff0000) << 8) |
03198 /// ((x & 0xff000000) >> 8)
03199 /// => (rotl (bswap x), 16)
03200 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
03201   if (!LegalOperations)
03202     return SDValue();
03203 
03204   EVT VT = N->getValueType(0);
03205   if (VT != MVT::i32)
03206     return SDValue();
03207   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
03208     return SDValue();
03209 
03210   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
03211   // Look for either
03212   // (or (or (and), (and)), (or (and), (and)))
03213   // (or (or (or (and), (and)), (and)), (and))
03214   if (N0.getOpcode() != ISD::OR)
03215     return SDValue();
03216   SDValue N00 = N0.getOperand(0);
03217   SDValue N01 = N0.getOperand(1);
03218 
03219   if (N1.getOpcode() == ISD::OR &&
03220       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
03221     // (or (or (and), (and)), (or (and), (and)))
03222     SDValue N000 = N00.getOperand(0);
03223     if (!isBSwapHWordElement(N000, Parts))
03224       return SDValue();
03225 
03226     SDValue N001 = N00.getOperand(1);
03227     if (!isBSwapHWordElement(N001, Parts))
03228       return SDValue();
03229     SDValue N010 = N01.getOperand(0);
03230     if (!isBSwapHWordElement(N010, Parts))
03231       return SDValue();
03232     SDValue N011 = N01.getOperand(1);
03233     if (!isBSwapHWordElement(N011, Parts))
03234       return SDValue();
03235   } else {
03236     // (or (or (or (and), (and)), (and)), (and))
03237     if (!isBSwapHWordElement(N1, Parts))
03238       return SDValue();
03239     if (!isBSwapHWordElement(N01, Parts))
03240       return SDValue();
03241     if (N00.getOpcode() != ISD::OR)
03242       return SDValue();
03243     SDValue N000 = N00.getOperand(0);
03244     if (!isBSwapHWordElement(N000, Parts))
03245       return SDValue();
03246     SDValue N001 = N00.getOperand(1);
03247     if (!isBSwapHWordElement(N001, Parts))
03248       return SDValue();
03249   }
03250 
03251   // Make sure the parts are all coming from the same node.
03252   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
03253     return SDValue();
03254 
03255   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
03256                               SDValue(Parts[0],0));
03257 
03258   // Result of the bswap should be rotated by 16. If it's not legal, then
03259   // do  (x << 16) | (x >> 16).
03260   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
03261   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
03262     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
03263   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
03264     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
03265   return DAG.getNode(ISD::OR, SDLoc(N), VT,
03266                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
03267                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
03268 }
03269 
03270 SDValue DAGCombiner::visitOR(SDNode *N) {
03271   SDValue N0 = N->getOperand(0);
03272   SDValue N1 = N->getOperand(1);
03273   SDValue LL, LR, RL, RR, CC0, CC1;
03274   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
03275   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
03276   EVT VT = N1.getValueType();
03277 
03278   // fold vector ops
03279   if (VT.isVector()) {
03280     SDValue FoldedVOp = SimplifyVBinOp(N);
03281     if (FoldedVOp.getNode()) return FoldedVOp;
03282 
03283     // fold (or x, 0) -> x, vector edition
03284     if (ISD::isBuildVectorAllZeros(N0.getNode()))
03285       return N1;
03286     if (ISD::isBuildVectorAllZeros(N1.getNode()))
03287       return N0;
03288 
03289     // fold (or x, -1) -> -1, vector edition
03290     if (ISD::isBuildVectorAllOnes(N0.getNode()))
03291       // do not return N0, because undef node may exist in N0
03292       return DAG.getConstant(
03293           APInt::getAllOnesValue(
03294               N0.getValueType().getScalarType().getSizeInBits()),
03295           N0.getValueType());
03296     if (ISD::isBuildVectorAllOnes(N1.getNode()))
03297       // do not return N1, because undef node may exist in N1
03298       return DAG.getConstant(
03299           APInt::getAllOnesValue(
03300               N1.getValueType().getScalarType().getSizeInBits()),
03301           N1.getValueType());
03302 
03303     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
03304     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
03305     // Do this only if the resulting shuffle is legal.
03306     if (isa<ShuffleVectorSDNode>(N0) &&
03307         isa<ShuffleVectorSDNode>(N1) &&
03308         // Avoid folding a node with illegal type.
03309         TLI.isTypeLegal(VT) &&
03310         N0->getOperand(1) == N1->getOperand(1) &&
03311         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
03312       bool CanFold = true;
03313       unsigned NumElts = VT.getVectorNumElements();
03314       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
03315       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
03316       // We construct two shuffle masks:
03317       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
03318       // and N1 as the second operand.
03319       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
03320       // and N0 as the second operand.
03321       // We do this because OR is commutable and therefore there might be
03322       // two ways to fold this node into a shuffle.
03323       SmallVector<int,4> Mask1;
03324       SmallVector<int,4> Mask2;
03325 
03326       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
03327         int M0 = SV0->getMaskElt(i);
03328         int M1 = SV1->getMaskElt(i);
03329 
03330         // Both shuffle indexes are undef. Propagate Undef.
03331         if (M0 < 0 && M1 < 0) {
03332           Mask1.push_back(M0);
03333           Mask2.push_back(M0);
03334           continue;
03335         }
03336 
03337         if (M0 < 0 || M1 < 0 ||
03338             (M0 < (int)NumElts && M1 < (int)NumElts) ||
03339             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
03340           CanFold = false;
03341           break;
03342         }
03343 
03344         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
03345         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
03346       }
03347 
03348       if (CanFold) {
03349         // Fold this sequence only if the resulting shuffle is 'legal'.
03350         if (TLI.isShuffleMaskLegal(Mask1, VT))
03351           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
03352                                       N1->getOperand(0), &Mask1[0]);
03353         if (TLI.isShuffleMaskLegal(Mask2, VT))
03354           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
03355                                       N0->getOperand(0), &Mask2[0]);
03356       }
03357     }
03358   }
03359 
03360   // fold (or x, undef) -> -1
03361   if (!LegalOperations &&
03362       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
03363     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
03364     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
03365   }
03366   // fold (or c1, c2) -> c1|c2
03367   if (N0C && N1C)
03368     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
03369   // canonicalize constant to RHS
03370   if (N0C && !N1C)
03371     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
03372   // fold (or x, 0) -> x
03373   if (N1C && N1C->isNullValue())
03374     return N0;
03375   // fold (or x, -1) -> -1
03376   if (N1C && N1C->isAllOnesValue())
03377     return N1;
03378   // fold (or x, c) -> c iff (x & ~c) == 0
03379   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
03380     return N1;
03381 
03382   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
03383   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
03384   if (BSwap.getNode())
03385     return BSwap;
03386   BSwap = MatchBSwapHWordLow(N, N0, N1);
03387   if (BSwap.getNode())
03388     return BSwap;
03389 
03390   // reassociate or
03391   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
03392   if (ROR.getNode())
03393     return ROR;
03394   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
03395   // iff (c1 & c2) == 0.
03396   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
03397              isa<ConstantSDNode>(N0.getOperand(1))) {
03398     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
03399     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
03400       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
03401       if (!COR.getNode())
03402         return SDValue();
03403       return DAG.getNode(ISD::AND, SDLoc(N), VT,
03404                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
03405                                      N0.getOperand(0), N1), COR);
03406     }
03407   }
03408   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
03409   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
03410     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
03411     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
03412 
03413     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
03414         LL.getValueType().isInteger()) {
03415       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
03416       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
03417       if (cast<ConstantSDNode>(LR)->isNullValue() &&
03418           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
03419         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
03420                                      LR.getValueType(), LL, RL);
03421         AddToWorklist(ORNode.getNode());
03422         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
03423       }
03424       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
03425       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
03426       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
03427           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
03428         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
03429                                       LR.getValueType(), LL, RL);
03430         AddToWorklist(ANDNode.getNode());
03431         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
03432       }
03433     }
03434     // canonicalize equivalent to ll == rl
03435     if (LL == RR && LR == RL) {
03436       Op1 = ISD::getSetCCSwappedOperands(Op1);
03437       std::swap(RL, RR);
03438     }
03439     if (LL == RL && LR == RR) {
03440       bool isInteger = LL.getValueType().isInteger();
03441       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
03442       if (Result != ISD::SETCC_INVALID &&
03443           (!LegalOperations ||
03444            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
03445             TLI.isOperationLegal(ISD::SETCC,
03446               getSetCCResultType(N0.getValueType())))))
03447         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
03448                             LL, LR, Result);
03449     }
03450   }
03451 
03452   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
03453   if (N0.getOpcode() == N1.getOpcode()) {
03454     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
03455     if (Tmp.getNode()) return Tmp;
03456   }
03457 
03458   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
03459   if (N0.getOpcode() == ISD::AND &&
03460       N1.getOpcode() == ISD::AND &&
03461       N0.getOperand(1).getOpcode() == ISD::Constant &&
03462       N1.getOperand(1).getOpcode() == ISD::Constant &&
03463       // Don't increase # computations.
03464       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
03465     // We can only do this xform if we know that bits from X that are set in C2
03466     // but not in C1 are already zero.  Likewise for Y.
03467     const APInt &LHSMask =
03468       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
03469     const APInt &RHSMask =
03470       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
03471 
03472     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
03473         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
03474       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
03475                               N0.getOperand(0), N1.getOperand(0));
03476       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
03477                          DAG.getConstant(LHSMask | RHSMask, VT));
03478     }
03479   }
03480 
03481   // See if this is some rotate idiom.
03482   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
03483     return SDValue(Rot, 0);
03484 
03485   // Simplify the operands using demanded-bits information.
03486   if (!VT.isVector() &&
03487       SimplifyDemandedBits(SDValue(N, 0)))
03488     return SDValue(N, 0);
03489 
03490   return SDValue();
03491 }
03492 
03493 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
03494 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
03495   if (Op.getOpcode() == ISD::AND) {
03496     if (isa<ConstantSDNode>(Op.getOperand(1))) {
03497       Mask = Op.getOperand(1);
03498       Op = Op.getOperand(0);
03499     } else {
03500       return false;
03501     }
03502   }
03503 
03504   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
03505     Shift = Op;
03506     return true;
03507   }
03508 
03509   return false;
03510 }
03511 
03512 // Return true if we can prove that, whenever Neg and Pos are both in the
03513 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
03514 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
03515 //
03516 //     (or (shift1 X, Neg), (shift2 X, Pos))
03517 //
03518 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
03519 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
03520 // to consider shift amounts with defined behavior.
03521 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
03522   // If OpSize is a power of 2 then:
03523   //
03524   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
03525   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
03526   //
03527   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
03528   // for the stronger condition:
03529   //
03530   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
03531   //
03532   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
03533   // we can just replace Neg with Neg' for the rest of the function.
03534   //
03535   // In other cases we check for the even stronger condition:
03536   //
03537   //     Neg == OpSize - Pos                                    [B]
03538   //
03539   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
03540   // behavior if Pos == 0 (and consequently Neg == OpSize).
03541   //
03542   // We could actually use [A] whenever OpSize is a power of 2, but the
03543   // only extra cases that it would match are those uninteresting ones
03544   // where Neg and Pos are never in range at the same time.  E.g. for
03545   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
03546   // as well as (sub 32, Pos), but:
03547   //
03548   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
03549   //
03550   // always invokes undefined behavior for 32-bit X.
03551   //
03552   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
03553   unsigned MaskLoBits = 0;
03554   if (Neg.getOpcode() == ISD::AND &&
03555       isPowerOf2_64(OpSize) &&
03556       Neg.getOperand(1).getOpcode() == ISD::Constant &&
03557       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
03558     Neg = Neg.getOperand(0);
03559     MaskLoBits = Log2_64(OpSize);
03560   }
03561 
03562   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
03563   if (Neg.getOpcode() != ISD::SUB)
03564     return 0;
03565   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
03566   if (!NegC)
03567     return 0;
03568   SDValue NegOp1 = Neg.getOperand(1);
03569 
03570   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
03571   // Pos'.  The truncation is redundant for the purpose of the equality.
03572   if (MaskLoBits &&
03573       Pos.getOpcode() == ISD::AND &&
03574       Pos.getOperand(1).getOpcode() == ISD::Constant &&
03575       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
03576     Pos = Pos.getOperand(0);
03577 
03578   // The condition we need is now:
03579   //
03580   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
03581   //
03582   // If NegOp1 == Pos then we need:
03583   //
03584   //              OpSize & Mask == NegC & Mask
03585   //
03586   // (because "x & Mask" is a truncation and distributes through subtraction).
03587   APInt Width;
03588   if (Pos == NegOp1)
03589     Width = NegC->getAPIntValue();
03590   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
03591   // Then the condition we want to prove becomes:
03592   //
03593   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
03594   //
03595   // which, again because "x & Mask" is a truncation, becomes:
03596   //
03597   //                NegC & Mask == (OpSize - PosC) & Mask
03598   //              OpSize & Mask == (NegC + PosC) & Mask
03599   else if (Pos.getOpcode() == ISD::ADD &&
03600            Pos.getOperand(0) == NegOp1 &&
03601            Pos.getOperand(1).getOpcode() == ISD::Constant)
03602     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
03603              NegC->getAPIntValue());
03604   else
03605     return false;
03606 
03607   // Now we just need to check that OpSize & Mask == Width & Mask.
03608   if (MaskLoBits)
03609     // Opsize & Mask is 0 since Mask is Opsize - 1.
03610     return Width.getLoBits(MaskLoBits) == 0;
03611   return Width == OpSize;
03612 }
03613 
03614 // A subroutine of MatchRotate used once we have found an OR of two opposite
03615 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
03616 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
03617 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
03618 // Neg with outer conversions stripped away.
03619 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
03620                                        SDValue Neg, SDValue InnerPos,
03621                                        SDValue InnerNeg, unsigned PosOpcode,
03622                                        unsigned NegOpcode, SDLoc DL) {
03623   // fold (or (shl x, (*ext y)),
03624   //          (srl x, (*ext (sub 32, y)))) ->
03625   //   (rotl x, y) or (rotr x, (sub 32, y))
03626   //
03627   // fold (or (shl x, (*ext (sub 32, y))),
03628   //          (srl x, (*ext y))) ->
03629   //   (rotr x, y) or (rotl x, (sub 32, y))
03630   EVT VT = Shifted.getValueType();
03631   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
03632     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
03633     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
03634                        HasPos ? Pos : Neg).getNode();
03635   }
03636 
03637   return nullptr;
03638 }
03639 
03640 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
03641 // idioms for rotate, and if the target supports rotation instructions, generate
03642 // a rot[lr].
03643 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
03644   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
03645   EVT VT = LHS.getValueType();
03646   if (!TLI.isTypeLegal(VT)) return nullptr;
03647 
03648   // The target must have at least one rotate flavor.
03649   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
03650   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
03651   if (!HasROTL && !HasROTR) return nullptr;
03652 
03653   // Match "(X shl/srl V1) & V2" where V2 may not be present.
03654   SDValue LHSShift;   // The shift.
03655   SDValue LHSMask;    // AND value if any.
03656   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
03657     return nullptr; // Not part of a rotate.
03658 
03659   SDValue RHSShift;   // The shift.
03660   SDValue RHSMask;    // AND value if any.
03661   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
03662     return nullptr; // Not part of a rotate.
03663 
03664   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
03665     return nullptr;   // Not shifting the same value.
03666 
03667   if (LHSShift.getOpcode() == RHSShift.getOpcode())
03668     return nullptr;   // Shifts must disagree.
03669 
03670   // Canonicalize shl to left side in a shl/srl pair.
03671   if (RHSShift.getOpcode() == ISD::SHL) {
03672     std::swap(LHS, RHS);
03673     std::swap(LHSShift, RHSShift);
03674     std::swap(LHSMask , RHSMask );
03675   }
03676 
03677   unsigned OpSizeInBits = VT.getSizeInBits();
03678   SDValue LHSShiftArg = LHSShift.getOperand(0);
03679   SDValue LHSShiftAmt = LHSShift.getOperand(1);
03680   SDValue RHSShiftArg = RHSShift.getOperand(0);
03681   SDValue RHSShiftAmt = RHSShift.getOperand(1);
03682 
03683   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
03684   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
03685   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
03686       RHSShiftAmt.getOpcode() == ISD::Constant) {
03687     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
03688     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
03689     if ((LShVal + RShVal) != OpSizeInBits)
03690       return nullptr;
03691 
03692     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
03693                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
03694 
03695     // If there is an AND of either shifted operand, apply it to the result.
03696     if (LHSMask.getNode() || RHSMask.getNode()) {
03697       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
03698 
03699       if (LHSMask.getNode()) {
03700         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
03701         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
03702       }
03703       if (RHSMask.getNode()) {
03704         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
03705         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
03706       }
03707 
03708       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
03709     }
03710 
03711     return Rot.getNode();
03712   }
03713 
03714   // If there is a mask here, and we have a variable shift, we can't be sure
03715   // that we're masking out the right stuff.
03716   if (LHSMask.getNode() || RHSMask.getNode())
03717     return nullptr;
03718 
03719   // If the shift amount is sign/zext/any-extended just peel it off.
03720   SDValue LExtOp0 = LHSShiftAmt;
03721   SDValue RExtOp0 = RHSShiftAmt;
03722   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
03723        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
03724        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
03725        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
03726       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
03727        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
03728        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
03729        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
03730     LExtOp0 = LHSShiftAmt.getOperand(0);
03731     RExtOp0 = RHSShiftAmt.getOperand(0);
03732   }
03733 
03734   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
03735                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
03736   if (TryL)
03737     return TryL;
03738 
03739   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
03740                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
03741   if (TryR)
03742     return TryR;
03743 
03744   return nullptr;
03745 }
03746 
03747 SDValue DAGCombiner::visitXOR(SDNode *N) {
03748   SDValue N0 = N->getOperand(0);
03749   SDValue N1 = N->getOperand(1);
03750   SDValue LHS, RHS, CC;
03751   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
03752   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
03753   EVT VT = N0.getValueType();
03754 
03755   // fold vector ops
03756   if (VT.isVector()) {
03757     SDValue FoldedVOp = SimplifyVBinOp(N);
03758     if (FoldedVOp.getNode()) return FoldedVOp;
03759 
03760     // fold (xor x, 0) -> x, vector edition
03761     if (ISD::isBuildVectorAllZeros(N0.getNode()))
03762       return N1;
03763     if (ISD::isBuildVectorAllZeros(N1.getNode()))
03764       return N0;
03765   }
03766 
03767   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
03768   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
03769     return DAG.getConstant(0, VT);
03770   // fold (xor x, undef) -> undef
03771   if (N0.getOpcode() == ISD::UNDEF)
03772     return N0;
03773   if (N1.getOpcode() == ISD::UNDEF)
03774     return N1;
03775   // fold (xor c1, c2) -> c1^c2
03776   if (N0C && N1C)
03777     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
03778   // canonicalize constant to RHS
03779   if (N0C && !N1C)
03780     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
03781   // fold (xor x, 0) -> x
03782   if (N1C && N1C->isNullValue())
03783     return N0;
03784   // reassociate xor
03785   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
03786   if (RXOR.getNode())
03787     return RXOR;
03788 
03789   // fold !(x cc y) -> (x !cc y)
03790   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
03791     bool isInt = LHS.getValueType().isInteger();
03792     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
03793                                                isInt);
03794 
03795     if (!LegalOperations ||
03796         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
03797       switch (N0.getOpcode()) {
03798       default:
03799         llvm_unreachable("Unhandled SetCC Equivalent!");
03800       case ISD::SETCC:
03801         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
03802       case ISD::SELECT_CC:
03803         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
03804                                N0.getOperand(3), NotCC);
03805       }
03806     }
03807   }
03808 
03809   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
03810   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
03811       N0.getNode()->hasOneUse() &&
03812       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
03813     SDValue V = N0.getOperand(0);
03814     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
03815                     DAG.getConstant(1, V.getValueType()));
03816     AddToWorklist(V.getNode());
03817     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
03818   }
03819 
03820   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
03821   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
03822       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
03823     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
03824     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
03825       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
03826       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
03827       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
03828       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
03829       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
03830     }
03831   }
03832   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
03833   if (N1C && N1C->isAllOnesValue() &&
03834       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
03835     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
03836     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
03837       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
03838       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
03839       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
03840       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
03841       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
03842     }
03843   }
03844   // fold (xor (and x, y), y) -> (and (not x), y)
03845   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
03846       N0->getOperand(1) == N1) {
03847     SDValue X = N0->getOperand(0);
03848     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
03849     AddToWorklist(NotX.getNode());
03850     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
03851   }
03852   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
03853   if (N1C && N0.getOpcode() == ISD::XOR) {
03854     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
03855     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
03856     if (N00C)
03857       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
03858                          DAG.getConstant(N1C->getAPIntValue() ^
03859                                          N00C->getAPIntValue(), VT));
03860     if (N01C)
03861       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
03862                          DAG.getConstant(N1C->getAPIntValue() ^
03863                                          N01C->getAPIntValue(), VT));
03864   }
03865   // fold (xor x, x) -> 0
03866   if (N0 == N1)
03867     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
03868 
03869   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
03870   if (N0.getOpcode() == N1.getOpcode()) {
03871     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
03872     if (Tmp.getNode()) return Tmp;
03873   }
03874 
03875   // Simplify the expression using non-local knowledge.
03876   if (!VT.isVector() &&
03877       SimplifyDemandedBits(SDValue(N, 0)))
03878     return SDValue(N, 0);
03879 
03880   return SDValue();
03881 }
03882 
03883 /// Handle transforms common to the three shifts, when the shift amount is a
03884 /// constant.
03885 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
03886   // We can't and shouldn't fold opaque constants.
03887   if (Amt->isOpaque())
03888     return SDValue();
03889 
03890   SDNode *LHS = N->getOperand(0).getNode();
03891   if (!LHS->hasOneUse()) return SDValue();
03892 
03893   // We want to pull some binops through shifts, so that we have (and (shift))
03894   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
03895   // thing happens with address calculations, so it's important to canonicalize
03896   // it.
03897   bool HighBitSet = false;  // Can we transform this if the high bit is set?
03898 
03899   switch (LHS->getOpcode()) {
03900   default: return SDValue();
03901   case ISD::OR:
03902   case ISD::XOR:
03903     HighBitSet = false; // We can only transform sra if the high bit is clear.
03904     break;
03905   case ISD::AND:
03906     HighBitSet = true;  // We can only transform sra if the high bit is set.
03907     break;
03908   case ISD::ADD:
03909     if (N->getOpcode() != ISD::SHL)
03910       return SDValue(); // only shl(add) not sr[al](add).
03911     HighBitSet = false; // We can only transform sra if the high bit is clear.
03912     break;
03913   }
03914 
03915   // We require the RHS of the binop to be a constant and not opaque as well.
03916   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
03917   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
03918 
03919   // FIXME: disable this unless the input to the binop is a shift by a constant.
03920   // If it is not a shift, it pessimizes some common cases like:
03921   //
03922   //    void foo(int *X, int i) { X[i & 1235] = 1; }
03923   //    int bar(int *X, int i) { return X[i & 255]; }
03924   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
03925   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
03926        BinOpLHSVal->getOpcode() != ISD::SRA &&
03927        BinOpLHSVal->getOpcode() != ISD::SRL) ||
03928       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
03929     return SDValue();
03930 
03931   EVT VT = N->getValueType(0);
03932 
03933   // If this is a signed shift right, and the high bit is modified by the
03934   // logical operation, do not perform the transformation. The highBitSet
03935   // boolean indicates the value of the high bit of the constant which would
03936   // cause it to be modified for this operation.
03937   if (N->getOpcode() == ISD::SRA) {
03938     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
03939     if (BinOpRHSSignSet != HighBitSet)
03940       return SDValue();
03941   }
03942 
03943   if (!TLI.isDesirableToCommuteWithShift(LHS))
03944     return SDValue();
03945 
03946   // Fold the constants, shifting the binop RHS by the shift amount.
03947   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
03948                                N->getValueType(0),
03949                                LHS->getOperand(1), N->getOperand(1));
03950   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
03951 
03952   // Create the new shift.
03953   SDValue NewShift = DAG.getNode(N->getOpcode(),
03954                                  SDLoc(LHS->getOperand(0)),
03955                                  VT, LHS->getOperand(0), N->getOperand(1));
03956 
03957   // Create the new binop.
03958   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
03959 }
03960 
03961 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
03962   assert(N->getOpcode() == ISD::TRUNCATE);
03963   assert(N->getOperand(0).getOpcode() == ISD::AND);
03964 
03965   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
03966   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
03967     SDValue N01 = N->getOperand(0).getOperand(1);
03968 
03969     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
03970       EVT TruncVT = N->getValueType(0);
03971       SDValue N00 = N->getOperand(0).getOperand(0);
03972       APInt TruncC = N01C->getAPIntValue();
03973       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
03974 
03975       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
03976                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
03977                          DAG.getConstant(TruncC, TruncVT));
03978     }
03979   }
03980 
03981   return SDValue();
03982 }
03983 
03984 SDValue DAGCombiner::visitRotate(SDNode *N) {
03985   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
03986   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
03987       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
03988     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
03989     if (NewOp1.getNode())
03990       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
03991                          N->getOperand(0), NewOp1);
03992   }
03993   return SDValue();
03994 }
03995 
03996 SDValue DAGCombiner::visitSHL(SDNode *N) {
03997   SDValue N0 = N->getOperand(0);
03998   SDValue N1 = N->getOperand(1);
03999   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04000   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04001   EVT VT = N0.getValueType();
04002   unsigned OpSizeInBits = VT.getScalarSizeInBits();
04003 
04004   // fold vector ops
04005   if (VT.isVector()) {
04006     SDValue FoldedVOp = SimplifyVBinOp(N);
04007     if (FoldedVOp.getNode()) return FoldedVOp;
04008 
04009     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
04010     // If setcc produces all-one true value then:
04011     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
04012     if (N1CV && N1CV->isConstant()) {
04013       if (N0.getOpcode() == ISD::AND) {
04014         SDValue N00 = N0->getOperand(0);
04015         SDValue N01 = N0->getOperand(1);
04016         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
04017 
04018         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
04019             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
04020                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
04021           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
04022           if (C.getNode())
04023             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
04024         }
04025       } else {
04026         N1C = isConstOrConstSplat(N1);
04027       }
04028     }
04029   }
04030 
04031   // fold (shl c1, c2) -> c1<<c2
04032   if (N0C && N1C)
04033     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
04034   // fold (shl 0, x) -> 0
04035   if (N0C && N0C->isNullValue())
04036     return N0;
04037   // fold (shl x, c >= size(x)) -> undef
04038   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
04039     return DAG.getUNDEF(VT);
04040   // fold (shl x, 0) -> x
04041   if (N1C && N1C->isNullValue())
04042     return N0;
04043   // fold (shl undef, x) -> 0
04044   if (N0.getOpcode() == ISD::UNDEF)
04045     return DAG.getConstant(0, VT);
04046   // if (shl x, c) is known to be zero, return 0
04047   if (DAG.MaskedValueIsZero(SDValue(N, 0),
04048                             APInt::getAllOnesValue(OpSizeInBits)))
04049     return DAG.getConstant(0, VT);
04050   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
04051   if (N1.getOpcode() == ISD::TRUNCATE &&
04052       N1.getOperand(0).getOpcode() == ISD::AND) {
04053     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
04054     if (NewOp1.getNode())
04055       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
04056   }
04057 
04058   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
04059     return SDValue(N, 0);
04060 
04061   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
04062   if (N1C && N0.getOpcode() == ISD::SHL) {
04063     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
04064       uint64_t c1 = N0C1->getZExtValue();
04065       uint64_t c2 = N1C->getZExtValue();
04066       if (c1 + c2 >= OpSizeInBits)
04067         return DAG.getConstant(0, VT);
04068       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
04069                          DAG.getConstant(c1 + c2, N1.getValueType()));
04070     }
04071   }
04072 
04073   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
04074   // For this to be valid, the second form must not preserve any of the bits
04075   // that are shifted out by the inner shift in the first form.  This means
04076   // the outer shift size must be >= the number of bits added by the ext.
04077   // As a corollary, we don't care what kind of ext it is.
04078   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
04079               N0.getOpcode() == ISD::ANY_EXTEND ||
04080               N0.getOpcode() == ISD::SIGN_EXTEND) &&
04081       N0.getOperand(0).getOpcode() == ISD::SHL) {
04082     SDValue N0Op0 = N0.getOperand(0);
04083     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
04084       uint64_t c1 = N0Op0C1->getZExtValue();
04085       uint64_t c2 = N1C->getZExtValue();
04086       EVT InnerShiftVT = N0Op0.getValueType();
04087       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
04088       if (c2 >= OpSizeInBits - InnerShiftSize) {
04089         if (c1 + c2 >= OpSizeInBits)
04090           return DAG.getConstant(0, VT);
04091         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
04092                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
04093                                        N0Op0->getOperand(0)),
04094                            DAG.getConstant(c1 + c2, N1.getValueType()));
04095       }
04096     }
04097   }
04098 
04099   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
04100   // Only fold this if the inner zext has no other uses to avoid increasing
04101   // the total number of instructions.
04102   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
04103       N0.getOperand(0).getOpcode() == ISD::SRL) {
04104     SDValue N0Op0 = N0.getOperand(0);
04105     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
04106       uint64_t c1 = N0Op0C1->getZExtValue();
04107       if (c1 < VT.getScalarSizeInBits()) {
04108         uint64_t c2 = N1C->getZExtValue();
04109         if (c1 == c2) {
04110           SDValue NewOp0 = N0.getOperand(0);
04111           EVT CountVT = NewOp0.getOperand(1).getValueType();
04112           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
04113                                        NewOp0, DAG.getConstant(c2, CountVT));
04114           AddToWorklist(NewSHL.getNode());
04115           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
04116         }
04117       }
04118     }
04119   }
04120 
04121   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
04122   //                               (and (srl x, (sub c1, c2), MASK)
04123   // Only fold this if the inner shift has no other uses -- if it does, folding
04124   // this will increase the total number of instructions.
04125   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
04126     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
04127       uint64_t c1 = N0C1->getZExtValue();
04128       if (c1 < OpSizeInBits) {
04129         uint64_t c2 = N1C->getZExtValue();
04130         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
04131         SDValue Shift;
04132         if (c2 > c1) {
04133           Mask = Mask.shl(c2 - c1);
04134           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
04135                               DAG.getConstant(c2 - c1, N1.getValueType()));
04136         } else {
04137           Mask = Mask.lshr(c1 - c2);
04138           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
04139                               DAG.getConstant(c1 - c2, N1.getValueType()));
04140         }
04141         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
04142                            DAG.getConstant(Mask, VT));
04143       }
04144     }
04145   }
04146   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
04147   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
04148     unsigned BitSize = VT.getScalarSizeInBits();
04149     SDValue HiBitsMask =
04150       DAG.getConstant(APInt::getHighBitsSet(BitSize,
04151                                             BitSize - N1C->getZExtValue()), VT);
04152     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
04153                        HiBitsMask);
04154   }
04155 
04156   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
04157   // Variant of version done on multiply, except mul by a power of 2 is turned
04158   // into a shift.
04159   APInt Val;
04160   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
04161       (isa<ConstantSDNode>(N0.getOperand(1)) ||
04162        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
04163     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
04164     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
04165     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
04166   }
04167 
04168   if (N1C) {
04169     SDValue NewSHL = visitShiftByConstant(N, N1C);
04170     if (NewSHL.getNode())
04171       return NewSHL;
04172   }
04173 
04174   return SDValue();
04175 }
04176 
04177 SDValue DAGCombiner::visitSRA(SDNode *N) {
04178   SDValue N0 = N->getOperand(0);
04179   SDValue N1 = N->getOperand(1);
04180   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04181   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04182   EVT VT = N0.getValueType();
04183   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
04184 
04185   // fold vector ops
04186   if (VT.isVector()) {
04187     SDValue FoldedVOp = SimplifyVBinOp(N);
04188     if (FoldedVOp.getNode()) return FoldedVOp;
04189 
04190     N1C = isConstOrConstSplat(N1);
04191   }
04192 
04193   // fold (sra c1, c2) -> (sra c1, c2)
04194   if (N0C && N1C)
04195     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
04196   // fold (sra 0, x) -> 0
04197   if (N0C && N0C->isNullValue())
04198     return N0;
04199   // fold (sra -1, x) -> -1
04200   if (N0C && N0C->isAllOnesValue())
04201     return N0;
04202   // fold (sra x, (setge c, size(x))) -> undef
04203   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
04204     return DAG.getUNDEF(VT);
04205   // fold (sra x, 0) -> x
04206   if (N1C && N1C->isNullValue())
04207     return N0;
04208   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
04209   // sext_inreg.
04210   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
04211     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
04212     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
04213     if (VT.isVector())
04214       ExtVT = EVT::getVectorVT(*DAG.getContext(),
04215                                ExtVT, VT.getVectorNumElements());
04216     if ((!LegalOperations ||
04217          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
04218       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
04219                          N0.getOperand(0), DAG.getValueType(ExtVT));
04220   }
04221 
04222   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
04223   if (N1C && N0.getOpcode() == ISD::SRA) {
04224     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
04225       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
04226       if (Sum >= OpSizeInBits)
04227         Sum = OpSizeInBits - 1;
04228       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
04229                          DAG.getConstant(Sum, N1.getValueType()));
04230     }
04231   }
04232 
04233   // fold (sra (shl X, m), (sub result_size, n))
04234   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
04235   // result_size - n != m.
04236   // If truncate is free for the target sext(shl) is likely to result in better
04237   // code.
04238   if (N0.getOpcode() == ISD::SHL && N1C) {
04239     // Get the two constanst of the shifts, CN0 = m, CN = n.
04240     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
04241     if (N01C) {
04242       LLVMContext &Ctx = *DAG.getContext();
04243       // Determine what the truncate's result bitsize and type would be.
04244       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
04245 
04246       if (VT.isVector())
04247         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
04248 
04249       // Determine the residual right-shift amount.
04250       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
04251 
04252       // If the shift is not a no-op (in which case this should be just a sign
04253       // extend already), the truncated to type is legal, sign_extend is legal
04254       // on that type, and the truncate to that type is both legal and free,
04255       // perform the transform.
04256       if ((ShiftAmt > 0) &&
04257           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
04258           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
04259           TLI.isTruncateFree(VT, TruncVT)) {
04260 
04261           SDValue Amt = DAG.getConstant(ShiftAmt,
04262               getShiftAmountTy(N0.getOperand(0).getValueType()));
04263           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
04264                                       N0.getOperand(0), Amt);
04265           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
04266                                       Shift);
04267           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
04268                              N->getValueType(0), Trunc);
04269       }
04270     }
04271   }
04272 
04273   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
04274   if (N1.getOpcode() == ISD::TRUNCATE &&
04275       N1.getOperand(0).getOpcode() == ISD::AND) {
04276     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
04277     if (NewOp1.getNode())
04278       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
04279   }
04280 
04281   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
04282   //      if c1 is equal to the number of bits the trunc removes
04283   if (N0.getOpcode() == ISD::TRUNCATE &&
04284       (N0.getOperand(0).getOpcode() == ISD::SRL ||
04285        N0.getOperand(0).getOpcode() == ISD::SRA) &&
04286       N0.getOperand(0).hasOneUse() &&
04287       N0.getOperand(0).getOperand(1).hasOneUse() &&
04288       N1C) {
04289     SDValue N0Op0 = N0.getOperand(0);
04290     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
04291       unsigned LargeShiftVal = LargeShift->getZExtValue();
04292       EVT LargeVT = N0Op0.getValueType();
04293 
04294       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
04295         SDValue Amt =
04296           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
04297                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
04298         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
04299                                   N0Op0.getOperand(0), Amt);
04300         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
04301       }
04302     }
04303   }
04304 
04305   // Simplify, based on bits shifted out of the LHS.
04306   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
04307     return SDValue(N, 0);
04308 
04309 
04310   // If the sign bit is known to be zero, switch this to a SRL.
04311   if (DAG.SignBitIsZero(N0))
04312     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
04313 
04314   if (N1C) {
04315     SDValue NewSRA = visitShiftByConstant(N, N1C);
04316     if (NewSRA.getNode())
04317       return NewSRA;
04318   }
04319 
04320   return SDValue();
04321 }
04322 
04323 SDValue DAGCombiner::visitSRL(SDNode *N) {
04324   SDValue N0 = N->getOperand(0);
04325   SDValue N1 = N->getOperand(1);
04326   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04328   EVT VT = N0.getValueType();
04329   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
04330 
04331   // fold vector ops
04332   if (VT.isVector()) {
04333     SDValue FoldedVOp = SimplifyVBinOp(N);
04334     if (FoldedVOp.getNode()) return FoldedVOp;
04335 
04336     N1C = isConstOrConstSplat(N1);
04337   }
04338 
04339   // fold (srl c1, c2) -> c1 >>u c2
04340   if (N0C && N1C)
04341     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
04342   // fold (srl 0, x) -> 0
04343   if (N0C && N0C->isNullValue())
04344     return N0;
04345   // fold (srl x, c >= size(x)) -> undef
04346   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
04347     return DAG.getUNDEF(VT);
04348   // fold (srl x, 0) -> x
04349   if (N1C && N1C->isNullValue())
04350     return N0;
04351   // if (srl x, c) is known to be zero, return 0
04352   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
04353                                    APInt::getAllOnesValue(OpSizeInBits)))
04354     return DAG.getConstant(0, VT);
04355 
04356   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
04357   if (N1C && N0.getOpcode() == ISD::SRL) {
04358     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
04359       uint64_t c1 = N01C->getZExtValue();
04360       uint64_t c2 = N1C->getZExtValue();
04361       if (c1 + c2 >= OpSizeInBits)
04362         return DAG.getConstant(0, VT);
04363       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
04364                          DAG.getConstant(c1 + c2, N1.getValueType()));
04365     }
04366   }
04367 
04368   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
04369   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
04370       N0.getOperand(0).getOpcode() == ISD::SRL &&
04371       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
04372     uint64_t c1 =
04373       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
04374     uint64_t c2 = N1C->getZExtValue();
04375     EVT InnerShiftVT = N0.getOperand(0).getValueType();
04376     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
04377     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
04378     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
04379     if (c1 + OpSizeInBits == InnerShiftSize) {
04380       if (c1 + c2 >= InnerShiftSize)
04381         return DAG.getConstant(0, VT);
04382       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
04383                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
04384                                      N0.getOperand(0)->getOperand(0),
04385                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
04386     }
04387   }
04388 
04389   // fold (srl (shl x, c), c) -> (and x, cst2)
04390   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
04391     unsigned BitSize = N0.getScalarValueSizeInBits();
04392     if (BitSize <= 64) {
04393       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
04394       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
04395                          DAG.getConstant(~0ULL >> ShAmt, VT));
04396     }
04397   }
04398 
04399   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
04400   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
04401     // Shifting in all undef bits?
04402     EVT SmallVT = N0.getOperand(0).getValueType();
04403     unsigned BitSize = SmallVT.getScalarSizeInBits();
04404     if (N1C->getZExtValue() >= BitSize)
04405       return DAG.getUNDEF(VT);
04406 
04407     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
04408       uint64_t ShiftAmt = N1C->getZExtValue();
04409       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
04410                                        N0.getOperand(0),
04411                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
04412       AddToWorklist(SmallShift.getNode());
04413       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
04414       return DAG.getNode(ISD::AND, SDLoc(N), VT,
04415                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
04416                          DAG.getConstant(Mask, VT));
04417     }
04418   }
04419 
04420   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
04421   // bit, which is unmodified by sra.
04422   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
04423     if (N0.getOpcode() == ISD::SRA)
04424       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
04425   }
04426 
04427   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
04428   if (N1C && N0.getOpcode() == ISD::CTLZ &&
04429       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
04430     APInt KnownZero, KnownOne;
04431     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
04432 
04433     // If any of the input bits are KnownOne, then the input couldn't be all
04434     // zeros, thus the result of the srl will always be zero.
04435     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
04436 
04437     // If all of the bits input the to ctlz node are known to be zero, then
04438     // the result of the ctlz is "32" and the result of the shift is one.
04439     APInt UnknownBits = ~KnownZero;
04440     if (UnknownBits == 0) return DAG.getConstant(1, VT);
04441 
04442     // Otherwise, check to see if there is exactly one bit input to the ctlz.
04443     if ((UnknownBits & (UnknownBits - 1)) == 0) {
04444       // Okay, we know that only that the single bit specified by UnknownBits
04445       // could be set on input to the CTLZ node. If this bit is set, the SRL
04446       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
04447       // to an SRL/XOR pair, which is likely to simplify more.
04448       unsigned ShAmt = UnknownBits.countTrailingZeros();
04449       SDValue Op = N0.getOperand(0);
04450 
04451       if (ShAmt) {
04452         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
04453                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
04454         AddToWorklist(Op.getNode());
04455       }
04456 
04457       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
04458                          Op, DAG.getConstant(1, VT));
04459     }
04460   }
04461 
04462   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
04463   if (N1.getOpcode() == ISD::TRUNCATE &&
04464       N1.getOperand(0).getOpcode() == ISD::AND) {
04465     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
04466     if (NewOp1.getNode())
04467       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
04468   }
04469 
04470   // fold operands of srl based on knowledge that the low bits are not
04471   // demanded.
04472   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
04473     return SDValue(N, 0);
04474 
04475   if (N1C) {
04476     SDValue NewSRL = visitShiftByConstant(N, N1C);
04477     if (NewSRL.getNode())
04478       return NewSRL;
04479   }
04480 
04481   // Attempt to convert a srl of a load into a narrower zero-extending load.
04482   SDValue NarrowLoad = ReduceLoadWidth(N);
04483   if (NarrowLoad.getNode())
04484     return NarrowLoad;
04485 
04486   // Here is a common situation. We want to optimize:
04487   //
04488   //   %a = ...
04489   //   %b = and i32 %a, 2
04490   //   %c = srl i32 %b, 1
04491   //   brcond i32 %c ...
04492   //
04493   // into
04494   //
04495   //   %a = ...
04496   //   %b = and %a, 2
04497   //   %c = setcc eq %b, 0
04498   //   brcond %c ...
04499   //
04500   // However when after the source operand of SRL is optimized into AND, the SRL
04501   // itself may not be optimized further. Look for it and add the BRCOND into
04502   // the worklist.
04503   if (N->hasOneUse()) {
04504     SDNode *Use = *N->use_begin();
04505     if (Use->getOpcode() == ISD::BRCOND)
04506       AddToWorklist(Use);
04507     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
04508       // Also look pass the truncate.
04509       Use = *Use->use_begin();
04510       if (Use->getOpcode() == ISD::BRCOND)
04511         AddToWorklist(Use);
04512     }
04513   }
04514 
04515   return SDValue();
04516 }
04517 
04518 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
04519   SDValue N0 = N->getOperand(0);
04520   EVT VT = N->getValueType(0);
04521 
04522   // fold (ctlz c1) -> c2
04523   if (isa<ConstantSDNode>(N0))
04524     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
04525   return SDValue();
04526 }
04527 
04528 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
04529   SDValue N0 = N->getOperand(0);
04530   EVT VT = N->getValueType(0);
04531 
04532   // fold (ctlz_zero_undef c1) -> c2
04533   if (isa<ConstantSDNode>(N0))
04534     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
04535   return SDValue();
04536 }
04537 
04538 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
04539   SDValue N0 = N->getOperand(0);
04540   EVT VT = N->getValueType(0);
04541 
04542   // fold (cttz c1) -> c2
04543   if (isa<ConstantSDNode>(N0))
04544     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
04545   return SDValue();
04546 }
04547 
04548 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
04549   SDValue N0 = N->getOperand(0);
04550   EVT VT = N->getValueType(0);
04551 
04552   // fold (cttz_zero_undef c1) -> c2
04553   if (isa<ConstantSDNode>(N0))
04554     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
04555   return SDValue();
04556 }
04557 
04558 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
04559   SDValue N0 = N->getOperand(0);
04560   EVT VT = N->getValueType(0);
04561 
04562   // fold (ctpop c1) -> c2
04563   if (isa<ConstantSDNode>(N0))
04564     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
04565   return SDValue();
04566 }
04567 
04568 SDValue DAGCombiner::visitSELECT(SDNode *N) {
04569   SDValue N0 = N->getOperand(0);
04570   SDValue N1 = N->getOperand(1);
04571   SDValue N2 = N->getOperand(2);
04572   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
04573   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
04574   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
04575   EVT VT = N->getValueType(0);
04576   EVT VT0 = N0.getValueType();
04577 
04578   // fold (select C, X, X) -> X
04579   if (N1 == N2)
04580     return N1;
04581   // fold (select true, X, Y) -> X
04582   if (N0C && !N0C->isNullValue())
04583     return N1;
04584   // fold (select false, X, Y) -> Y
04585   if (N0C && N0C->isNullValue())
04586     return N2;
04587   // fold (select C, 1, X) -> (or C, X)
04588   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
04589     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
04590   // fold (select C, 0, 1) -> (xor C, 1)
04591   // We can't do this reliably if integer based booleans have different contents
04592   // to floating point based booleans. This is because we can't tell whether we
04593   // have an integer-based boolean or a floating-point-based boolean unless we
04594   // can find the SETCC that produced it and inspect its operands. This is
04595   // fairly easy if C is the SETCC node, but it can potentially be
04596   // undiscoverable (or not reasonably discoverable). For example, it could be
04597   // in another basic block or it could require searching a complicated
04598   // expression.
04599   if (VT.isInteger() &&
04600       (VT0 == MVT::i1 || (VT0.isInteger() &&
04601                           TLI.getBooleanContents(false, false) ==
04602                               TLI.getBooleanContents(false, true) &&
04603                           TLI.getBooleanContents(false, false) ==
04604                               TargetLowering::ZeroOrOneBooleanContent)) &&
04605       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
04606     SDValue XORNode;
04607     if (VT == VT0)
04608       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
04609                          N0, DAG.getConstant(1, VT0));
04610     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
04611                           N0, DAG.getConstant(1, VT0));
04612     AddToWorklist(XORNode.getNode());
04613     if (VT.bitsGT(VT0))
04614       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
04615     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
04616   }
04617   // fold (select C, 0, X) -> (and (not C), X)
04618   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
04619     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
04620     AddToWorklist(NOTNode.getNode());
04621     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
04622   }
04623   // fold (select C, X, 1) -> (or (not C), X)
04624   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
04625     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
04626     AddToWorklist(NOTNode.getNode());
04627     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
04628   }
04629   // fold (select C, X, 0) -> (and C, X)
04630   if (VT == MVT::i1 && N2C && N2C->isNullValue())
04631     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
04632   // fold (select X, X, Y) -> (or X, Y)
04633   // fold (select X, 1, Y) -> (or X, Y)
04634   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
04635     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
04636   // fold (select X, Y, X) -> (and X, Y)
04637   // fold (select X, Y, 0) -> (and X, Y)
04638   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
04639     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
04640 
04641   // If we can fold this based on the true/false value, do so.
04642   if (SimplifySelectOps(N, N1, N2))
04643     return SDValue(N, 0);  // Don't revisit N.
04644 
04645   // fold selects based on a setcc into other things, such as min/max/abs
04646   if (N0.getOpcode() == ISD::SETCC) {
04647     if ((!LegalOperations &&
04648          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
04649   TLI.isOperationLegal(ISD::SELECT_CC, VT))
04650       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
04651                          N0.getOperand(0), N0.getOperand(1),
04652                          N1, N2, N0.getOperand(2));
04653     return SimplifySelect(SDLoc(N), N0, N1, N2);
04654   }
04655 
04656   return SDValue();
04657 }
04658 
04659 static
04660 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
04661   SDLoc DL(N);
04662   EVT LoVT, HiVT;
04663   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
04664 
04665   // Split the inputs.
04666   SDValue Lo, Hi, LL, LH, RL, RH;
04667   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
04668   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
04669 
04670   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
04671   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
04672 
04673   return std::make_pair(Lo, Hi);
04674 }
04675 
04676 // This function assumes all the vselect's arguments are CONCAT_VECTOR
04677 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
04678 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
04679   SDLoc dl(N);
04680   SDValue Cond = N->getOperand(0);
04681   SDValue LHS = N->getOperand(1);
04682   SDValue RHS = N->getOperand(2);
04683   EVT VT = N->getValueType(0);
04684   int NumElems = VT.getVectorNumElements();
04685   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
04686          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
04687          Cond.getOpcode() == ISD::BUILD_VECTOR);
04688 
04689   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
04690   // binary ones here.
04691   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
04692     return SDValue();
04693 
04694   // We're sure we have an even number of elements due to the
04695   // concat_vectors we have as arguments to vselect.
04696   // Skip BV elements until we find one that's not an UNDEF
04697   // After we find an UNDEF element, keep looping until we get to half the
04698   // length of the BV and see if all the non-undef nodes are the same.
04699   ConstantSDNode *BottomHalf = nullptr;
04700   for (int i = 0; i < NumElems / 2; ++i) {
04701     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
04702       continue;
04703 
04704     if (BottomHalf == nullptr)
04705       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
04706     else if (Cond->getOperand(i).getNode() != BottomHalf)
04707       return SDValue();
04708   }
04709 
04710   // Do the same for the second half of the BuildVector
04711   ConstantSDNode *TopHalf = nullptr;
04712   for (int i = NumElems / 2; i < NumElems; ++i) {
04713     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
04714       continue;
04715 
04716     if (TopHalf == nullptr)
04717       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
04718     else if (Cond->getOperand(i).getNode() != TopHalf)
04719       return SDValue();
04720   }
04721 
04722   assert(TopHalf && BottomHalf &&
04723          "One half of the selector was all UNDEFs and the other was all the "
04724          "same value. This should have been addressed before this function.");
04725   return DAG.getNode(
04726       ISD::CONCAT_VECTORS, dl, VT,
04727       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
04728       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
04729 }
04730 
04731 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
04732   SDValue N0 = N->getOperand(0);
04733   SDValue N1 = N->getOperand(1);
04734   SDValue N2 = N->getOperand(2);
04735   SDLoc DL(N);
04736 
04737   // Canonicalize integer abs.
04738   // vselect (setg[te] X,  0),  X, -X ->
04739   // vselect (setgt    X, -1),  X, -X ->
04740   // vselect (setl[te] X,  0), -X,  X ->
04741   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
04742   if (N0.getOpcode() == ISD::SETCC) {
04743     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
04744     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
04745     bool isAbs = false;
04746     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
04747 
04748     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
04749          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
04750         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
04751       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
04752     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
04753              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
04754       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
04755 
04756     if (isAbs) {
04757       EVT VT = LHS.getValueType();
04758       SDValue Shift = DAG.getNode(
04759           ISD::SRA, DL, VT, LHS,
04760           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
04761       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
04762       AddToWorklist(Shift.getNode());
04763       AddToWorklist(Add.getNode());
04764       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
04765     }
04766   }
04767 
04768   // If the VSELECT result requires splitting and the mask is provided by a
04769   // SETCC, then split both nodes and its operands before legalization. This
04770   // prevents the type legalizer from unrolling SETCC into scalar comparisons
04771   // and enables future optimizations (e.g. min/max pattern matching on X86).
04772   if (N0.getOpcode() == ISD::SETCC) {
04773     EVT VT = N->getValueType(0);
04774 
04775     // Check if any splitting is required.
04776     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
04777         TargetLowering::TypeSplitVector)
04778       return SDValue();
04779 
04780     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
04781     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
04782     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
04783     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
04784 
04785     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
04786     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
04787 
04788     // Add the new VSELECT nodes to the work list in case they need to be split
04789     // again.
04790     AddToWorklist(Lo.getNode());
04791     AddToWorklist(Hi.getNode());
04792 
04793     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
04794   }
04795 
04796   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
04797   if (ISD::isBuildVectorAllOnes(N0.getNode()))
04798     return N1;
04799   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
04800   if (ISD::isBuildVectorAllZeros(N0.getNode()))
04801     return N2;
04802 
04803   // The ConvertSelectToConcatVector function is assuming both the above
04804   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
04805   // and addressed.
04806   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
04807       N2.getOpcode() == ISD::CONCAT_VECTORS &&
04808       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
04809     SDValue CV = ConvertSelectToConcatVector(N, DAG);
04810     if (CV.getNode())
04811       return CV;
04812   }
04813 
04814   return SDValue();
04815 }
04816 
04817 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
04818   SDValue N0 = N->getOperand(0);
04819   SDValue N1 = N->getOperand(1);
04820   SDValue N2 = N->getOperand(2);
04821   SDValue N3 = N->getOperand(3);
04822   SDValue N4 = N->getOperand(4);
04823   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
04824 
04825   // fold select_cc lhs, rhs, x, x, cc -> x
04826   if (N2 == N3)
04827     return N2;
04828 
04829   // Determine if the condition we're dealing with is constant
04830   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
04831                               N0, N1, CC, SDLoc(N), false);
04832   if (SCC.getNode()) {
04833     AddToWorklist(SCC.getNode());
04834 
04835     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
04836       if (!SCCC->isNullValue())
04837         return N2;    // cond always true -> true val
04838       else
04839         return N3;    // cond always false -> false val
04840     }
04841 
04842     // Fold to a simpler select_cc
04843     if (SCC.getOpcode() == ISD::SETCC)
04844       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
04845                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
04846                          SCC.getOperand(2));
04847   }
04848 
04849   // If we can fold this based on the true/false value, do so.
04850   if (SimplifySelectOps(N, N2, N3))
04851     return SDValue(N, 0);  // Don't revisit N.
04852 
04853   // fold select_cc into other things, such as min/max/abs
04854   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
04855 }
04856 
04857 SDValue DAGCombiner::visitSETCC(SDNode *N) {
04858   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
04859                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
04860                        SDLoc(N));
04861 }
04862 
04863 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
04864 // dag node into a ConstantSDNode or a build_vector of constants.
04865 // This function is called by the DAGCombiner when visiting sext/zext/aext
04866 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
04867 // Vector extends are not folded if operations are legal; this is to
04868 // avoid introducing illegal build_vector dag nodes.
04869 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
04870                                          SelectionDAG &DAG, bool LegalTypes,
04871                                          bool LegalOperations) {
04872   unsigned Opcode = N->getOpcode();
04873   SDValue N0 = N->getOperand(0);
04874   EVT VT = N->getValueType(0);
04875 
04876   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
04877          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
04878 
04879   // fold (sext c1) -> c1
04880   // fold (zext c1) -> c1
04881   // fold (aext c1) -> c1
04882   if (isa<ConstantSDNode>(N0))
04883     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
04884 
04885   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
04886   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
04887   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
04888   EVT SVT = VT.getScalarType();
04889   if (!(VT.isVector() &&
04890       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
04891       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
04892     return nullptr;
04893 
04894   // We can fold this node into a build_vector.
04895   unsigned VTBits = SVT.getSizeInBits();
04896   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
04897   unsigned ShAmt = VTBits - EVTBits;
04898   SmallVector<SDValue, 8> Elts;
04899   unsigned NumElts = N0->getNumOperands();
04900   SDLoc DL(N);
04901 
04902   for (unsigned i=0; i != NumElts; ++i) {
04903     SDValue Op = N0->getOperand(i);
04904     if (Op->getOpcode() == ISD::UNDEF) {
04905       Elts.push_back(DAG.getUNDEF(SVT));
04906       continue;
04907     }
04908 
04909     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
04910     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
04911     if (Opcode == ISD::SIGN_EXTEND)
04912       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
04913                                      SVT));
04914     else
04915       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
04916                                      SVT));
04917   }
04918 
04919   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
04920 }
04921 
04922 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
04923 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
04924 // transformation. Returns true if extension are possible and the above
04925 // mentioned transformation is profitable.
04926 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
04927                                     unsigned ExtOpc,
04928                                     SmallVectorImpl<SDNode *> &ExtendNodes,
04929                                     const TargetLowering &TLI) {
04930   bool HasCopyToRegUses = false;
04931   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
04932   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
04933                             UE = N0.getNode()->use_end();
04934        UI != UE; ++UI) {
04935     SDNode *User = *UI;
04936     if (User == N)
04937       continue;
04938     if (UI.getUse().getResNo() != N0.getResNo())
04939       continue;
04940     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
04941     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
04942       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
04943       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
04944         // Sign bits will be lost after a zext.
04945         return false;
04946       bool Add = false;
04947       for (unsigned i = 0; i != 2; ++i) {
04948         SDValue UseOp = User->getOperand(i);
04949         if (UseOp == N0)
04950           continue;
04951         if (!isa<ConstantSDNode>(UseOp))
04952           return false;
04953         Add = true;
04954       }
04955       if (Add)
04956         ExtendNodes.push_back(User);
04957       continue;
04958     }
04959     // If truncates aren't free and there are users we can't
04960     // extend, it isn't worthwhile.
04961     if (!isTruncFree)
04962       return false;
04963     // Remember if this value is live-out.
04964     if (User->getOpcode() == ISD::CopyToReg)
04965       HasCopyToRegUses = true;
04966   }
04967 
04968   if (HasCopyToRegUses) {
04969     bool BothLiveOut = false;
04970     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
04971          UI != UE; ++UI) {
04972       SDUse &Use = UI.getUse();
04973       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
04974         BothLiveOut = true;
04975         break;
04976       }
04977     }
04978     if (BothLiveOut)
04979       // Both unextended and extended values are live out. There had better be
04980       // a good reason for the transformation.
04981       return ExtendNodes.size();
04982   }
04983   return true;
04984 }
04985 
04986 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
04987                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
04988                                   ISD::NodeType ExtType) {
04989   // Extend SetCC uses if necessary.
04990   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
04991     SDNode *SetCC = SetCCs[i];
04992     SmallVector<SDValue, 4> Ops;
04993 
04994     for (unsigned j = 0; j != 2; ++j) {
04995       SDValue SOp = SetCC->getOperand(j);
04996       if (SOp == Trunc)
04997         Ops.push_back(ExtLoad);
04998       else
04999         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
05000     }
05001 
05002     Ops.push_back(SetCC->getOperand(2));
05003     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
05004   }
05005 }
05006 
05007 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
05008   SDValue N0 = N->getOperand(0);
05009   EVT VT = N->getValueType(0);
05010 
05011   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
05012                                               LegalOperations))
05013     return SDValue(Res, 0);
05014 
05015   // fold (sext (sext x)) -> (sext x)
05016   // fold (sext (aext x)) -> (sext x)
05017   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
05018     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
05019                        N0.getOperand(0));
05020 
05021   if (N0.getOpcode() == ISD::TRUNCATE) {
05022     // fold (sext (truncate (load x))) -> (sext (smaller load x))
05023     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
05024     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
05025     if (NarrowLoad.getNode()) {
05026       SDNode* oye = N0.getNode()->getOperand(0).getNode();
05027       if (NarrowLoad.getNode() != N0.getNode()) {
05028         CombineTo(N0.getNode(), NarrowLoad);
05029         // CombineTo deleted the truncate, if needed, but not what's under it.
05030         AddToWorklist(oye);
05031       }
05032       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05033     }
05034 
05035     // See if the value being truncated is already sign extended.  If so, just
05036     // eliminate the trunc/sext pair.
05037     SDValue Op = N0.getOperand(0);
05038     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
05039     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
05040     unsigned DestBits = VT.getScalarType().getSizeInBits();
05041     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
05042 
05043     if (OpBits == DestBits) {
05044       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
05045       // bits, it is already ready.
05046       if (NumSignBits > DestBits-MidBits)
05047         return Op;
05048     } else if (OpBits < DestBits) {
05049       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
05050       // bits, just sext from i32.
05051       if (NumSignBits > OpBits-MidBits)
05052         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
05053     } else {
05054       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
05055       // bits, just truncate to i32.
05056       if (NumSignBits > OpBits-MidBits)
05057         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
05058     }
05059 
05060     // fold (sext (truncate x)) -> (sextinreg x).
05061     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
05062                                                  N0.getValueType())) {
05063       if (OpBits < DestBits)
05064         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
05065       else if (OpBits > DestBits)
05066         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
05067       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
05068                          DAG.getValueType(N0.getValueType()));
05069     }
05070   }
05071 
05072   // fold (sext (load x)) -> (sext (truncate (sextload x)))
05073   // None of the supported targets knows how to perform load and sign extend
05074   // on vectors in one instruction.  We only perform this transformation on
05075   // scalars.
05076   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
05077       ISD::isUNINDEXEDLoad(N0.getNode()) &&
05078       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
05079        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
05080     bool DoXform = true;
05081     SmallVector<SDNode*, 4> SetCCs;
05082     if (!N0.hasOneUse())
05083       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
05084     if (DoXform) {
05085       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05086       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
05087                                        LN0->getChain(),
05088                                        LN0->getBasePtr(), N0.getValueType(),
05089                                        LN0->getMemOperand());
05090       CombineTo(N, ExtLoad);
05091       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
05092                                   N0.getValueType(), ExtLoad);
05093       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
05094       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
05095                       ISD::SIGN_EXTEND);
05096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05097     }
05098   }
05099 
05100   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
05101   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
05102   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
05103       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
05104     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05105     EVT MemVT = LN0->getMemoryVT();
05106     if ((!LegalOperations && !LN0->isVolatile()) ||
05107         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
05108       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
05109                                        LN0->getChain(),
05110                                        LN0->getBasePtr(), MemVT,
05111                                        LN0->getMemOperand());
05112       CombineTo(N, ExtLoad);
05113       CombineTo(N0.getNode(),
05114                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
05115                             N0.getValueType(), ExtLoad),
05116                 ExtLoad.getValue(1));
05117       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05118     }
05119   }
05120 
05121   // fold (sext (and/or/xor (load x), cst)) ->
05122   //      (and/or/xor (sextload x), (sext cst))
05123   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
05124        N0.getOpcode() == ISD::XOR) &&
05125       isa<LoadSDNode>(N0.getOperand(0)) &&
05126       N0.getOperand(1).getOpcode() == ISD::Constant &&
05127       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
05128       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
05129     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
05130     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
05131       bool DoXform = true;
05132       SmallVector<SDNode*, 4> SetCCs;
05133       if (!N0.hasOneUse())
05134         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
05135                                           SetCCs, TLI);
05136       if (DoXform) {
05137         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
05138                                          LN0->getChain(), LN0->getBasePtr(),
05139                                          LN0->getMemoryVT(),
05140                                          LN0->getMemOperand());
05141         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
05142         Mask = Mask.sext(VT.getSizeInBits());
05143         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
05144                                   ExtLoad, DAG.getConstant(Mask, VT));
05145         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
05146                                     SDLoc(N0.getOperand(0)),
05147                                     N0.getOperand(0).getValueType(), ExtLoad);
05148         CombineTo(N, And);
05149         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
05150         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
05151                         ISD::SIGN_EXTEND);
05152         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05153       }
05154     }
05155   }
05156 
05157   if (N0.getOpcode() == ISD::SETCC) {
05158     EVT N0VT = N0.getOperand(0).getValueType();
05159     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
05160     // Only do this before legalize for now.
05161     if (VT.isVector() && !LegalOperations &&
05162         TLI.getBooleanContents(N0VT) ==
05163             TargetLowering::ZeroOrNegativeOneBooleanContent) {
05164       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
05165       // of the same size as the compared operands. Only optimize sext(setcc())
05166       // if this is the case.
05167       EVT SVT = getSetCCResultType(N0VT);
05168 
05169       // We know that the # elements of the results is the same as the
05170       // # elements of the compare (and the # elements of the compare result
05171       // for that matter).  Check to see that they are the same size.  If so,
05172       // we know that the element size of the sext'd result matches the
05173       // element size of the compare operands.
05174       if (VT.getSizeInBits() == SVT.getSizeInBits())
05175         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
05176                              N0.getOperand(1),
05177                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
05178 
05179       // If the desired elements are smaller or larger than the source
05180       // elements we can use a matching integer vector type and then
05181       // truncate/sign extend
05182       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
05183       if (SVT == MatchingVectorType) {
05184         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
05185                                N0.getOperand(0), N0.getOperand(1),
05186                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
05187         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
05188       }
05189     }
05190 
05191     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
05192     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
05193     SDValue NegOne =
05194       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
05195     SDValue SCC =
05196       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
05197                        NegOne, DAG.getConstant(0, VT),
05198                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
05199     if (SCC.getNode()) return SCC;
05200 
05201     if (!VT.isVector()) {
05202       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
05203       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
05204         SDLoc DL(N);
05205         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
05206         SDValue SetCC = DAG.getSetCC(DL,
05207                                      SetCCVT,
05208                                      N0.getOperand(0), N0.getOperand(1), CC);
05209         EVT SelectVT = getSetCCResultType(VT);
05210         return DAG.getSelect(DL, VT,
05211                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
05212                              NegOne, DAG.getConstant(0, VT));
05213 
05214       }
05215     }
05216   }
05217 
05218   // fold (sext x) -> (zext x) if the sign bit is known zero.
05219   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
05220       DAG.SignBitIsZero(N0))
05221     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
05222 
05223   return SDValue();
05224 }
05225 
05226 // isTruncateOf - If N is a truncate of some other value, return true, record
05227 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
05228 // This function computes KnownZero to avoid a duplicated call to
05229 // computeKnownBits in the caller.
05230 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
05231                          APInt &KnownZero) {
05232   APInt KnownOne;
05233   if (N->getOpcode() == ISD::TRUNCATE) {
05234     Op = N->getOperand(0);
05235     DAG.computeKnownBits(Op, KnownZero, KnownOne);
05236     return true;
05237   }
05238 
05239   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
05240       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
05241     return false;
05242 
05243   SDValue Op0 = N->getOperand(0);
05244   SDValue Op1 = N->getOperand(1);
05245   assert(Op0.getValueType() == Op1.getValueType());
05246 
05247   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
05248   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
05249   if (COp0 && COp0->isNullValue())
05250     Op = Op1;
05251   else if (COp1 && COp1->isNullValue())
05252     Op = Op0;
05253   else
05254     return false;
05255 
05256   DAG.computeKnownBits(Op, KnownZero, KnownOne);
05257 
05258   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
05259     return false;
05260 
05261   return true;
05262 }
05263 
05264 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
05265   SDValue N0 = N->getOperand(0);
05266   EVT VT = N->getValueType(0);
05267 
05268   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
05269                                               LegalOperations))
05270     return SDValue(Res, 0);
05271 
05272   // fold (zext (zext x)) -> (zext x)
05273   // fold (zext (aext x)) -> (zext x)
05274   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
05275     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
05276                        N0.getOperand(0));
05277 
05278   // fold (zext (truncate x)) -> (zext x) or
05279   //      (zext (truncate x)) -> (truncate x)
05280   // This is valid when the truncated bits of x are already zero.
05281   // FIXME: We should extend this to work for vectors too.
05282   SDValue Op;
05283   APInt KnownZero;
05284   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
05285     APInt TruncatedBits =
05286       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
05287       APInt(Op.getValueSizeInBits(), 0) :
05288       APInt::getBitsSet(Op.getValueSizeInBits(),
05289                         N0.getValueSizeInBits(),
05290                         std::min(Op.getValueSizeInBits(),
05291                                  VT.getSizeInBits()));
05292     if (TruncatedBits == (KnownZero & TruncatedBits)) {
05293       if (VT.bitsGT(Op.getValueType()))
05294         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
05295       if (VT.bitsLT(Op.getValueType()))
05296         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
05297 
05298       return Op;
05299     }
05300   }
05301 
05302   // fold (zext (truncate (load x))) -> (zext (smaller load x))
05303   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
05304   if (N0.getOpcode() == ISD::TRUNCATE) {
05305     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
05306     if (NarrowLoad.getNode()) {
05307       SDNode* oye = N0.getNode()->getOperand(0).getNode();
05308       if (NarrowLoad.getNode() != N0.getNode()) {
05309         CombineTo(N0.getNode(), NarrowLoad);
05310         // CombineTo deleted the truncate, if needed, but not what's under it.
05311         AddToWorklist(oye);
05312       }
05313       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05314     }
05315   }
05316 
05317   // fold (zext (truncate x)) -> (and x, mask)
05318   if (N0.getOpcode() == ISD::TRUNCATE &&
05319       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
05320 
05321     // fold (zext (truncate (load x))) -> (zext (smaller load x))
05322     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
05323     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
05324     if (NarrowLoad.getNode()) {
05325       SDNode* oye = N0.getNode()->getOperand(0).getNode();
05326       if (NarrowLoad.getNode() != N0.getNode()) {
05327         CombineTo(N0.getNode(), NarrowLoad);
05328         // CombineTo deleted the truncate, if needed, but not what's under it.
05329         AddToWorklist(oye);
05330       }
05331       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05332     }
05333 
05334     SDValue Op = N0.getOperand(0);
05335     if (Op.getValueType().bitsLT(VT)) {
05336       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
05337       AddToWorklist(Op.getNode());
05338     } else if (Op.getValueType().bitsGT(VT)) {
05339       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
05340       AddToWorklist(Op.getNode());
05341     }
05342     return DAG.getZeroExtendInReg(Op, SDLoc(N),
05343                                   N0.getValueType().getScalarType());
05344   }
05345 
05346   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
05347   // if either of the casts is not free.
05348   if (N0.getOpcode() == ISD::AND &&
05349       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
05350       N0.getOperand(1).getOpcode() == ISD::Constant &&
05351       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
05352                            N0.getValueType()) ||
05353        !TLI.isZExtFree(N0.getValueType(), VT))) {
05354     SDValue X = N0.getOperand(0).getOperand(0);
05355     if (X.getValueType().bitsLT(VT)) {
05356       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
05357     } else if (X.getValueType().bitsGT(VT)) {
05358       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
05359     }
05360     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
05361     Mask = Mask.zext(VT.getSizeInBits());
05362     return DAG.getNode(ISD::AND, SDLoc(N), VT,
05363                        X, DAG.getConstant(Mask, VT));
05364   }
05365 
05366   // fold (zext (load x)) -> (zext (truncate (zextload x)))
05367   // None of the supported targets knows how to perform load and vector_zext
05368   // on vectors in one instruction.  We only perform this transformation on
05369   // scalars.
05370   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
05371       ISD::isUNINDEXEDLoad(N0.getNode()) &&
05372       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
05373        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
05374     bool DoXform = true;
05375     SmallVector<SDNode*, 4> SetCCs;
05376     if (!N0.hasOneUse())
05377       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
05378     if (DoXform) {
05379       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05380       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
05381                                        LN0->getChain(),
05382                                        LN0->getBasePtr(), N0.getValueType(),
05383                                        LN0->getMemOperand());
05384       CombineTo(N, ExtLoad);
05385       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
05386                                   N0.getValueType(), ExtLoad);
05387       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
05388 
05389       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
05390                       ISD::ZERO_EXTEND);
05391       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05392     }
05393   }
05394 
05395   // fold (zext (and/or/xor (load x), cst)) ->
05396   //      (and/or/xor (zextload x), (zext cst))
05397   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
05398        N0.getOpcode() == ISD::XOR) &&
05399       isa<LoadSDNode>(N0.getOperand(0)) &&
05400       N0.getOperand(1).getOpcode() == ISD::Constant &&
05401       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
05402       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
05403     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
05404     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
05405       bool DoXform = true;
05406       SmallVector<SDNode*, 4> SetCCs;
05407       if (!N0.hasOneUse())
05408         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
05409                                           SetCCs, TLI);
05410       if (DoXform) {
05411         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
05412                                          LN0->getChain(), LN0->getBasePtr(),
05413                                          LN0->getMemoryVT(),
05414                                          LN0->getMemOperand());
05415         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
05416         Mask = Mask.zext(VT.getSizeInBits());
05417         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
05418                                   ExtLoad, DAG.getConstant(Mask, VT));
05419         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
05420                                     SDLoc(N0.getOperand(0)),
05421                                     N0.getOperand(0).getValueType(), ExtLoad);
05422         CombineTo(N, And);
05423         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
05424         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
05425                         ISD::ZERO_EXTEND);
05426         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05427       }
05428     }
05429   }
05430 
05431   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
05432   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
05433   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
05434       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
05435     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05436     EVT MemVT = LN0->getMemoryVT();
05437     if ((!LegalOperations && !LN0->isVolatile()) ||
05438         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
05439       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
05440                                        LN0->getChain(),
05441                                        LN0->getBasePtr(), MemVT,
05442                                        LN0->getMemOperand());
05443       CombineTo(N, ExtLoad);
05444       CombineTo(N0.getNode(),
05445                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
05446                             ExtLoad),
05447                 ExtLoad.getValue(1));
05448       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05449     }
05450   }
05451 
05452   if (N0.getOpcode() == ISD::SETCC) {
05453     if (!LegalOperations && VT.isVector() &&
05454         N0.getValueType().getVectorElementType() == MVT::i1) {
05455       EVT N0VT = N0.getOperand(0).getValueType();
05456       if (getSetCCResultType(N0VT) == N0.getValueType())
05457         return SDValue();
05458 
05459       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
05460       // Only do this before legalize for now.
05461       EVT EltVT = VT.getVectorElementType();
05462       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
05463                                     DAG.getConstant(1, EltVT));
05464       if (VT.getSizeInBits() == N0VT.getSizeInBits())
05465         // We know that the # elements of the results is the same as the
05466         // # elements of the compare (and the # elements of the compare result
05467         // for that matter).  Check to see that they are the same size.  If so,
05468         // we know that the element size of the sext'd result matches the
05469         // element size of the compare operands.
05470         return DAG.getNode(ISD::AND, SDLoc(N), VT,
05471                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
05472                                          N0.getOperand(1),
05473                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
05474                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
05475                                        OneOps));
05476 
05477       // If the desired elements are smaller or larger than the source
05478       // elements we can use a matching integer vector type and then
05479       // truncate/sign extend
05480       EVT MatchingElementType =
05481         EVT::getIntegerVT(*DAG.getContext(),
05482                           N0VT.getScalarType().getSizeInBits());
05483       EVT MatchingVectorType =
05484         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
05485                          N0VT.getVectorNumElements());
05486       SDValue VsetCC =
05487         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
05488                       N0.getOperand(1),
05489                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
05490       return DAG.getNode(ISD::AND, SDLoc(N), VT,
05491                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
05492                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
05493     }
05494 
05495     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
05496     SDValue SCC =
05497       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
05498                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
05499                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
05500     if (SCC.getNode()) return SCC;
05501   }
05502 
05503   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
05504   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
05505       isa<ConstantSDNode>(N0.getOperand(1)) &&
05506       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
05507       N0.hasOneUse()) {
05508     SDValue ShAmt = N0.getOperand(1);
05509     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
05510     if (N0.getOpcode() == ISD::SHL) {
05511       SDValue InnerZExt = N0.getOperand(0);
05512       // If the original shl may be shifting out bits, do not perform this
05513       // transformation.
05514       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
05515         InnerZExt.getOperand(0).getValueType().getSizeInBits();
05516       if (ShAmtVal > KnownZeroBits)
05517         return SDValue();
05518     }
05519 
05520     SDLoc DL(N);
05521 
05522     // Ensure that the shift amount is wide enough for the shifted value.
05523     if (VT.getSizeInBits() >= 256)
05524       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
05525 
05526     return DAG.getNode(N0.getOpcode(), DL, VT,
05527                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
05528                        ShAmt);
05529   }
05530 
05531   return SDValue();
05532 }
05533 
05534 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
05535   SDValue N0 = N->getOperand(0);
05536   EVT VT = N->getValueType(0);
05537 
05538   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
05539                                               LegalOperations))
05540     return SDValue(Res, 0);
05541 
05542   // fold (aext (aext x)) -> (aext x)
05543   // fold (aext (zext x)) -> (zext x)
05544   // fold (aext (sext x)) -> (sext x)
05545   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
05546       N0.getOpcode() == ISD::ZERO_EXTEND ||
05547       N0.getOpcode() == ISD::SIGN_EXTEND)
05548     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
05549 
05550   // fold (aext (truncate (load x))) -> (aext (smaller load x))
05551   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
05552   if (N0.getOpcode() == ISD::TRUNCATE) {
05553     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
05554     if (NarrowLoad.getNode()) {
05555       SDNode* oye = N0.getNode()->getOperand(0).getNode();
05556       if (NarrowLoad.getNode() != N0.getNode()) {
05557         CombineTo(N0.getNode(), NarrowLoad);
05558         // CombineTo deleted the truncate, if needed, but not what's under it.
05559         AddToWorklist(oye);
05560       }
05561       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05562     }
05563   }
05564 
05565   // fold (aext (truncate x))
05566   if (N0.getOpcode() == ISD::TRUNCATE) {
05567     SDValue TruncOp = N0.getOperand(0);
05568     if (TruncOp.getValueType() == VT)
05569       return TruncOp; // x iff x size == zext size.
05570     if (TruncOp.getValueType().bitsGT(VT))
05571       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
05572     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
05573   }
05574 
05575   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
05576   // if the trunc is not free.
05577   if (N0.getOpcode() == ISD::AND &&
05578       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
05579       N0.getOperand(1).getOpcode() == ISD::Constant &&
05580       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
05581                           N0.getValueType())) {
05582     SDValue X = N0.getOperand(0).getOperand(0);
05583     if (X.getValueType().bitsLT(VT)) {
05584       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
05585     } else if (X.getValueType().bitsGT(VT)) {
05586       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
05587     }
05588     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
05589     Mask = Mask.zext(VT.getSizeInBits());
05590     return DAG.getNode(ISD::AND, SDLoc(N), VT,
05591                        X, DAG.getConstant(Mask, VT));
05592   }
05593 
05594   // fold (aext (load x)) -> (aext (truncate (extload x)))
05595   // None of the supported targets knows how to perform load and any_ext
05596   // on vectors in one instruction.  We only perform this transformation on
05597   // scalars.
05598   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
05599       ISD::isUNINDEXEDLoad(N0.getNode()) &&
05600       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
05601     bool DoXform = true;
05602     SmallVector<SDNode*, 4> SetCCs;
05603     if (!N0.hasOneUse())
05604       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
05605     if (DoXform) {
05606       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05607       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
05608                                        LN0->getChain(),
05609                                        LN0->getBasePtr(), N0.getValueType(),
05610                                        LN0->getMemOperand());
05611       CombineTo(N, ExtLoad);
05612       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
05613                                   N0.getValueType(), ExtLoad);
05614       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
05615       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
05616                       ISD::ANY_EXTEND);
05617       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05618     }
05619   }
05620 
05621   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
05622   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
05623   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
05624   if (N0.getOpcode() == ISD::LOAD &&
05625       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
05626       N0.hasOneUse()) {
05627     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05628     ISD::LoadExtType ExtType = LN0->getExtensionType();
05629     EVT MemVT = LN0->getMemoryVT();
05630     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
05631       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
05632                                        VT, LN0->getChain(), LN0->getBasePtr(),
05633                                        MemVT, LN0->getMemOperand());
05634       CombineTo(N, ExtLoad);
05635       CombineTo(N0.getNode(),
05636                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
05637                             N0.getValueType(), ExtLoad),
05638                 ExtLoad.getValue(1));
05639       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05640     }
05641   }
05642 
05643   if (N0.getOpcode() == ISD::SETCC) {
05644     // For vectors:
05645     // aext(setcc) -> vsetcc
05646     // aext(setcc) -> truncate(vsetcc)
05647     // aext(setcc) -> aext(vsetcc)
05648     // Only do this before legalize for now.
05649     if (VT.isVector() && !LegalOperations) {
05650       EVT N0VT = N0.getOperand(0).getValueType();
05651         // We know that the # elements of the results is the same as the
05652         // # elements of the compare (and the # elements of the compare result
05653         // for that matter).  Check to see that they are the same size.  If so,
05654         // we know that the element size of the sext'd result matches the
05655         // element size of the compare operands.
05656       if (VT.getSizeInBits() == N0VT.getSizeInBits())
05657         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
05658                              N0.getOperand(1),
05659                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
05660       // If the desired elements are smaller or larger than the source
05661       // elements we can use a matching integer vector type and then
05662       // truncate/any extend
05663       else {
05664         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
05665         SDValue VsetCC =
05666           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
05667                         N0.getOperand(1),
05668                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
05669         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
05670       }
05671     }
05672 
05673     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
05674     SDValue SCC =
05675       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
05676                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
05677                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
05678     if (SCC.getNode())
05679       return SCC;
05680   }
05681 
05682   return SDValue();
05683 }
05684 
05685 /// See if the specified operand can be simplified with the knowledge that only
05686 /// the bits specified by Mask are used.  If so, return the simpler operand,
05687 /// otherwise return a null SDValue.
05688 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
05689   switch (V.getOpcode()) {
05690   default: break;
05691   case ISD::Constant: {
05692     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
05693     assert(CV && "Const value should be ConstSDNode.");
05694     const APInt &CVal = CV->getAPIntValue();
05695     APInt NewVal = CVal & Mask;
05696     if (NewVal != CVal)
05697       return DAG.getConstant(NewVal, V.getValueType());
05698     break;
05699   }
05700   case ISD::OR:
05701   case ISD::XOR:
05702     // If the LHS or RHS don't contribute bits to the or, drop them.
05703     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
05704       return V.getOperand(1);
05705     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
05706       return V.getOperand(0);
05707     break;
05708   case ISD::SRL:
05709     // Only look at single-use SRLs.
05710     if (!V.getNode()->hasOneUse())
05711       break;
05712     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
05713       // See if we can recursively simplify the LHS.
05714       unsigned Amt = RHSC->getZExtValue();
05715 
05716       // Watch out for shift count overflow though.
05717       if (Amt >= Mask.getBitWidth()) break;
05718       APInt NewMask = Mask << Amt;
05719       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
05720       if (SimplifyLHS.getNode())
05721         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
05722                            SimplifyLHS, V.getOperand(1));
05723     }
05724   }
05725   return SDValue();
05726 }
05727 
05728 /// If the result of a wider load is shifted to right of N  bits and then
05729 /// truncated to a narrower type and where N is a multiple of number of bits of
05730 /// the narrower type, transform it to a narrower load from address + N / num of
05731 /// bits of new type. If the result is to be extended, also fold the extension
05732 /// to form a extending load.
05733 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
05734   unsigned Opc = N->getOpcode();
05735 
05736   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
05737   SDValue N0 = N->getOperand(0);
05738   EVT VT = N->getValueType(0);
05739   EVT ExtVT = VT;
05740 
05741   // This transformation isn't valid for vector loads.
05742   if (VT.isVector())
05743     return SDValue();
05744 
05745   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
05746   // extended to VT.
05747   if (Opc == ISD::SIGN_EXTEND_INREG) {
05748     ExtType = ISD::SEXTLOAD;
05749     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
05750   } else if (Opc == ISD::SRL) {
05751     // Another special-case: SRL is basically zero-extending a narrower value.
05752     ExtType = ISD::ZEXTLOAD;
05753     N0 = SDValue(N, 0);
05754     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
05755     if (!N01) return SDValue();
05756     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
05757                               VT.getSizeInBits() - N01->getZExtValue());
05758   }
05759   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
05760     return SDValue();
05761 
05762   unsigned EVTBits = ExtVT.getSizeInBits();
05763 
05764   // Do not generate loads of non-round integer types since these can
05765   // be expensive (and would be wrong if the type is not byte sized).
05766   if (!ExtVT.isRound())
05767     return SDValue();
05768 
05769   unsigned ShAmt = 0;
05770   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
05771     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
05772       ShAmt = N01->getZExtValue();
05773       // Is the shift amount a multiple of size of VT?
05774       if ((ShAmt & (EVTBits-1)) == 0) {
05775         N0 = N0.getOperand(0);
05776         // Is the load width a multiple of size of VT?
05777         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
05778           return SDValue();
05779       }
05780 
05781       // At this point, we must have a load or else we can't do the transform.
05782       if (!isa<LoadSDNode>(N0)) return SDValue();
05783 
05784       // Because a SRL must be assumed to *need* to zero-extend the high bits
05785       // (as opposed to anyext the high bits), we can't combine the zextload
05786       // lowering of SRL and an sextload.
05787       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
05788         return SDValue();
05789 
05790       // If the shift amount is larger than the input type then we're not
05791       // accessing any of the loaded bytes.  If the load was a zextload/extload
05792       // then the result of the shift+trunc is zero/undef (handled elsewhere).
05793       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
05794         return SDValue();
05795     }
05796   }
05797 
05798   // If the load is shifted left (and the result isn't shifted back right),
05799   // we can fold the truncate through the shift.
05800   unsigned ShLeftAmt = 0;
05801   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
05802       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
05803     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
05804       ShLeftAmt = N01->getZExtValue();
05805       N0 = N0.getOperand(0);
05806     }
05807   }
05808 
05809   // If we haven't found a load, we can't narrow it.  Don't transform one with
05810   // multiple uses, this would require adding a new load.
05811   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
05812     return SDValue();
05813 
05814   // Don't change the width of a volatile load.
05815   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05816   if (LN0->isVolatile())
05817     return SDValue();
05818 
05819   // Verify that we are actually reducing a load width here.
05820   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
05821     return SDValue();
05822 
05823   // For the transform to be legal, the load must produce only two values
05824   // (the value loaded and the chain).  Don't transform a pre-increment
05825   // load, for example, which produces an extra value.  Otherwise the
05826   // transformation is not equivalent, and the downstream logic to replace
05827   // uses gets things wrong.
05828   if (LN0->getNumValues() > 2)
05829     return SDValue();
05830 
05831   // If the load that we're shrinking is an extload and we're not just
05832   // discarding the extension we can't simply shrink the load. Bail.
05833   // TODO: It would be possible to merge the extensions in some cases.
05834   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
05835       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
05836     return SDValue();
05837 
05838   EVT PtrType = N0.getOperand(1).getValueType();
05839 
05840   if (PtrType == MVT::Untyped || PtrType.isExtended())
05841     // It's not possible to generate a constant of extended or untyped type.
05842     return SDValue();
05843 
05844   // For big endian targets, we need to adjust the offset to the pointer to
05845   // load the correct bytes.
05846   if (TLI.isBigEndian()) {
05847     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
05848     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
05849     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
05850   }
05851 
05852   uint64_t PtrOff = ShAmt / 8;
05853   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
05854   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
05855                                PtrType, LN0->getBasePtr(),
05856                                DAG.getConstant(PtrOff, PtrType));
05857   AddToWorklist(NewPtr.getNode());
05858 
05859   SDValue Load;
05860   if (ExtType == ISD::NON_EXTLOAD)
05861     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
05862                         LN0->getPointerInfo().getWithOffset(PtrOff),
05863                         LN0->isVolatile(), LN0->isNonTemporal(),
05864                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
05865   else
05866     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
05867                           LN0->getPointerInfo().getWithOffset(PtrOff),
05868                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
05869                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
05870 
05871   // Replace the old load's chain with the new load's chain.
05872   WorklistRemover DeadNodes(*this);
05873   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
05874 
05875   // Shift the result left, if we've swallowed a left shift.
05876   SDValue Result = Load;
05877   if (ShLeftAmt != 0) {
05878     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
05879     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
05880       ShImmTy = VT;
05881     // If the shift amount is as large as the result size (but, presumably,
05882     // no larger than the source) then the useful bits of the result are
05883     // zero; we can't simply return the shortened shift, because the result
05884     // of that operation is undefined.
05885     if (ShLeftAmt >= VT.getSizeInBits())
05886       Result = DAG.getConstant(0, VT);
05887     else
05888       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
05889                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
05890   }
05891 
05892   // Return the new loaded value.
05893   return Result;
05894 }
05895 
05896 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
05897   SDValue N0 = N->getOperand(0);
05898   SDValue N1 = N->getOperand(1);
05899   EVT VT = N->getValueType(0);
05900   EVT EVT = cast<VTSDNode>(N1)->getVT();
05901   unsigned VTBits = VT.getScalarType().getSizeInBits();
05902   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
05903 
05904   // fold (sext_in_reg c1) -> c1
05905   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
05906     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
05907 
05908   // If the input is already sign extended, just drop the extension.
05909   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
05910     return N0;
05911 
05912   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
05913   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
05914       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
05915     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
05916                        N0.getOperand(0), N1);
05917 
05918   // fold (sext_in_reg (sext x)) -> (sext x)
05919   // fold (sext_in_reg (aext x)) -> (sext x)
05920   // if x is small enough.
05921   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
05922     SDValue N00 = N0.getOperand(0);
05923     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
05924         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
05925       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
05926   }
05927 
05928   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
05929   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
05930     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
05931 
05932   // fold operands of sext_in_reg based on knowledge that the top bits are not
05933   // demanded.
05934   if (SimplifyDemandedBits(SDValue(N, 0)))
05935     return SDValue(N, 0);
05936 
05937   // fold (sext_in_reg (load x)) -> (smaller sextload x)
05938   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
05939   SDValue NarrowLoad = ReduceLoadWidth(N);
05940   if (NarrowLoad.getNode())
05941     return NarrowLoad;
05942 
05943   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
05944   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
05945   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
05946   if (N0.getOpcode() == ISD::SRL) {
05947     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
05948       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
05949         // We can turn this into an SRA iff the input to the SRL is already sign
05950         // extended enough.
05951         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
05952         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
05953           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
05954                              N0.getOperand(0), N0.getOperand(1));
05955       }
05956   }
05957 
05958   // fold (sext_inreg (extload x)) -> (sextload x)
05959   if (ISD::isEXTLoad(N0.getNode()) &&
05960       ISD::isUNINDEXEDLoad(N0.getNode()) &&
05961       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
05962       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
05963        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
05964     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05965     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
05966                                      LN0->getChain(),
05967                                      LN0->getBasePtr(), EVT,
05968                                      LN0->getMemOperand());
05969     CombineTo(N, ExtLoad);
05970     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
05971     AddToWorklist(ExtLoad.getNode());
05972     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05973   }
05974   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
05975   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
05976       N0.hasOneUse() &&
05977       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
05978       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
05979        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
05980     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
05981     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
05982                                      LN0->getChain(),
05983                                      LN0->getBasePtr(), EVT,
05984                                      LN0->getMemOperand());
05985     CombineTo(N, ExtLoad);
05986     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
05987     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
05988   }
05989 
05990   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
05991   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
05992     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
05993                                        N0.getOperand(1), false);
05994     if (BSwap.getNode())
05995       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
05996                          BSwap, N1);
05997   }
05998 
05999   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
06000   // into a build_vector.
06001   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
06002     SmallVector<SDValue, 8> Elts;
06003     unsigned NumElts = N0->getNumOperands();
06004     unsigned ShAmt = VTBits - EVTBits;
06005 
06006     for (unsigned i = 0; i != NumElts; ++i) {
06007       SDValue Op = N0->getOperand(i);
06008       if (Op->getOpcode() == ISD::UNDEF) {
06009         Elts.push_back(Op);
06010         continue;
06011       }
06012 
06013       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
06014       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
06015       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
06016                                      Op.getValueType()));
06017     }
06018 
06019     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
06020   }
06021 
06022   return SDValue();
06023 }
06024 
06025 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
06026   SDValue N0 = N->getOperand(0);
06027   EVT VT = N->getValueType(0);
06028   bool isLE = TLI.isLittleEndian();
06029 
06030   // noop truncate
06031   if (N0.getValueType() == N->getValueType(0))
06032     return N0;
06033   // fold (truncate c1) -> c1
06034   if (isa<ConstantSDNode>(N0))
06035     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
06036   // fold (truncate (truncate x)) -> (truncate x)
06037   if (N0.getOpcode() == ISD::TRUNCATE)
06038     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
06039   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
06040   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
06041       N0.getOpcode() == ISD::SIGN_EXTEND ||
06042       N0.getOpcode() == ISD::ANY_EXTEND) {
06043     if (N0.getOperand(0).getValueType().bitsLT(VT))
06044       // if the source is smaller than the dest, we still need an extend
06045       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
06046                          N0.getOperand(0));
06047     if (N0.getOperand(0).getValueType().bitsGT(VT))
06048       // if the source is larger than the dest, than we just need the truncate
06049       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
06050     // if the source and dest are the same type, we can drop both the extend
06051     // and the truncate.
06052     return N0.getOperand(0);
06053   }
06054 
06055   // Fold extract-and-trunc into a narrow extract. For example:
06056   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
06057   //   i32 y = TRUNCATE(i64 x)
06058   //        -- becomes --
06059   //   v16i8 b = BITCAST (v2i64 val)
06060   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
06061   //
06062   // Note: We only run this optimization after type legalization (which often
06063   // creates this pattern) and before operation legalization after which
06064   // we need to be more careful about the vector instructions that we generate.
06065   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
06066       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
06067 
06068     EVT VecTy = N0.getOperand(0).getValueType();
06069     EVT ExTy = N0.getValueType();
06070     EVT TrTy = N->getValueType(0);
06071 
06072     unsigned NumElem = VecTy.getVectorNumElements();
06073     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
06074 
06075     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
06076     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
06077 
06078     SDValue EltNo = N0->getOperand(1);
06079     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
06080       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
06081       EVT IndexTy = TLI.getVectorIdxTy();
06082       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
06083 
06084       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
06085                               NVT, N0.getOperand(0));
06086 
06087       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
06088                          SDLoc(N), TrTy, V,
06089                          DAG.getConstant(Index, IndexTy));
06090     }
06091   }
06092 
06093   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
06094   if (N0.getOpcode() == ISD::SELECT) {
06095     EVT SrcVT = N0.getValueType();
06096     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
06097         TLI.isTruncateFree(SrcVT, VT)) {
06098       SDLoc SL(N0);
06099       SDValue Cond = N0.getOperand(0);
06100       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
06101       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
06102       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
06103     }
06104   }
06105 
06106   // Fold a series of buildvector, bitcast, and truncate if possible.
06107   // For example fold
06108   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
06109   //   (2xi32 (buildvector x, y)).
06110   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
06111       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
06112       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
06113       N0.getOperand(0).hasOneUse()) {
06114 
06115     SDValue BuildVect = N0.getOperand(0);
06116     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
06117     EVT TruncVecEltTy = VT.getVectorElementType();
06118 
06119     // Check that the element types match.
06120     if (BuildVectEltTy == TruncVecEltTy) {
06121       // Now we only need to compute the offset of the truncated elements.
06122       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
06123       unsigned TruncVecNumElts = VT.getVectorNumElements();
06124       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
06125 
06126       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
06127              "Invalid number of elements");
06128 
06129       SmallVector<SDValue, 8> Opnds;
06130       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
06131         Opnds.push_back(BuildVect.getOperand(i));
06132 
06133       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
06134     }
06135   }
06136 
06137   // See if we can simplify the input to this truncate through knowledge that
06138   // only the low bits are being used.
06139   // For example "trunc (or (shl x, 8), y)" // -> trunc y
06140   // Currently we only perform this optimization on scalars because vectors
06141   // may have different active low bits.
06142   if (!VT.isVector()) {
06143     SDValue Shorter =
06144       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
06145                                                VT.getSizeInBits()));
06146     if (Shorter.getNode())
06147       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
06148   }
06149   // fold (truncate (load x)) -> (smaller load x)
06150   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
06151   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
06152     SDValue Reduced = ReduceLoadWidth(N);
06153     if (Reduced.getNode())
06154       return Reduced;
06155     // Handle the case where the load remains an extending load even
06156     // after truncation.
06157     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
06158       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
06159       if (!LN0->isVolatile() &&
06160           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
06161         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
06162                                          VT, LN0->getChain(), LN0->getBasePtr(),
06163                                          LN0->getMemoryVT(),
06164                                          LN0->getMemOperand());
06165         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
06166         return NewLoad;
06167       }
06168     }
06169   }
06170   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
06171   // where ... are all 'undef'.
06172   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
06173     SmallVector<EVT, 8> VTs;
06174     SDValue V;
06175     unsigned Idx = 0;
06176     unsigned NumDefs = 0;
06177 
06178     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
06179       SDValue X = N0.getOperand(i);
06180       if (X.getOpcode() != ISD::UNDEF) {
06181         V = X;
06182         Idx = i;
06183         NumDefs++;
06184       }
06185       // Stop if more than one members are non-undef.
06186       if (NumDefs > 1)
06187         break;
06188       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
06189                                      VT.getVectorElementType(),
06190                                      X.getValueType().getVectorNumElements()));
06191     }
06192 
06193     if (NumDefs == 0)
06194       return DAG.getUNDEF(VT);
06195 
06196     if (NumDefs == 1) {
06197       assert(V.getNode() && "The single defined operand is empty!");
06198       SmallVector<SDValue, 8> Opnds;
06199       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
06200         if (i != Idx) {
06201           Opnds.push_back(DAG.getUNDEF(VTs[i]));
06202           continue;
06203         }
06204         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
06205         AddToWorklist(NV.getNode());
06206         Opnds.push_back(NV);
06207       }
06208       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
06209     }
06210   }
06211 
06212   // Simplify the operands using demanded-bits information.
06213   if (!VT.isVector() &&
06214       SimplifyDemandedBits(SDValue(N, 0)))
06215     return SDValue(N, 0);
06216 
06217   return SDValue();
06218 }
06219 
06220 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
06221   SDValue Elt = N->getOperand(i);
06222   if (Elt.getOpcode() != ISD::MERGE_VALUES)
06223     return Elt.getNode();
06224   return Elt.getOperand(Elt.getResNo()).getNode();
06225 }
06226 
06227 /// build_pair (load, load) -> load
06228 /// if load locations are consecutive.
06229 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
06230   assert(N->getOpcode() == ISD::BUILD_PAIR);
06231 
06232   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
06233   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
06234   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
06235       LD1->getAddressSpace() != LD2->getAddressSpace())
06236     return SDValue();
06237   EVT LD1VT = LD1->getValueType(0);
06238 
06239   if (ISD::isNON_EXTLoad(LD2) &&
06240       LD2->hasOneUse() &&
06241       // If both are volatile this would reduce the number of volatile loads.
06242       // If one is volatile it might be ok, but play conservative and bail out.
06243       !LD1->isVolatile() &&
06244       !LD2->isVolatile() &&
06245       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
06246     unsigned Align = LD1->getAlignment();
06247     unsigned NewAlign = TLI.getDataLayout()->
06248       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
06249 
06250     if (NewAlign <= Align &&
06251         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
06252       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
06253                          LD1->getBasePtr(), LD1->getPointerInfo(),
06254                          false, false, false, Align);
06255   }
06256 
06257   return SDValue();
06258 }
06259 
06260 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
06261   SDValue N0 = N->getOperand(0);
06262   EVT VT = N->getValueType(0);
06263 
06264   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
06265   // Only do this before legalize, since afterward the target may be depending
06266   // on the bitconvert.
06267   // First check to see if this is all constant.
06268   if (!LegalTypes &&
06269       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
06270       VT.isVector()) {
06271     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
06272 
06273     EVT DestEltVT = N->getValueType(0).getVectorElementType();
06274     assert(!DestEltVT.isVector() &&
06275            "Element type of vector ValueType must not be vector!");
06276     if (isSimple)
06277       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
06278   }
06279 
06280   // If the input is a constant, let getNode fold it.
06281   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
06282     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
06283     if (Res.getNode() != N) {
06284       if (!LegalOperations ||
06285           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
06286         return Res;
06287 
06288       // Folding it resulted in an illegal node, and it's too late to
06289       // do that. Clean up the old node and forego the transformation.
06290       // Ideally this won't happen very often, because instcombine
06291       // and the earlier dagcombine runs (where illegal nodes are
06292       // permitted) should have folded most of them already.
06293       deleteAndRecombine(Res.getNode());
06294     }
06295   }
06296 
06297   // (conv (conv x, t1), t2) -> (conv x, t2)
06298   if (N0.getOpcode() == ISD::BITCAST)
06299     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
06300                        N0.getOperand(0));
06301 
06302   // fold (conv (load x)) -> (load (conv*)x)
06303   // If the resultant load doesn't need a higher alignment than the original!
06304   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
06305       // Do not change the width of a volatile load.
06306       !cast<LoadSDNode>(N0)->isVolatile() &&
06307       // Do not remove the cast if the types differ in endian layout.
06308       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
06309       TLI.hasBigEndianPartOrdering(VT) &&
06310       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
06311       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
06312     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
06313     unsigned Align = TLI.getDataLayout()->
06314       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
06315     unsigned OrigAlign = LN0->getAlignment();
06316 
06317     if (Align <= OrigAlign) {
06318       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
06319                                  LN0->getBasePtr(), LN0->getPointerInfo(),
06320                                  LN0->isVolatile(), LN0->isNonTemporal(),
06321                                  LN0->isInvariant(), OrigAlign,
06322                                  LN0->getAAInfo());
06323       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
06324       return Load;
06325     }
06326   }
06327 
06328   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
06329   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
06330   // This often reduces constant pool loads.
06331   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
06332        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
06333       N0.getNode()->hasOneUse() && VT.isInteger() &&
06334       !VT.isVector() && !N0.getValueType().isVector()) {
06335     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
06336                                   N0.getOperand(0));
06337     AddToWorklist(NewConv.getNode());
06338 
06339     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
06340     if (N0.getOpcode() == ISD::FNEG)
06341       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
06342                          NewConv, DAG.getConstant(SignBit, VT));
06343     assert(N0.getOpcode() == ISD::FABS);
06344     return DAG.getNode(ISD::AND, SDLoc(N), VT,
06345                        NewConv, DAG.getConstant(~SignBit, VT));
06346   }
06347 
06348   // fold (bitconvert (fcopysign cst, x)) ->
06349   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
06350   // Note that we don't handle (copysign x, cst) because this can always be
06351   // folded to an fneg or fabs.
06352   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
06353       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
06354       VT.isInteger() && !VT.isVector()) {
06355     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
06356     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
06357     if (isTypeLegal(IntXVT)) {
06358       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
06359                               IntXVT, N0.getOperand(1));
06360       AddToWorklist(X.getNode());
06361 
06362       // If X has a different width than the result/lhs, sext it or truncate it.
06363       unsigned VTWidth = VT.getSizeInBits();
06364       if (OrigXWidth < VTWidth) {
06365         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
06366         AddToWorklist(X.getNode());
06367       } else if (OrigXWidth > VTWidth) {
06368         // To get the sign bit in the right place, we have to shift it right
06369         // before truncating.
06370         X = DAG.getNode(ISD::SRL, SDLoc(X),
06371                         X.getValueType(), X,
06372                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
06373         AddToWorklist(X.getNode());
06374         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
06375         AddToWorklist(X.getNode());
06376       }
06377 
06378       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
06379       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
06380                       X, DAG.getConstant(SignBit, VT));
06381       AddToWorklist(X.getNode());
06382 
06383       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
06384                                 VT, N0.getOperand(0));
06385       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
06386                         Cst, DAG.getConstant(~SignBit, VT));
06387       AddToWorklist(Cst.getNode());
06388 
06389       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
06390     }
06391   }
06392 
06393   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
06394   if (N0.getOpcode() == ISD::BUILD_PAIR) {
06395     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
06396     if (CombineLD.getNode())
06397       return CombineLD;
06398   }
06399 
06400   return SDValue();
06401 }
06402 
06403 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
06404   EVT VT = N->getValueType(0);
06405   return CombineConsecutiveLoads(N, VT);
06406 }
06407 
06408 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
06409 /// operands. DstEltVT indicates the destination element value type.
06410 SDValue DAGCombiner::
06411 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
06412   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
06413 
06414   // If this is already the right type, we're done.
06415   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
06416 
06417   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
06418   unsigned DstBitSize = DstEltVT.getSizeInBits();
06419 
06420   // If this is a conversion of N elements of one type to N elements of another
06421   // type, convert each element.  This handles FP<->INT cases.
06422   if (SrcBitSize == DstBitSize) {
06423     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
06424                               BV->getValueType(0).getVectorNumElements());
06425 
06426     // Due to the FP element handling below calling this routine recursively,
06427     // we can end up with a scalar-to-vector node here.
06428     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
06429       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
06430                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
06431                                      DstEltVT, BV->getOperand(0)));
06432 
06433     SmallVector<SDValue, 8> Ops;
06434     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
06435       SDValue Op = BV->getOperand(i);
06436       // If the vector element type is not legal, the BUILD_VECTOR operands
06437       // are promoted and implicitly truncated.  Make that explicit here.
06438       if (Op.getValueType() != SrcEltVT)
06439         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
06440       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
06441                                 DstEltVT, Op));
06442       AddToWorklist(Ops.back().getNode());
06443     }
06444     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
06445   }
06446 
06447   // Otherwise, we're growing or shrinking the elements.  To avoid having to
06448   // handle annoying details of growing/shrinking FP values, we convert them to
06449   // int first.
06450   if (SrcEltVT.isFloatingPoint()) {
06451     // Convert the input float vector to a int vector where the elements are the
06452     // same sizes.
06453     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
06454     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
06455     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
06456     SrcEltVT = IntVT;
06457   }
06458 
06459   // Now we know the input is an integer vector.  If the output is a FP type,
06460   // convert to integer first, then to FP of the right size.
06461   if (DstEltVT.isFloatingPoint()) {
06462     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
06463     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
06464     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
06465 
06466     // Next, convert to FP elements of the same size.
06467     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
06468   }
06469 
06470   // Okay, we know the src/dst types are both integers of differing types.
06471   // Handling growing first.
06472   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
06473   if (SrcBitSize < DstBitSize) {
06474     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
06475 
06476     SmallVector<SDValue, 8> Ops;
06477     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
06478          i += NumInputsPerOutput) {
06479       bool isLE = TLI.isLittleEndian();
06480       APInt NewBits = APInt(DstBitSize, 0);
06481       bool EltIsUndef = true;
06482       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
06483         // Shift the previously computed bits over.
06484         NewBits <<= SrcBitSize;
06485         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
06486         if (Op.getOpcode() == ISD::UNDEF) continue;
06487         EltIsUndef = false;
06488 
06489         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
06490                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
06491       }
06492 
06493       if (EltIsUndef)
06494         Ops.push_back(DAG.getUNDEF(DstEltVT));
06495       else
06496         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
06497     }
06498 
06499     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
06500     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
06501   }
06502 
06503   // Finally, this must be the case where we are shrinking elements: each input
06504   // turns into multiple outputs.
06505   bool isS2V = ISD::isScalarToVector(BV);
06506   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
06507   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
06508                             NumOutputsPerInput*BV->getNumOperands());
06509   SmallVector<SDValue, 8> Ops;
06510 
06511   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
06512     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
06513       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
06514         Ops.push_back(DAG.getUNDEF(DstEltVT));
06515       continue;
06516     }
06517 
06518     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
06519                   getAPIntValue().zextOrTrunc(SrcBitSize);
06520 
06521     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
06522       APInt ThisVal = OpVal.trunc(DstBitSize);
06523       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
06524       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
06525         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
06526         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
06527                            Ops[0]);
06528       OpVal = OpVal.lshr(DstBitSize);
06529     }
06530 
06531     // For big endian targets, swap the order of the pieces of each element.
06532     if (TLI.isBigEndian())
06533       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
06534   }
06535 
06536   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
06537 }
06538 
06539 SDValue DAGCombiner::visitFADD(SDNode *N) {
06540   SDValue N0 = N->getOperand(0);
06541   SDValue N1 = N->getOperand(1);
06542   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
06543   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
06544   EVT VT = N->getValueType(0);
06545   const TargetOptions &Options = DAG.getTarget().Options;
06546   
06547   // fold vector ops
06548   if (VT.isVector()) {
06549     SDValue FoldedVOp = SimplifyVBinOp(N);
06550     if (FoldedVOp.getNode()) return FoldedVOp;
06551   }
06552 
06553   // fold (fadd c1, c2) -> c1 + c2
06554   if (N0CFP && N1CFP)
06555     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
06556 
06557   // canonicalize constant to RHS
06558   if (N0CFP && !N1CFP)
06559     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
06560 
06561   // fold (fadd A, (fneg B)) -> (fsub A, B)
06562   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
06563       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
06564     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
06565                        GetNegatedExpression(N1, DAG, LegalOperations));
06566   
06567   // fold (fadd (fneg A), B) -> (fsub B, A)
06568   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
06569       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
06570     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
06571                        GetNegatedExpression(N0, DAG, LegalOperations));
06572 
06573   // If 'unsafe math' is enabled, fold lots of things.
06574   if (Options.UnsafeFPMath) {
06575     // No FP constant should be created after legalization as Instruction
06576     // Selection pass has a hard time dealing with FP constants.
06577     bool AllowNewConst = (Level < AfterLegalizeDAG);
06578     
06579     // fold (fadd A, 0) -> A
06580     if (N1CFP && N1CFP->getValueAPF().isZero())
06581       return N0;
06582 
06583     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
06584     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
06585         isa<ConstantFPSDNode>(N0.getOperand(1)))
06586       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
06587                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
06588                                      N0.getOperand(1), N1));
06589     
06590     // If allowed, fold (fadd (fneg x), x) -> 0.0
06591     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
06592       return DAG.getConstantFP(0.0, VT);
06593     
06594     // If allowed, fold (fadd x, (fneg x)) -> 0.0
06595     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
06596       return DAG.getConstantFP(0.0, VT);
06597     
06598     // We can fold chains of FADD's of the same value into multiplications.
06599     // This transform is not safe in general because we are reducing the number
06600     // of rounding steps.
06601     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
06602       if (N0.getOpcode() == ISD::FMUL) {
06603         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
06604         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
06605         
06606         // (fadd (fmul x, c), x) -> (fmul x, c+1)
06607         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
06608           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
06609                                        SDValue(CFP01, 0),
06610                                        DAG.getConstantFP(1.0, VT));
06611           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
06612         }
06613         
06614         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
06615         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
06616             N1.getOperand(0) == N1.getOperand(1) &&
06617             N0.getOperand(0) == N1.getOperand(0)) {
06618           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
06619                                        SDValue(CFP01, 0),
06620                                        DAG.getConstantFP(2.0, VT));
06621           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
06622                              N0.getOperand(0), NewCFP);
06623         }
06624       }
06625       
06626       if (N1.getOpcode() == ISD::FMUL) {
06627         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
06628         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
06629         
06630         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
06631         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
06632           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
06633                                        SDValue(CFP11, 0),
06634                                        DAG.getConstantFP(1.0, VT));
06635           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
06636         }
06637 
06638         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
06639         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
06640             N0.getOperand(0) == N0.getOperand(1) &&
06641             N1.getOperand(0) == N0.getOperand(0)) {
06642           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
06643                                        SDValue(CFP11, 0),
06644                                        DAG.getConstantFP(2.0, VT));
06645           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
06646         }
06647       }
06648 
06649       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
06650         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
06651         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
06652         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
06653             (N0.getOperand(0) == N1))
06654           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
06655                              N1, DAG.getConstantFP(3.0, VT));
06656       }
06657       
06658       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
06659         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
06660         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
06661         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
06662             N1.getOperand(0) == N0)
06663           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
06664                              N0, DAG.getConstantFP(3.0, VT));
06665       }
06666       
06667       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
06668       if (AllowNewConst &&
06669           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
06670           N0.getOperand(0) == N0.getOperand(1) &&
06671           N1.getOperand(0) == N1.getOperand(1) &&
06672           N0.getOperand(0) == N1.getOperand(0))
06673         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
06674                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
06675     }
06676   } // enable-unsafe-fp-math
06677   
06678   // FADD -> FMA combines:
06679   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
06680       DAG.getTarget()
06681           .getSubtargetImpl()
06682           ->getTargetLowering()
06683           ->isFMAFasterThanFMulAndFAdd(VT) &&
06684       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
06685 
06686     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
06687     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
06688       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
06689                          N0.getOperand(0), N0.getOperand(1), N1);
06690 
06691     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
06692     // Note: Commutes FADD operands.
06693     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
06694       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
06695                          N1.getOperand(0), N1.getOperand(1), N0);
06696   }
06697 
06698   return SDValue();
06699 }
06700 
06701 SDValue DAGCombiner::visitFSUB(SDNode *N) {
06702   SDValue N0 = N->getOperand(0);
06703   SDValue N1 = N->getOperand(1);
06704   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
06705   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
06706   EVT VT = N->getValueType(0);
06707   SDLoc dl(N);
06708   const TargetOptions &Options = DAG.getTarget().Options;
06709 
06710   // fold vector ops
06711   if (VT.isVector()) {
06712     SDValue FoldedVOp = SimplifyVBinOp(N);
06713     if (FoldedVOp.getNode()) return FoldedVOp;
06714   }
06715 
06716   // fold (fsub c1, c2) -> c1-c2
06717   if (N0CFP && N1CFP)
06718     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
06719 
06720   // fold (fsub A, (fneg B)) -> (fadd A, B)
06721   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
06722     return DAG.getNode(ISD::FADD, dl, VT, N0,
06723                        GetNegatedExpression(N1, DAG, LegalOperations));
06724 
06725   // If 'unsafe math' is enabled, fold lots of things.
06726   if (Options.UnsafeFPMath) {
06727     // (fsub A, 0) -> A
06728     if (N1CFP && N1CFP->getValueAPF().isZero())
06729       return N0;
06730 
06731     // (fsub 0, B) -> -B
06732     if (N0CFP && N0CFP->getValueAPF().isZero()) {
06733       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
06734         return GetNegatedExpression(N1, DAG, LegalOperations);
06735       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
06736         return DAG.getNode(ISD::FNEG, dl, VT, N1);
06737     }
06738 
06739     // (fsub x, x) -> 0.0
06740     if (N0 == N1)
06741       return DAG.getConstantFP(0.0f, VT);
06742 
06743     // (fsub x, (fadd x, y)) -> (fneg y)
06744     // (fsub x, (fadd y, x)) -> (fneg y)
06745     if (N1.getOpcode() == ISD::FADD) {
06746       SDValue N10 = N1->getOperand(0);
06747       SDValue N11 = N1->getOperand(1);
06748 
06749       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
06750         return GetNegatedExpression(N11, DAG, LegalOperations);
06751 
06752       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
06753         return GetNegatedExpression(N10, DAG, LegalOperations);
06754     }
06755   }
06756 
06757   // FSUB -> FMA combines:
06758   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
06759       DAG.getTarget().getSubtargetImpl()
06760           ->getTargetLowering()
06761           ->isFMAFasterThanFMulAndFAdd(VT) &&
06762       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
06763 
06764     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
06765     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
06766       return DAG.getNode(ISD::FMA, dl, VT,
06767                          N0.getOperand(0), N0.getOperand(1),
06768                          DAG.getNode(ISD::FNEG, dl, VT, N1));
06769 
06770     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
06771     // Note: Commutes FSUB operands.
06772     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
06773       return DAG.getNode(ISD::FMA, dl, VT,
06774                          DAG.getNode(ISD::FNEG, dl, VT,
06775                          N1.getOperand(0)),
06776                          N1.getOperand(1), N0);
06777 
06778     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
06779     if (N0.getOpcode() == ISD::FNEG &&
06780         N0.getOperand(0).getOpcode() == ISD::FMUL &&
06781         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
06782       SDValue N00 = N0.getOperand(0).getOperand(0);
06783       SDValue N01 = N0.getOperand(0).getOperand(1);
06784       return DAG.getNode(ISD::FMA, dl, VT,
06785                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
06786                          DAG.getNode(ISD::FNEG, dl, VT, N1));
06787     }
06788   }
06789 
06790   return SDValue();
06791 }
06792 
06793 SDValue DAGCombiner::visitFMUL(SDNode *N) {
06794   SDValue N0 = N->getOperand(0);
06795   SDValue N1 = N->getOperand(1);
06796   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
06797   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
06798   EVT VT = N->getValueType(0);
06799   const TargetOptions &Options = DAG.getTarget().Options;
06800 
06801   // fold vector ops
06802   if (VT.isVector()) {
06803     // This just handles C1 * C2 for vectors. Other vector folds are below.
06804     SDValue FoldedVOp = SimplifyVBinOp(N);
06805     if (FoldedVOp.getNode())
06806       return FoldedVOp;
06807     // Canonicalize vector constant to RHS.
06808     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
06809         N1.getOpcode() != ISD::BUILD_VECTOR)
06810       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
06811         if (BV0->isConstant())
06812           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
06813   }
06814 
06815   // fold (fmul c1, c2) -> c1*c2
06816   if (N0CFP && N1CFP)
06817     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
06818 
06819   // canonicalize constant to RHS
06820   if (N0CFP && !N1CFP)
06821     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
06822 
06823   // fold (fmul A, 1.0) -> A
06824   if (N1CFP && N1CFP->isExactlyValue(1.0))
06825     return N0;
06826 
06827   if (Options.UnsafeFPMath) {
06828     // fold (fmul A, 0) -> 0
06829     if (N1CFP && N1CFP->getValueAPF().isZero())
06830       return N1;
06831 
06832     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
06833     if (N0.getOpcode() == ISD::FMUL) {
06834       // Fold scalars or any vector constants (not just splats).
06835       // This fold is done in general by InstCombine, but extra fmul insts
06836       // may have been generated during lowering.
06837       SDValue N01 = N0.getOperand(1);
06838       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
06839       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
06840       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
06841           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
06842         SDLoc SL(N);
06843         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
06844         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
06845       }
06846     }
06847 
06848     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
06849     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
06850     // during an early run of DAGCombiner can prevent folding with fmuls
06851     // inserted during lowering.
06852     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
06853       SDLoc SL(N);
06854       const SDValue Two = DAG.getConstantFP(2.0, VT);
06855       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
06856       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
06857     }
06858   }
06859 
06860   // fold (fmul X, 2.0) -> (fadd X, X)
06861   if (N1CFP && N1CFP->isExactlyValue(+2.0))
06862     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
06863 
06864   // fold (fmul X, -1.0) -> (fneg X)
06865   if (N1CFP && N1CFP->isExactlyValue(-1.0))
06866     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
06867       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
06868 
06869   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
06870   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
06871     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
06872       // Both can be negated for free, check to see if at least one is cheaper
06873       // negated.
06874       if (LHSNeg == 2 || RHSNeg == 2)
06875         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
06876                            GetNegatedExpression(N0, DAG, LegalOperations),
06877                            GetNegatedExpression(N1, DAG, LegalOperations));
06878     }
06879   }
06880 
06881   return SDValue();
06882 }
06883 
06884 SDValue DAGCombiner::visitFMA(SDNode *N) {
06885   SDValue N0 = N->getOperand(0);
06886   SDValue N1 = N->getOperand(1);
06887   SDValue N2 = N->getOperand(2);
06888   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
06889   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
06890   EVT VT = N->getValueType(0);
06891   SDLoc dl(N);
06892   const TargetOptions &Options = DAG.getTarget().Options;
06893 
06894   // Constant fold FMA.
06895   if (isa<ConstantFPSDNode>(N0) &&
06896       isa<ConstantFPSDNode>(N1) &&
06897       isa<ConstantFPSDNode>(N2)) {
06898     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
06899   }
06900 
06901   if (Options.UnsafeFPMath) {
06902     if (N0CFP && N0CFP->isZero())
06903       return N2;
06904     if (N1CFP && N1CFP->isZero())
06905       return N2;
06906   }
06907   if (N0CFP && N0CFP->isExactlyValue(1.0))
06908     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
06909   if (N1CFP && N1CFP->isExactlyValue(1.0))
06910     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
06911 
06912   // Canonicalize (fma c, x, y) -> (fma x, c, y)
06913   if (N0CFP && !N1CFP)
06914     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
06915 
06916   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
06917   if (Options.UnsafeFPMath && N1CFP &&
06918       N2.getOpcode() == ISD::FMUL &&
06919       N0 == N2.getOperand(0) &&
06920       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
06921     return DAG.getNode(ISD::FMUL, dl, VT, N0,
06922                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
06923   }
06924 
06925 
06926   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
06927   if (Options.UnsafeFPMath &&
06928       N0.getOpcode() == ISD::FMUL && N1CFP &&
06929       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
06930     return DAG.getNode(ISD::FMA, dl, VT,
06931                        N0.getOperand(0),
06932                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
06933                        N2);
06934   }
06935 
06936   // (fma x, 1, y) -> (fadd x, y)
06937   // (fma x, -1, y) -> (fadd (fneg x), y)
06938   if (N1CFP) {
06939     if (N1CFP->isExactlyValue(1.0))
06940       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
06941 
06942     if (N1CFP->isExactlyValue(-1.0) &&
06943         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
06944       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
06945       AddToWorklist(RHSNeg.getNode());
06946       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
06947     }
06948   }
06949 
06950   // (fma x, c, x) -> (fmul x, (c+1))
06951   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
06952     return DAG.getNode(ISD::FMUL, dl, VT, N0,
06953                        DAG.getNode(ISD::FADD, dl, VT,
06954                                    N1, DAG.getConstantFP(1.0, VT)));
06955 
06956   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
06957   if (Options.UnsafeFPMath && N1CFP &&
06958       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
06959     return DAG.getNode(ISD::FMUL, dl, VT, N0,
06960                        DAG.getNode(ISD::FADD, dl, VT,
06961                                    N1, DAG.getConstantFP(-1.0, VT)));
06962 
06963 
06964   return SDValue();
06965 }
06966 
06967 SDValue DAGCombiner::visitFDIV(SDNode *N) {
06968   SDValue N0 = N->getOperand(0);
06969   SDValue N1 = N->getOperand(1);
06970   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
06971   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
06972   EVT VT = N->getValueType(0);
06973   const TargetOptions &Options = DAG.getTarget().Options;
06974 
06975   // fold vector ops
06976   if (VT.isVector()) {
06977     SDValue FoldedVOp = SimplifyVBinOp(N);
06978     if (FoldedVOp.getNode()) return FoldedVOp;
06979   }
06980 
06981   // fold (fdiv c1, c2) -> c1/c2
06982   if (N0CFP && N1CFP)
06983     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
06984 
06985   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
06986   if (N1CFP && Options.UnsafeFPMath) {
06987     // Compute the reciprocal 1.0 / c2.
06988     APFloat N1APF = N1CFP->getValueAPF();
06989     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
06990     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
06991     // Only do the transform if the reciprocal is a legal fp immediate that
06992     // isn't too nasty (eg NaN, denormal, ...).
06993     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
06994         (!LegalOperations ||
06995          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
06996          // backend)... we should handle this gracefully after Legalize.
06997          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
06998          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
06999          TLI.isFPImmLegal(Recip, VT)))
07000       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
07001                          DAG.getConstantFP(Recip, VT));
07002   }
07003 
07004   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
07005   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
07006     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
07007       // Both can be negated for free, check to see if at least one is cheaper
07008       // negated.
07009       if (LHSNeg == 2 || RHSNeg == 2)
07010         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
07011                            GetNegatedExpression(N0, DAG, LegalOperations),
07012                            GetNegatedExpression(N1, DAG, LegalOperations));
07013     }
07014   }
07015 
07016   return SDValue();
07017 }
07018 
07019 SDValue DAGCombiner::visitFREM(SDNode *N) {
07020   SDValue N0 = N->getOperand(0);
07021   SDValue N1 = N->getOperand(1);
07022   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07023   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
07024   EVT VT = N->getValueType(0);
07025 
07026   // fold (frem c1, c2) -> fmod(c1,c2)
07027   if (N0CFP && N1CFP)
07028     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
07029 
07030   return SDValue();
07031 }
07032 
07033 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
07034   SDValue N0 = N->getOperand(0);
07035   SDValue N1 = N->getOperand(1);
07036   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07037   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
07038   EVT VT = N->getValueType(0);
07039 
07040   if (N0CFP && N1CFP)  // Constant fold
07041     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
07042 
07043   if (N1CFP) {
07044     const APFloat& V = N1CFP->getValueAPF();
07045     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
07046     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
07047     if (!V.isNegative()) {
07048       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
07049         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
07050     } else {
07051       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
07052         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
07053                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
07054     }
07055   }
07056 
07057   // copysign(fabs(x), y) -> copysign(x, y)
07058   // copysign(fneg(x), y) -> copysign(x, y)
07059   // copysign(copysign(x,z), y) -> copysign(x, y)
07060   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
07061       N0.getOpcode() == ISD::FCOPYSIGN)
07062     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
07063                        N0.getOperand(0), N1);
07064 
07065   // copysign(x, abs(y)) -> abs(x)
07066   if (N1.getOpcode() == ISD::FABS)
07067     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
07068 
07069   // copysign(x, copysign(y,z)) -> copysign(x, z)
07070   if (N1.getOpcode() == ISD::FCOPYSIGN)
07071     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
07072                        N0, N1.getOperand(1));
07073 
07074   // copysign(x, fp_extend(y)) -> copysign(x, y)
07075   // copysign(x, fp_round(y)) -> copysign(x, y)
07076   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
07077     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
07078                        N0, N1.getOperand(0));
07079 
07080   return SDValue();
07081 }
07082 
07083 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
07084   SDValue N0 = N->getOperand(0);
07085   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
07086   EVT VT = N->getValueType(0);
07087   EVT OpVT = N0.getValueType();
07088 
07089   // fold (sint_to_fp c1) -> c1fp
07090   if (N0C &&
07091       // ...but only if the target supports immediate floating-point values
07092       (!LegalOperations ||
07093        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
07094     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
07095 
07096   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
07097   // but UINT_TO_FP is legal on this target, try to convert.
07098   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
07099       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
07100     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
07101     if (DAG.SignBitIsZero(N0))
07102       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
07103   }
07104 
07105   // The next optimizations are desirable only if SELECT_CC can be lowered.
07106   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
07107     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
07108     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
07109         !VT.isVector() &&
07110         (!LegalOperations ||
07111          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
07112       SDValue Ops[] =
07113         { N0.getOperand(0), N0.getOperand(1),
07114           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
07115           N0.getOperand(2) };
07116       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
07117     }
07118 
07119     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
07120     //      (select_cc x, y, 1.0, 0.0,, cc)
07121     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
07122         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
07123         (!LegalOperations ||
07124          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
07125       SDValue Ops[] =
07126         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
07127           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
07128           N0.getOperand(0).getOperand(2) };
07129       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
07130     }
07131   }
07132 
07133   return SDValue();
07134 }
07135 
07136 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
07137   SDValue N0 = N->getOperand(0);
07138   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
07139   EVT VT = N->getValueType(0);
07140   EVT OpVT = N0.getValueType();
07141 
07142   // fold (uint_to_fp c1) -> c1fp
07143   if (N0C &&
07144       // ...but only if the target supports immediate floating-point values
07145       (!LegalOperations ||
07146        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
07147     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
07148 
07149   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
07150   // but SINT_TO_FP is legal on this target, try to convert.
07151   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
07152       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
07153     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
07154     if (DAG.SignBitIsZero(N0))
07155       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
07156   }
07157 
07158   // The next optimizations are desirable only if SELECT_CC can be lowered.
07159   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
07160     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
07161 
07162     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
07163         (!LegalOperations ||
07164          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
07165       SDValue Ops[] =
07166         { N0.getOperand(0), N0.getOperand(1),
07167           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
07168           N0.getOperand(2) };
07169       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
07170     }
07171   }
07172 
07173   return SDValue();
07174 }
07175 
07176 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
07177   SDValue N0 = N->getOperand(0);
07178   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07179   EVT VT = N->getValueType(0);
07180 
07181   // fold (fp_to_sint c1fp) -> c1
07182   if (N0CFP)
07183     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
07184 
07185   return SDValue();
07186 }
07187 
07188 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
07189   SDValue N0 = N->getOperand(0);
07190   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07191   EVT VT = N->getValueType(0);
07192 
07193   // fold (fp_to_uint c1fp) -> c1
07194   if (N0CFP)
07195     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
07196 
07197   return SDValue();
07198 }
07199 
07200 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
07201   SDValue N0 = N->getOperand(0);
07202   SDValue N1 = N->getOperand(1);
07203   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07204   EVT VT = N->getValueType(0);
07205 
07206   // fold (fp_round c1fp) -> c1fp
07207   if (N0CFP)
07208     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
07209 
07210   // fold (fp_round (fp_extend x)) -> x
07211   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
07212     return N0.getOperand(0);
07213 
07214   // fold (fp_round (fp_round x)) -> (fp_round x)
07215   if (N0.getOpcode() == ISD::FP_ROUND) {
07216     // This is a value preserving truncation if both round's are.
07217     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
07218                    N0.getNode()->getConstantOperandVal(1) == 1;
07219     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
07220                        DAG.getIntPtrConstant(IsTrunc));
07221   }
07222 
07223   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
07224   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
07225     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
07226                               N0.getOperand(0), N1);
07227     AddToWorklist(Tmp.getNode());
07228     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
07229                        Tmp, N0.getOperand(1));
07230   }
07231 
07232   return SDValue();
07233 }
07234 
07235 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
07236   SDValue N0 = N->getOperand(0);
07237   EVT VT = N->getValueType(0);
07238   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
07239   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07240 
07241   // fold (fp_round_inreg c1fp) -> c1fp
07242   if (N0CFP && isTypeLegal(EVT)) {
07243     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
07244     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
07245   }
07246 
07247   return SDValue();
07248 }
07249 
07250 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
07251   SDValue N0 = N->getOperand(0);
07252   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07253   EVT VT = N->getValueType(0);
07254 
07255   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
07256   if (N->hasOneUse() &&
07257       N->use_begin()->getOpcode() == ISD::FP_ROUND)
07258     return SDValue();
07259 
07260   // fold (fp_extend c1fp) -> c1fp
07261   if (N0CFP)
07262     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
07263 
07264   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
07265   // value of X.
07266   if (N0.getOpcode() == ISD::FP_ROUND
07267       && N0.getNode()->getConstantOperandVal(1) == 1) {
07268     SDValue In = N0.getOperand(0);
07269     if (In.getValueType() == VT) return In;
07270     if (VT.bitsLT(In.getValueType()))
07271       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
07272                          In, N0.getOperand(1));
07273     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
07274   }
07275 
07276   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
07277   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
07278        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
07279     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
07280     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
07281                                      LN0->getChain(),
07282                                      LN0->getBasePtr(), N0.getValueType(),
07283                                      LN0->getMemOperand());
07284     CombineTo(N, ExtLoad);
07285     CombineTo(N0.getNode(),
07286               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
07287                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
07288               ExtLoad.getValue(1));
07289     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
07290   }
07291 
07292   return SDValue();
07293 }
07294 
07295 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
07296   SDValue N0 = N->getOperand(0);
07297   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07298   EVT VT = N->getValueType(0);
07299 
07300   // fold (fceil c1) -> fceil(c1)
07301   if (N0CFP)
07302     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
07303 
07304   return SDValue();
07305 }
07306 
07307 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
07308   SDValue N0 = N->getOperand(0);
07309   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07310   EVT VT = N->getValueType(0);
07311 
07312   // fold (ftrunc c1) -> ftrunc(c1)
07313   if (N0CFP)
07314     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
07315 
07316   return SDValue();
07317 }
07318 
07319 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
07320   SDValue N0 = N->getOperand(0);
07321   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
07322   EVT VT = N->getValueType(0);
07323 
07324   // fold (ffloor c1) -> ffloor(c1)
07325   if (N0CFP)
07326     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
07327 
07328   return SDValue();
07329 }
07330 
07331 // FIXME: FNEG and FABS have a lot in common; refactor.
07332 SDValue DAGCombiner::visitFNEG(SDNode *N) {
07333   SDValue N0 = N->getOperand(0);
07334   EVT VT = N->getValueType(0);
07335 
07336   if (VT.isVector()) {
07337     SDValue FoldedVOp = SimplifyVUnaryOp(N);
07338     if (FoldedVOp.getNode()) return FoldedVOp;
07339   }
07340 
07341   // Constant fold FNEG.
07342   if (isa<ConstantFPSDNode>(N0))
07343     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
07344 
07345   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
07346                          &DAG.getTarget().Options))
07347     return GetNegatedExpression(N0, DAG, LegalOperations);
07348 
07349   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
07350   // constant pool values.
07351   if (!TLI.isFNegFree(VT) &&
07352       N0.getOpcode() == ISD::BITCAST &&
07353       N0.getNode()->hasOneUse()) {
07354     SDValue Int = N0.getOperand(0);
07355     EVT IntVT = Int.getValueType();
07356     if (IntVT.isInteger() && !IntVT.isVector()) {
07357       APInt SignMask;
07358       if (N0.getValueType().isVector()) {
07359         // For a vector, get a mask such as 0x80... per scalar element
07360         // and splat it.
07361         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
07362         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
07363       } else {
07364         // For a scalar, just generate 0x80...
07365         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
07366       }
07367       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
07368                         DAG.getConstant(SignMask, IntVT));
07369       AddToWorklist(Int.getNode());
07370       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
07371     }
07372   }
07373 
07374   // (fneg (fmul c, x)) -> (fmul -c, x)
07375   if (N0.getOpcode() == ISD::FMUL) {
07376     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
07377     if (CFP1) {
07378       APFloat CVal = CFP1->getValueAPF();
07379       CVal.changeSign();
07380       if (Level >= AfterLegalizeDAG &&
07381           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
07382            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
07383         return DAG.getNode(
07384             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
07385             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
07386     }
07387   }
07388 
07389   return SDValue();
07390 }
07391 
07392 SDValue DAGCombiner::visitFABS(SDNode *N) {
07393   SDValue N0 = N->getOperand(0);
07394   EVT VT = N->getValueType(0);
07395 
07396   if (VT.isVector()) {
07397     SDValue FoldedVOp = SimplifyVUnaryOp(N);
07398     if (FoldedVOp.getNode()) return FoldedVOp;
07399   }
07400 
07401   // fold (fabs c1) -> fabs(c1)
07402   if (isa<ConstantFPSDNode>(N0))
07403     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
07404   
07405   // fold (fabs (fabs x)) -> (fabs x)
07406   if (N0.getOpcode() == ISD::FABS)
07407     return N->getOperand(0);
07408 
07409   // fold (fabs (fneg x)) -> (fabs x)
07410   // fold (fabs (fcopysign x, y)) -> (fabs x)
07411   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
07412     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
07413 
07414   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
07415   // constant pool values.
07416   if (!TLI.isFAbsFree(VT) &&
07417       N0.getOpcode() == ISD::BITCAST &&
07418       N0.getNode()->hasOneUse()) {
07419     SDValue Int = N0.getOperand(0);
07420     EVT IntVT = Int.getValueType();
07421     if (IntVT.isInteger() && !IntVT.isVector()) {
07422       APInt SignMask;
07423       if (N0.getValueType().isVector()) {
07424         // For a vector, get a mask such as 0x7f... per scalar element
07425         // and splat it.
07426         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
07427         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
07428       } else {
07429         // For a scalar, just generate 0x7f...
07430         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
07431       }
07432       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
07433                         DAG.getConstant(SignMask, IntVT));
07434       AddToWorklist(Int.getNode());
07435       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
07436     }
07437   }
07438 
07439   return SDValue();
07440 }
07441 
07442 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
07443   SDValue Chain = N->getOperand(0);
07444   SDValue N1 = N->getOperand(1);
07445   SDValue N2 = N->getOperand(2);
07446 
07447   // If N is a constant we could fold this into a fallthrough or unconditional
07448   // branch. However that doesn't happen very often in normal code, because
07449   // Instcombine/SimplifyCFG should have handled the available opportunities.
07450   // If we did this folding here, it would be necessary to update the
07451   // MachineBasicBlock CFG, which is awkward.
07452 
07453   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
07454   // on the target.
07455   if (N1.getOpcode() == ISD::SETCC &&
07456       TLI.isOperationLegalOrCustom(ISD::BR_CC,
07457                                    N1.getOperand(0).getValueType())) {
07458     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
07459                        Chain, N1.getOperand(2),
07460                        N1.getOperand(0), N1.getOperand(1), N2);
07461   }
07462 
07463   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
07464       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
07465        (N1.getOperand(0).hasOneUse() &&
07466         N1.getOperand(0).getOpcode() == ISD::SRL))) {
07467     SDNode *Trunc = nullptr;
07468     if (N1.getOpcode() == ISD::TRUNCATE) {
07469       // Look pass the truncate.
07470       Trunc = N1.getNode();
07471       N1 = N1.getOperand(0);
07472     }
07473 
07474     // Match this pattern so that we can generate simpler code:
07475     //
07476     //   %a = ...
07477     //   %b = and i32 %a, 2
07478     //   %c = srl i32 %b, 1
07479     //   brcond i32 %c ...
07480     //
07481     // into
07482     //
07483     //   %a = ...
07484     //   %b = and i32 %a, 2
07485     //   %c = setcc eq %b, 0
07486     //   brcond %c ...
07487     //
07488     // This applies only when the AND constant value has one bit set and the
07489     // SRL constant is equal to the log2 of the AND constant. The back-end is
07490     // smart enough to convert the result into a TEST/JMP sequence.
07491     SDValue Op0 = N1.getOperand(0);
07492     SDValue Op1 = N1.getOperand(1);
07493 
07494     if (Op0.getOpcode() == ISD::AND &&
07495         Op1.getOpcode() == ISD::Constant) {
07496       SDValue AndOp1 = Op0.getOperand(1);
07497 
07498       if (AndOp1.getOpcode() == ISD::Constant) {
07499         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
07500 
07501         if (AndConst.isPowerOf2() &&
07502             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
07503           SDValue SetCC =
07504             DAG.getSetCC(SDLoc(N),
07505                          getSetCCResultType(Op0.getValueType()),
07506                          Op0, DAG.getConstant(0, Op0.getValueType()),
07507                          ISD::SETNE);
07508 
07509           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
07510                                           MVT::Other, Chain, SetCC, N2);
07511           // Don't add the new BRCond into the worklist or else SimplifySelectCC
07512           // will convert it back to (X & C1) >> C2.
07513           CombineTo(N, NewBRCond, false);
07514           // Truncate is dead.
07515           if (Trunc)
07516             deleteAndRecombine(Trunc);
07517           // Replace the uses of SRL with SETCC
07518           WorklistRemover DeadNodes(*this);
07519           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
07520           deleteAndRecombine(N1.getNode());
07521           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
07522         }
07523       }
07524     }
07525 
07526     if (Trunc)
07527       // Restore N1 if the above transformation doesn't match.
07528       N1 = N->getOperand(1);
07529   }
07530 
07531   // Transform br(xor(x, y)) -> br(x != y)
07532   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
07533   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
07534     SDNode *TheXor = N1.getNode();
07535     SDValue Op0 = TheXor->getOperand(0);
07536     SDValue Op1 = TheXor->getOperand(1);
07537     if (Op0.getOpcode() == Op1.getOpcode()) {
07538       // Avoid missing important xor optimizations.
07539       SDValue Tmp = visitXOR(TheXor);
07540       if (Tmp.getNode()) {
07541         if (Tmp.getNode() != TheXor) {
07542           DEBUG(dbgs() << "\nReplacing.8 ";
07543                 TheXor->dump(&DAG);
07544                 dbgs() << "\nWith: ";
07545                 Tmp.getNode()->dump(&DAG);
07546                 dbgs() << '\n');
07547           WorklistRemover DeadNodes(*this);
07548           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
07549           deleteAndRecombine(TheXor);
07550           return DAG.getNode(ISD::BRCOND, SDLoc(N),
07551                              MVT::Other, Chain, Tmp, N2);
07552         }
07553 
07554         // visitXOR has changed XOR's operands or replaced the XOR completely,
07555         // bail out.
07556         return SDValue(N, 0);
07557       }
07558     }
07559 
07560     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
07561       bool Equal = false;
07562       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
07563         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
07564             Op0.getOpcode() == ISD::XOR) {
07565           TheXor = Op0.getNode();
07566           Equal = true;
07567         }
07568 
07569       EVT SetCCVT = N1.getValueType();
07570       if (LegalTypes)
07571         SetCCVT = getSetCCResultType(SetCCVT);
07572       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
07573                                    SetCCVT,
07574                                    Op0, Op1,
07575                                    Equal ? ISD::SETEQ : ISD::SETNE);
07576       // Replace the uses of XOR with SETCC
07577       WorklistRemover DeadNodes(*this);
07578       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
07579       deleteAndRecombine(N1.getNode());
07580       return DAG.getNode(ISD::BRCOND, SDLoc(N),
07581                          MVT::Other, Chain, SetCC, N2);
07582     }
07583   }
07584 
07585   return SDValue();
07586 }
07587 
07588 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
07589 //
07590 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
07591   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
07592   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
07593 
07594   // If N is a constant we could fold this into a fallthrough or unconditional
07595   // branch. However that doesn't happen very often in normal code, because
07596   // Instcombine/SimplifyCFG should have handled the available opportunities.
07597   // If we did this folding here, it would be necessary to update the
07598   // MachineBasicBlock CFG, which is awkward.
07599 
07600   // Use SimplifySetCC to simplify SETCC's.
07601   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
07602                                CondLHS, CondRHS, CC->get(), SDLoc(N),
07603                                false);
07604   if (Simp.getNode()) AddToWorklist(Simp.getNode());
07605 
07606   // fold to a simpler setcc
07607   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
07608     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
07609                        N->getOperand(0), Simp.getOperand(2),
07610                        Simp.getOperand(0), Simp.getOperand(1),
07611                        N->getOperand(4));
07612 
07613   return SDValue();
07614 }
07615 
07616 /// Return true if 'Use' is a load or a store that uses N as its base pointer
07617 /// and that N may be folded in the load / store addressing mode.
07618 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
07619                                     SelectionDAG &DAG,
07620                                     const TargetLowering &TLI) {
07621   EVT VT;
07622   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
07623     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
07624       return false;
07625     VT = Use->getValueType(0);
07626   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
07627     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
07628       return false;
07629     VT = ST->getValue().getValueType();
07630   } else
07631     return false;
07632 
07633   TargetLowering::AddrMode AM;
07634   if (N->getOpcode() == ISD::ADD) {
07635     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
07636     if (Offset)
07637       // [reg +/- imm]
07638       AM.BaseOffs = Offset->getSExtValue();
07639     else
07640       // [reg +/- reg]
07641       AM.Scale = 1;
07642   } else if (N->getOpcode() == ISD::SUB) {
07643     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
07644     if (Offset)
07645       // [reg +/- imm]
07646       AM.BaseOffs = -Offset->getSExtValue();
07647     else
07648       // [reg +/- reg]
07649       AM.Scale = 1;
07650   } else
07651     return false;
07652 
07653   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
07654 }
07655 
07656 /// Try turning a load/store into a pre-indexed load/store when the base
07657 /// pointer is an add or subtract and it has other uses besides the load/store.
07658 /// After the transformation, the new indexed load/store has effectively folded
07659 /// the add/subtract in and all of its other uses are redirected to the
07660 /// new load/store.
07661 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
07662   if (Level < AfterLegalizeDAG)
07663     return false;
07664 
07665   bool isLoad = true;
07666   SDValue Ptr;
07667   EVT VT;
07668   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
07669     if (LD->isIndexed())
07670       return false;
07671     VT = LD->getMemoryVT();
07672     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
07673         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
07674       return false;
07675     Ptr = LD->getBasePtr();
07676   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
07677     if (ST->isIndexed())
07678       return false;
07679     VT = ST->getMemoryVT();
07680     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
07681         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
07682       return false;
07683     Ptr = ST->getBasePtr();
07684     isLoad = false;
07685   } else {
07686     return false;
07687   }
07688 
07689   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
07690   // out.  There is no reason to make this a preinc/predec.
07691   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
07692       Ptr.getNode()->hasOneUse())
07693     return false;
07694 
07695   // Ask the target to do addressing mode selection.
07696   SDValue BasePtr;
07697   SDValue Offset;
07698   ISD::MemIndexedMode AM = ISD::UNINDEXED;
07699   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
07700     return false;
07701 
07702   // Backends without true r+i pre-indexed forms may need to pass a
07703   // constant base with a variable offset so that constant coercion
07704   // will work with the patterns in canonical form.
07705   bool Swapped = false;
07706   if (isa<ConstantSDNode>(BasePtr)) {
07707     std::swap(BasePtr, Offset);
07708     Swapped = true;
07709   }
07710 
07711   // Don't create a indexed load / store with zero offset.
07712   if (isa<ConstantSDNode>(Offset) &&
07713       cast<ConstantSDNode>(Offset)->isNullValue())
07714     return false;
07715 
07716   // Try turning it into a pre-indexed load / store except when:
07717   // 1) The new base ptr is a frame index.
07718   // 2) If N is a store and the new base ptr is either the same as or is a
07719   //    predecessor of the value being stored.
07720   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
07721   //    that would create a cycle.
07722   // 4) All uses are load / store ops that use it as old base ptr.
07723 
07724   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
07725   // (plus the implicit offset) to a register to preinc anyway.
07726   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
07727     return false;
07728 
07729   // Check #2.
07730   if (!isLoad) {
07731     SDValue Val = cast<StoreSDNode>(N)->getValue();
07732     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
07733       return false;
07734   }
07735 
07736   // If the offset is a constant, there may be other adds of constants that
07737   // can be folded with this one. We should do this to avoid having to keep
07738   // a copy of the original base pointer.
07739   SmallVector<SDNode *, 16> OtherUses;
07740   if (isa<ConstantSDNode>(Offset))
07741     for (SDNode *Use : BasePtr.getNode()->uses()) {
07742       if (Use == Ptr.getNode())
07743         continue;
07744 
07745       if (Use->isPredecessorOf(N))
07746         continue;
07747 
07748       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
07749         OtherUses.clear();
07750         break;
07751       }
07752 
07753       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
07754       if (Op1.getNode() == BasePtr.getNode())
07755         std::swap(Op0, Op1);
07756       assert(Op0.getNode() == BasePtr.getNode() &&
07757              "Use of ADD/SUB but not an operand");
07758 
07759       if (!isa<ConstantSDNode>(Op1)) {
07760         OtherUses.clear();
07761         break;
07762       }
07763 
07764       // FIXME: In some cases, we can be smarter about this.
07765       if (Op1.getValueType() != Offset.getValueType()) {
07766         OtherUses.clear();
07767         break;
07768       }
07769 
07770       OtherUses.push_back(Use);
07771     }
07772 
07773   if (Swapped)
07774     std::swap(BasePtr, Offset);
07775 
07776   // Now check for #3 and #4.
07777   bool RealUse = false;
07778 
07779   // Caches for hasPredecessorHelper
07780   SmallPtrSet<const SDNode *, 32> Visited;
07781   SmallVector<const SDNode *, 16> Worklist;
07782 
07783   for (SDNode *Use : Ptr.getNode()->uses()) {
07784     if (Use == N)
07785       continue;
07786     if (N->hasPredecessorHelper(Use, Visited, Worklist))
07787       return false;
07788 
07789     // If Ptr may be folded in addressing mode of other use, then it's
07790     // not profitable to do this transformation.
07791     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
07792       RealUse = true;
07793   }
07794 
07795   if (!RealUse)
07796     return false;
07797 
07798   SDValue Result;
07799   if (isLoad)
07800     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
07801                                 BasePtr, Offset, AM);
07802   else
07803     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
07804                                  BasePtr, Offset, AM);
07805   ++PreIndexedNodes;
07806   ++NodesCombined;
07807   DEBUG(dbgs() << "\nReplacing.4 ";
07808         N->dump(&DAG);
07809         dbgs() << "\nWith: ";
07810         Result.getNode()->dump(&DAG);
07811         dbgs() << '\n');
07812   WorklistRemover DeadNodes(*this);
07813   if (isLoad) {
07814     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
07815     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
07816   } else {
07817     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
07818   }
07819 
07820   // Finally, since the node is now dead, remove it from the graph.
07821   deleteAndRecombine(N);
07822 
07823   if (Swapped)
07824     std::swap(BasePtr, Offset);
07825 
07826   // Replace other uses of BasePtr that can be updated to use Ptr
07827   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
07828     unsigned OffsetIdx = 1;
07829     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
07830       OffsetIdx = 0;
07831     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
07832            BasePtr.getNode() && "Expected BasePtr operand");
07833 
07834     // We need to replace ptr0 in the following expression:
07835     //   x0 * offset0 + y0 * ptr0 = t0
07836     // knowing that
07837     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
07838     //
07839     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
07840     // indexed load/store and the expresion that needs to be re-written.
07841     //
07842     // Therefore, we have:
07843     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
07844 
07845     ConstantSDNode *CN =
07846       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
07847     int X0, X1, Y0, Y1;
07848     APInt Offset0 = CN->getAPIntValue();
07849     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
07850 
07851     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
07852     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
07853     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
07854     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
07855 
07856     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
07857 
07858     APInt CNV = Offset0;
07859     if (X0 < 0) CNV = -CNV;
07860     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
07861     else CNV = CNV - Offset1;
07862 
07863     // We can now generate the new expression.
07864     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
07865     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
07866 
07867     SDValue NewUse = DAG.getNode(Opcode,
07868                                  SDLoc(OtherUses[i]),
07869                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
07870     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
07871     deleteAndRecombine(OtherUses[i]);
07872   }
07873 
07874   // Replace the uses of Ptr with uses of the updated base value.
07875   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
07876   deleteAndRecombine(Ptr.getNode());
07877 
07878   return true;
07879 }
07880 
07881 /// Try to combine a load/store with a add/sub of the base pointer node into a
07882 /// post-indexed load/store. The transformation folded the add/subtract into the
07883 /// new indexed load/store effectively and all of its uses are redirected to the
07884 /// new load/store.
07885 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
07886   if (Level < AfterLegalizeDAG)
07887     return false;
07888 
07889   bool isLoad = true;
07890   SDValue Ptr;
07891   EVT VT;
07892   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
07893     if (LD->isIndexed())
07894       return false;
07895     VT = LD->getMemoryVT();
07896     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
07897         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
07898       return false;
07899     Ptr = LD->getBasePtr();
07900   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
07901     if (ST->isIndexed())
07902       return false;
07903     VT = ST->getMemoryVT();
07904     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
07905         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
07906       return false;
07907     Ptr = ST->getBasePtr();
07908     isLoad = false;
07909   } else {
07910     return false;
07911   }
07912 
07913   if (Ptr.getNode()->hasOneUse())
07914     return false;
07915 
07916   for (SDNode *Op : Ptr.getNode()->uses()) {
07917     if (Op == N ||
07918         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
07919       continue;
07920 
07921     SDValue BasePtr;
07922     SDValue Offset;
07923     ISD::MemIndexedMode AM = ISD::UNINDEXED;
07924     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
07925       // Don't create a indexed load / store with zero offset.
07926       if (isa<ConstantSDNode>(Offset) &&
07927           cast<ConstantSDNode>(Offset)->isNullValue())
07928         continue;
07929 
07930       // Try turning it into a post-indexed load / store except when
07931       // 1) All uses are load / store ops that use it as base ptr (and
07932       //    it may be folded as addressing mmode).
07933       // 2) Op must be independent of N, i.e. Op is neither a predecessor
07934       //    nor a successor of N. Otherwise, if Op is folded that would
07935       //    create a cycle.
07936 
07937       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
07938         continue;
07939 
07940       // Check for #1.
07941       bool TryNext = false;
07942       for (SDNode *Use : BasePtr.getNode()->uses()) {
07943         if (Use == Ptr.getNode())
07944           continue;
07945 
07946         // If all the uses are load / store addresses, then don't do the
07947         // transformation.
07948         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
07949           bool RealUse = false;
07950           for (SDNode *UseUse : Use->uses()) {
07951             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
07952               RealUse = true;
07953           }
07954 
07955           if (!RealUse) {
07956             TryNext = true;
07957             break;
07958           }
07959         }
07960       }
07961 
07962       if (TryNext)
07963         continue;
07964 
07965       // Check for #2
07966       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
07967         SDValue Result = isLoad
07968           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
07969                                BasePtr, Offset, AM)
07970           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
07971                                 BasePtr, Offset, AM);
07972         ++PostIndexedNodes;
07973         ++NodesCombined;
07974         DEBUG(dbgs() << "\nReplacing.5 ";
07975               N->dump(&DAG);
07976               dbgs() << "\nWith: ";
07977               Result.getNode()->dump(&DAG);
07978               dbgs() << '\n');
07979         WorklistRemover DeadNodes(*this);
07980         if (isLoad) {
07981           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
07982           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
07983         } else {
07984           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
07985         }
07986 
07987         // Finally, since the node is now dead, remove it from the graph.
07988         deleteAndRecombine(N);
07989 
07990         // Replace the uses of Use with uses of the updated base value.
07991         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
07992                                       Result.getValue(isLoad ? 1 : 0));
07993         deleteAndRecombine(Op);
07994         return true;
07995       }
07996     }
07997   }
07998 
07999   return false;
08000 }
08001 
08002 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
08003 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
08004   ISD::MemIndexedMode AM = LD->getAddressingMode();
08005   assert(AM != ISD::UNINDEXED);
08006   SDValue BP = LD->getOperand(1);
08007   SDValue Inc = LD->getOperand(2);
08008 
08009   // Some backends use TargetConstants for load offsets, but don't expect
08010   // TargetConstants in general ADD nodes. We can convert these constants into
08011   // regular Constants (if the constant is not opaque).
08012   assert((Inc.getOpcode() != ISD::TargetConstant ||
08013           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
08014          "Cannot split out indexing using opaque target constants");
08015   if (Inc.getOpcode() == ISD::TargetConstant) {
08016     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
08017     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
08018                           ConstInc->getValueType(0));
08019   }
08020 
08021   unsigned Opc =
08022       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
08023   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
08024 }
08025 
08026 SDValue DAGCombiner::visitLOAD(SDNode *N) {
08027   LoadSDNode *LD  = cast<LoadSDNode>(N);
08028   SDValue Chain = LD->getChain();
08029   SDValue Ptr   = LD->getBasePtr();
08030 
08031   // If load is not volatile and there are no uses of the loaded value (and
08032   // the updated indexed value in case of indexed loads), change uses of the
08033   // chain value into uses of the chain input (i.e. delete the dead load).
08034   if (!LD->isVolatile()) {
08035     if (N->getValueType(1) == MVT::Other) {
08036       // Unindexed loads.
08037       if (!N->hasAnyUseOfValue(0)) {
08038         // It's not safe to use the two value CombineTo variant here. e.g.
08039         // v1, chain2 = load chain1, loc
08040         // v2, chain3 = load chain2, loc
08041         // v3         = add v2, c
08042         // Now we replace use of chain2 with chain1.  This makes the second load
08043         // isomorphic to the one we are deleting, and thus makes this load live.
08044         DEBUG(dbgs() << "\nReplacing.6 ";
08045               N->dump(&DAG);
08046               dbgs() << "\nWith chain: ";
08047               Chain.getNode()->dump(&DAG);
08048               dbgs() << "\n");
08049         WorklistRemover DeadNodes(*this);
08050         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
08051 
08052         if (N->use_empty())
08053           deleteAndRecombine(N);
08054 
08055         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
08056       }
08057     } else {
08058       // Indexed loads.
08059       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
08060 
08061       // If this load has an opaque TargetConstant offset, then we cannot split
08062       // the indexing into an add/sub directly (that TargetConstant may not be
08063       // valid for a different type of node, and we cannot convert an opaque
08064       // target constant into a regular constant).
08065       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
08066                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
08067 
08068       if (!N->hasAnyUseOfValue(0) &&
08069           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
08070         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
08071         SDValue Index;
08072         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
08073           Index = SplitIndexingFromLoad(LD);
08074           // Try to fold the base pointer arithmetic into subsequent loads and
08075           // stores.
08076           AddUsersToWorklist(N);
08077         } else
08078           Index = DAG.getUNDEF(N->getValueType(1));
08079         DEBUG(dbgs() << "\nReplacing.7 ";
08080               N->dump(&DAG);
08081               dbgs() << "\nWith: ";
08082               Undef.getNode()->dump(&DAG);
08083               dbgs() << " and 2 other values\n");
08084         WorklistRemover DeadNodes(*this);
08085         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
08086         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
08087         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
08088         deleteAndRecombine(N);
08089         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
08090       }
08091     }
08092   }
08093 
08094   // If this load is directly stored, replace the load value with the stored
08095   // value.
08096   // TODO: Handle store large -> read small portion.
08097   // TODO: Handle TRUNCSTORE/LOADEXT
08098   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
08099     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
08100       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
08101       if (PrevST->getBasePtr() == Ptr &&
08102           PrevST->getValue().getValueType() == N->getValueType(0))
08103       return CombineTo(N, Chain.getOperand(1), Chain);
08104     }
08105   }
08106 
08107   // Try to infer better alignment information than the load already has.
08108   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
08109     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
08110       if (Align > LD->getMemOperand()->getBaseAlignment()) {
08111         SDValue NewLoad =
08112                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
08113                               LD->getValueType(0),
08114                               Chain, Ptr, LD->getPointerInfo(),
08115                               LD->getMemoryVT(),
08116                               LD->isVolatile(), LD->isNonTemporal(),
08117                               LD->isInvariant(), Align, LD->getAAInfo());
08118         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
08119       }
08120     }
08121   }
08122 
08123   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
08124     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
08125 #ifndef NDEBUG
08126   if (CombinerAAOnlyFunc.getNumOccurrences() &&
08127       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
08128     UseAA = false;
08129 #endif
08130   if (UseAA && LD->isUnindexed()) {
08131     // Walk up chain skipping non-aliasing memory nodes.
08132     SDValue BetterChain = FindBetterChain(N, Chain);
08133 
08134     // If there is a better chain.
08135     if (Chain != BetterChain) {
08136       SDValue ReplLoad;
08137 
08138       // Replace the chain to void dependency.
08139       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
08140         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
08141                                BetterChain, Ptr, LD->getMemOperand());
08142       } else {
08143         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
08144                                   LD->getValueType(0),
08145                                   BetterChain, Ptr, LD->getMemoryVT(),
08146                                   LD->getMemOperand());
08147       }
08148 
08149       // Create token factor to keep old chain connected.
08150       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
08151                                   MVT::Other, Chain, ReplLoad.getValue(1));
08152 
08153       // Make sure the new and old chains are cleaned up.
08154       AddToWorklist(Token.getNode());
08155 
08156       // Replace uses with load result and token factor. Don't add users
08157       // to work list.
08158       return CombineTo(N, ReplLoad.getValue(0), Token, false);
08159     }
08160   }
08161 
08162   // Try transforming N to an indexed load.
08163   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
08164     return SDValue(N, 0);
08165 
08166   // Try to slice up N to more direct loads if the slices are mapped to
08167   // different register banks or pairing can take place.
08168   if (SliceUpLoad(N))
08169     return SDValue(N, 0);
08170 
08171   return SDValue();
08172 }
08173 
08174 namespace {
08175 /// \brief Helper structure used to slice a load in smaller loads.
08176 /// Basically a slice is obtained from the following sequence:
08177 /// Origin = load Ty1, Base
08178 /// Shift = srl Ty1 Origin, CstTy Amount
08179 /// Inst = trunc Shift to Ty2
08180 ///
08181 /// Then, it will be rewriten into:
08182 /// Slice = load SliceTy, Base + SliceOffset
08183 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
08184 ///
08185 /// SliceTy is deduced from the number of bits that are actually used to
08186 /// build Inst.
08187 struct LoadedSlice {
08188   /// \brief Helper structure used to compute the cost of a slice.
08189   struct Cost {
08190     /// Are we optimizing for code size.
08191     bool ForCodeSize;
08192     /// Various cost.
08193     unsigned Loads;
08194     unsigned Truncates;
08195     unsigned CrossRegisterBanksCopies;
08196     unsigned ZExts;
08197     unsigned Shift;
08198 
08199     Cost(bool ForCodeSize = false)
08200         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
08201           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
08202 
08203     /// \brief Get the cost of one isolated slice.
08204     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
08205         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
08206           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
08207       EVT TruncType = LS.Inst->getValueType(0);
08208       EVT LoadedType = LS.getLoadedType();
08209       if (TruncType != LoadedType &&
08210           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
08211         ZExts = 1;
08212     }
08213 
08214     /// \brief Account for slicing gain in the current cost.
08215     /// Slicing provide a few gains like removing a shift or a
08216     /// truncate. This method allows to grow the cost of the original
08217     /// load with the gain from this slice.
08218     void addSliceGain(const LoadedSlice &LS) {
08219       // Each slice saves a truncate.
08220       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
08221       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
08222                               LS.Inst->getOperand(0).getValueType()))
08223         ++Truncates;
08224       // If there is a shift amount, this slice gets rid of it.
08225       if (LS.Shift)
08226         ++Shift;
08227       // If this slice can merge a cross register bank copy, account for it.
08228       if (LS.canMergeExpensiveCrossRegisterBankCopy())
08229         ++CrossRegisterBanksCopies;
08230     }
08231 
08232     Cost &operator+=(const Cost &RHS) {
08233       Loads += RHS.Loads;
08234       Truncates += RHS.Truncates;
08235       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
08236       ZExts += RHS.ZExts;
08237       Shift += RHS.Shift;
08238       return *this;
08239     }
08240 
08241     bool operator==(const Cost &RHS) const {
08242       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
08243              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
08244              ZExts == RHS.ZExts && Shift == RHS.Shift;
08245     }
08246 
08247     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
08248 
08249     bool operator<(const Cost &RHS) const {
08250       // Assume cross register banks copies are as expensive as loads.
08251       // FIXME: Do we want some more target hooks?
08252       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
08253       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
08254       // Unless we are optimizing for code size, consider the
08255       // expensive operation first.
08256       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
08257         return ExpensiveOpsLHS < ExpensiveOpsRHS;
08258       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
08259              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
08260     }
08261 
08262     bool operator>(const Cost &RHS) const { return RHS < *this; }
08263 
08264     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
08265 
08266     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
08267   };
08268   // The last instruction that represent the slice. This should be a
08269   // truncate instruction.
08270   SDNode *Inst;
08271   // The original load instruction.
08272   LoadSDNode *Origin;
08273   // The right shift amount in bits from the original load.
08274   unsigned Shift;
08275   // The DAG from which Origin came from.
08276   // This is used to get some contextual information about legal types, etc.
08277   SelectionDAG *DAG;
08278 
08279   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
08280               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
08281       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
08282 
08283   LoadedSlice(const LoadedSlice &LS)
08284       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
08285 
08286   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
08287   /// \return Result is \p BitWidth and has used bits set to 1 and
08288   ///         not used bits set to 0.
08289   APInt getUsedBits() const {
08290     // Reproduce the trunc(lshr) sequence:
08291     // - Start from the truncated value.
08292     // - Zero extend to the desired bit width.
08293     // - Shift left.
08294     assert(Origin && "No original load to compare against.");
08295     unsigned BitWidth = Origin->getValueSizeInBits(0);
08296     assert(Inst && "This slice is not bound to an instruction");
08297     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
08298            "Extracted slice is bigger than the whole type!");
08299     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
08300     UsedBits.setAllBits();
08301     UsedBits = UsedBits.zext(BitWidth);
08302     UsedBits <<= Shift;
08303     return UsedBits;
08304   }
08305 
08306   /// \brief Get the size of the slice to be loaded in bytes.
08307   unsigned getLoadedSize() const {
08308     unsigned SliceSize = getUsedBits().countPopulation();
08309     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
08310     return SliceSize / 8;
08311   }
08312 
08313   /// \brief Get the type that will be loaded for this slice.
08314   /// Note: This may not be the final type for the slice.
08315   EVT getLoadedType() const {
08316     assert(DAG && "Missing context");
08317     LLVMContext &Ctxt = *DAG->getContext();
08318     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
08319   }
08320 
08321   /// \brief Get the alignment of the load used for this slice.
08322   unsigned getAlignment() const {
08323     unsigned Alignment = Origin->getAlignment();
08324     unsigned Offset = getOffsetFromBase();
08325     if (Offset != 0)
08326       Alignment = MinAlign(Alignment, Alignment + Offset);
08327     return Alignment;
08328   }
08329 
08330   /// \brief Check if this slice can be rewritten with legal operations.
08331   bool isLegal() const {
08332     // An invalid slice is not legal.
08333     if (!Origin || !Inst || !DAG)
08334       return false;
08335 
08336     // Offsets are for indexed load only, we do not handle that.
08337     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
08338       return false;
08339 
08340     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
08341 
08342     // Check that the type is legal.
08343     EVT SliceType = getLoadedType();
08344     if (!TLI.isTypeLegal(SliceType))
08345       return false;
08346 
08347     // Check that the load is legal for this type.
08348     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
08349       return false;
08350 
08351     // Check that the offset can be computed.
08352     // 1. Check its type.
08353     EVT PtrType = Origin->getBasePtr().getValueType();
08354     if (PtrType == MVT::Untyped || PtrType.isExtended())
08355       return false;
08356 
08357     // 2. Check that it fits in the immediate.
08358     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
08359       return false;
08360 
08361     // 3. Check that the computation is legal.
08362     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
08363       return false;
08364 
08365     // Check that the zext is legal if it needs one.
08366     EVT TruncateType = Inst->getValueType(0);
08367     if (TruncateType != SliceType &&
08368         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
08369       return false;
08370 
08371     return true;
08372   }
08373 
08374   /// \brief Get the offset in bytes of this slice in the original chunk of
08375   /// bits.
08376   /// \pre DAG != nullptr.
08377   uint64_t getOffsetFromBase() const {
08378     assert(DAG && "Missing context.");
08379     bool IsBigEndian =
08380         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
08381     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
08382     uint64_t Offset = Shift / 8;
08383     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
08384     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
08385            "The size of the original loaded type is not a multiple of a"
08386            " byte.");
08387     // If Offset is bigger than TySizeInBytes, it means we are loading all
08388     // zeros. This should have been optimized before in the process.
08389     assert(TySizeInBytes > Offset &&
08390            "Invalid shift amount for given loaded size");
08391     if (IsBigEndian)
08392       Offset = TySizeInBytes - Offset - getLoadedSize();
08393     return Offset;
08394   }
08395 
08396   /// \brief Generate the sequence of instructions to load the slice
08397   /// represented by this object and redirect the uses of this slice to
08398   /// this new sequence of instructions.
08399   /// \pre this->Inst && this->Origin are valid Instructions and this
08400   /// object passed the legal check: LoadedSlice::isLegal returned true.
08401   /// \return The last instruction of the sequence used to load the slice.
08402   SDValue loadSlice() const {
08403     assert(Inst && Origin && "Unable to replace a non-existing slice.");
08404     const SDValue &OldBaseAddr = Origin->getBasePtr();
08405     SDValue BaseAddr = OldBaseAddr;
08406     // Get the offset in that chunk of bytes w.r.t. the endianess.
08407     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
08408     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
08409     if (Offset) {
08410       // BaseAddr = BaseAddr + Offset.
08411       EVT ArithType = BaseAddr.getValueType();
08412       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
08413                               DAG->getConstant(Offset, ArithType));
08414     }
08415 
08416     // Create the type of the loaded slice according to its size.
08417     EVT SliceType = getLoadedType();
08418 
08419     // Create the load for the slice.
08420     SDValue LastInst = DAG->getLoad(
08421         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
08422         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
08423         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
08424     // If the final type is not the same as the loaded type, this means that
08425     // we have to pad with zero. Create a zero extend for that.
08426     EVT FinalType = Inst->getValueType(0);
08427     if (SliceType != FinalType)
08428       LastInst =
08429           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
08430     return LastInst;
08431   }
08432 
08433   /// \brief Check if this slice can be merged with an expensive cross register
08434   /// bank copy. E.g.,
08435   /// i = load i32
08436   /// f = bitcast i32 i to float
08437   bool canMergeExpensiveCrossRegisterBankCopy() const {
08438     if (!Inst || !Inst->hasOneUse())
08439       return false;
08440     SDNode *Use = *Inst->use_begin();
08441     if (Use->getOpcode() != ISD::BITCAST)
08442       return false;
08443     assert(DAG && "Missing context");
08444     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
08445     EVT ResVT = Use->getValueType(0);
08446     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
08447     const TargetRegisterClass *ArgRC =
08448         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
08449     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
08450       return false;
08451 
08452     // At this point, we know that we perform a cross-register-bank copy.
08453     // Check if it is expensive.
08454     const TargetRegisterInfo *TRI =
08455         TLI.getTargetMachine().getSubtargetImpl()->getRegisterInfo();
08456     // Assume bitcasts are cheap, unless both register classes do not
08457     // explicitly share a common sub class.
08458     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
08459       return false;
08460 
08461     // Check if it will be merged with the load.
08462     // 1. Check the alignment constraint.
08463     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
08464         ResVT.getTypeForEVT(*DAG->getContext()));
08465 
08466     if (RequiredAlignment > getAlignment())
08467       return false;
08468 
08469     // 2. Check that the load is a legal operation for that type.
08470     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
08471       return false;
08472 
08473     // 3. Check that we do not have a zext in the way.
08474     if (Inst->getValueType(0) != getLoadedType())
08475       return false;
08476 
08477     return true;
08478   }
08479 };
08480 }
08481 
08482 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
08483 /// \p UsedBits looks like 0..0 1..1 0..0.
08484 static bool areUsedBitsDense(const APInt &UsedBits) {
08485   // If all the bits are one, this is dense!
08486   if (UsedBits.isAllOnesValue())
08487     return true;
08488 
08489   // Get rid of the unused bits on the right.
08490   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
08491   // Get rid of the unused bits on the left.
08492   if (NarrowedUsedBits.countLeadingZeros())
08493     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
08494   // Check that the chunk of bits is completely used.
08495   return NarrowedUsedBits.isAllOnesValue();
08496 }
08497 
08498 /// \brief Check whether or not \p First and \p Second are next to each other
08499 /// in memory. This means that there is no hole between the bits loaded
08500 /// by \p First and the bits loaded by \p Second.
08501 static bool areSlicesNextToEachOther(const LoadedSlice &First,
08502                                      const LoadedSlice &Second) {
08503   assert(First.Origin == Second.Origin && First.Origin &&
08504          "Unable to match different memory origins.");
08505   APInt UsedBits = First.getUsedBits();
08506   assert((UsedBits & Second.getUsedBits()) == 0 &&
08507          "Slices are not supposed to overlap.");
08508   UsedBits |= Second.getUsedBits();
08509   return areUsedBitsDense(UsedBits);
08510 }
08511 
08512 /// \brief Adjust the \p GlobalLSCost according to the target
08513 /// paring capabilities and the layout of the slices.
08514 /// \pre \p GlobalLSCost should account for at least as many loads as
08515 /// there is in the slices in \p LoadedSlices.
08516 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
08517                                  LoadedSlice::Cost &GlobalLSCost) {
08518   unsigned NumberOfSlices = LoadedSlices.size();
08519   // If there is less than 2 elements, no pairing is possible.
08520   if (NumberOfSlices < 2)
08521     return;
08522 
08523   // Sort the slices so that elements that are likely to be next to each
08524   // other in memory are next to each other in the list.
08525   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
08526             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
08527     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
08528     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
08529   });
08530   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
08531   // First (resp. Second) is the first (resp. Second) potentially candidate
08532   // to be placed in a paired load.
08533   const LoadedSlice *First = nullptr;
08534   const LoadedSlice *Second = nullptr;
08535   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
08536                 // Set the beginning of the pair.
08537                                                            First = Second) {
08538 
08539     Second = &LoadedSlices[CurrSlice];
08540 
08541     // If First is NULL, it means we start a new pair.
08542     // Get to the next slice.
08543     if (!First)
08544       continue;
08545 
08546     EVT LoadedType = First->getLoadedType();
08547 
08548     // If the types of the slices are different, we cannot pair them.
08549     if (LoadedType != Second->getLoadedType())
08550       continue;
08551 
08552     // Check if the target supplies paired loads for this type.
08553     unsigned RequiredAlignment = 0;
08554     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
08555       // move to the next pair, this type is hopeless.
08556       Second = nullptr;
08557       continue;
08558     }
08559     // Check if we meet the alignment requirement.
08560     if (RequiredAlignment > First->getAlignment())
08561       continue;
08562 
08563     // Check that both loads are next to each other in memory.
08564     if (!areSlicesNextToEachOther(*First, *Second))
08565       continue;
08566 
08567     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
08568     --GlobalLSCost.Loads;
08569     // Move to the next pair.
08570     Second = nullptr;
08571   }
08572 }
08573 
08574 /// \brief Check the profitability of all involved LoadedSlice.
08575 /// Currently, it is considered profitable if there is exactly two
08576 /// involved slices (1) which are (2) next to each other in memory, and
08577 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
08578 ///
08579 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
08580 /// the elements themselves.
08581 ///
08582 /// FIXME: When the cost model will be mature enough, we can relax
08583 /// constraints (1) and (2).
08584 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
08585                                 const APInt &UsedBits, bool ForCodeSize) {
08586   unsigned NumberOfSlices = LoadedSlices.size();
08587   if (StressLoadSlicing)
08588     return NumberOfSlices > 1;
08589 
08590   // Check (1).
08591   if (NumberOfSlices != 2)
08592     return false;
08593 
08594   // Check (2).
08595   if (!areUsedBitsDense(UsedBits))
08596     return false;
08597 
08598   // Check (3).
08599   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
08600   // The original code has one big load.
08601   OrigCost.Loads = 1;
08602   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
08603     const LoadedSlice &LS = LoadedSlices[CurrSlice];
08604     // Accumulate the cost of all the slices.
08605     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
08606     GlobalSlicingCost += SliceCost;
08607 
08608     // Account as cost in the original configuration the gain obtained
08609     // with the current slices.
08610     OrigCost.addSliceGain(LS);
08611   }
08612 
08613   // If the target supports paired load, adjust the cost accordingly.
08614   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
08615   return OrigCost > GlobalSlicingCost;
08616 }
08617 
08618 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
08619 /// operations, split it in the various pieces being extracted.
08620 ///
08621 /// This sort of thing is introduced by SROA.
08622 /// This slicing takes care not to insert overlapping loads.
08623 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
08624 bool DAGCombiner::SliceUpLoad(SDNode *N) {
08625   if (Level < AfterLegalizeDAG)
08626     return false;
08627 
08628   LoadSDNode *LD = cast<LoadSDNode>(N);
08629   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
08630       !LD->getValueType(0).isInteger())
08631     return false;
08632 
08633   // Keep track of already used bits to detect overlapping values.
08634   // In that case, we will just abort the transformation.
08635   APInt UsedBits(LD->getValueSizeInBits(0), 0);
08636 
08637   SmallVector<LoadedSlice, 4> LoadedSlices;
08638 
08639   // Check if this load is used as several smaller chunks of bits.
08640   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
08641   // of computation for each trunc.
08642   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
08643        UI != UIEnd; ++UI) {
08644     // Skip the uses of the chain.
08645     if (UI.getUse().getResNo() != 0)
08646       continue;
08647 
08648     SDNode *User = *UI;
08649     unsigned Shift = 0;
08650 
08651     // Check if this is a trunc(lshr).
08652     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
08653         isa<ConstantSDNode>(User->getOperand(1))) {
08654       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
08655       User = *User->use_begin();
08656     }
08657 
08658     // At this point, User is a Truncate, iff we encountered, trunc or
08659     // trunc(lshr).
08660     if (User->getOpcode() != ISD::TRUNCATE)
08661       return false;
08662 
08663     // The width of the type must be a power of 2 and greater than 8-bits.
08664     // Otherwise the load cannot be represented in LLVM IR.
08665     // Moreover, if we shifted with a non-8-bits multiple, the slice
08666     // will be across several bytes. We do not support that.
08667     unsigned Width = User->getValueSizeInBits(0);
08668     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
08669       return 0;
08670 
08671     // Build the slice for this chain of computations.
08672     LoadedSlice LS(User, LD, Shift, &DAG);
08673     APInt CurrentUsedBits = LS.getUsedBits();
08674 
08675     // Check if this slice overlaps with another.
08676     if ((CurrentUsedBits & UsedBits) != 0)
08677       return false;
08678     // Update the bits used globally.
08679     UsedBits |= CurrentUsedBits;
08680 
08681     // Check if the new slice would be legal.
08682     if (!LS.isLegal())
08683       return false;
08684 
08685     // Record the slice.
08686     LoadedSlices.push_back(LS);
08687   }
08688 
08689   // Abort slicing if it does not seem to be profitable.
08690   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
08691     return false;
08692 
08693   ++SlicedLoads;
08694 
08695   // Rewrite each chain to use an independent load.
08696   // By construction, each chain can be represented by a unique load.
08697 
08698   // Prepare the argument for the new token factor for all the slices.
08699   SmallVector<SDValue, 8> ArgChains;
08700   for (SmallVectorImpl<LoadedSlice>::const_iterator
08701            LSIt = LoadedSlices.begin(),
08702            LSItEnd = LoadedSlices.end();
08703        LSIt != LSItEnd; ++LSIt) {
08704     SDValue SliceInst = LSIt->loadSlice();
08705     CombineTo(LSIt->Inst, SliceInst, true);
08706     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
08707       SliceInst = SliceInst.getOperand(0);
08708     assert(SliceInst->getOpcode() == ISD::LOAD &&
08709            "It takes more than a zext to get to the loaded slice!!");
08710     ArgChains.push_back(SliceInst.getValue(1));
08711   }
08712 
08713   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
08714                               ArgChains);
08715   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
08716   return true;
08717 }
08718 
08719 /// Check to see if V is (and load (ptr), imm), where the load is having
08720 /// specific bytes cleared out.  If so, return the byte size being masked out
08721 /// and the shift amount.
08722 static std::pair<unsigned, unsigned>
08723 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
08724   std::pair<unsigned, unsigned> Result(0, 0);
08725 
08726   // Check for the structure we're looking for.
08727   if (V->getOpcode() != ISD::AND ||
08728       !isa<ConstantSDNode>(V->getOperand(1)) ||
08729       !ISD::isNormalLoad(V->getOperand(0).getNode()))
08730     return Result;
08731 
08732   // Check the chain and pointer.
08733   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
08734   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
08735 
08736   // The store should be chained directly to the load or be an operand of a
08737   // tokenfactor.
08738   if (LD == Chain.getNode())
08739     ; // ok.
08740   else if (Chain->getOpcode() != ISD::TokenFactor)
08741     return Result; // Fail.
08742   else {
08743     bool isOk = false;
08744     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
08745       if (Chain->getOperand(i).getNode() == LD) {
08746         isOk = true;
08747         break;
08748       }
08749     if (!isOk) return Result;
08750   }
08751 
08752   // This only handles simple types.
08753   if (V.getValueType() != MVT::i16 &&
08754       V.getValueType() != MVT::i32 &&
08755       V.getValueType() != MVT::i64)
08756     return Result;
08757 
08758   // Check the constant mask.  Invert it so that the bits being masked out are
08759   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
08760   // follow the sign bit for uniformity.
08761   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
08762   unsigned NotMaskLZ = countLeadingZeros(NotMask);
08763   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
08764   unsigned NotMaskTZ = countTrailingZeros(NotMask);
08765   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
08766   if (NotMaskLZ == 64) return Result;  // All zero mask.
08767 
08768   // See if we have a continuous run of bits.  If so, we have 0*1+0*
08769   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
08770     return Result;
08771 
08772   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
08773   if (V.getValueType() != MVT::i64 && NotMaskLZ)
08774     NotMaskLZ -= 64-V.getValueSizeInBits();
08775 
08776   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
08777   switch (MaskedBytes) {
08778   case 1:
08779   case 2:
08780   case 4: break;
08781   default: return Result; // All one mask, or 5-byte mask.
08782   }
08783 
08784   // Verify that the first bit starts at a multiple of mask so that the access
08785   // is aligned the same as the access width.
08786   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
08787 
08788   Result.first = MaskedBytes;
08789   Result.second = NotMaskTZ/8;
08790   return Result;
08791 }
08792 
08793 
08794 /// Check to see if IVal is something that provides a value as specified by
08795 /// MaskInfo. If so, replace the specified store with a narrower store of
08796 /// truncated IVal.
08797 static SDNode *
08798 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
08799                                 SDValue IVal, StoreSDNode *St,
08800                                 DAGCombiner *DC) {
08801   unsigned NumBytes = MaskInfo.first;
08802   unsigned ByteShift = MaskInfo.second;
08803   SelectionDAG &DAG = DC->getDAG();
08804 
08805   // Check to see if IVal is all zeros in the part being masked in by the 'or'
08806   // that uses this.  If not, this is not a replacement.
08807   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
08808                                   ByteShift*8, (ByteShift+NumBytes)*8);
08809   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
08810 
08811   // Check that it is legal on the target to do this.  It is legal if the new
08812   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
08813   // legalization.
08814   MVT VT = MVT::getIntegerVT(NumBytes*8);
08815   if (!DC->isTypeLegal(VT))
08816     return nullptr;
08817 
08818   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
08819   // shifted by ByteShift and truncated down to NumBytes.
08820   if (ByteShift)
08821     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
08822                        DAG.getConstant(ByteShift*8,
08823                                     DC->getShiftAmountTy(IVal.getValueType())));
08824 
08825   // Figure out the offset for the store and the alignment of the access.
08826   unsigned StOffset;
08827   unsigned NewAlign = St->getAlignment();
08828 
08829   if (DAG.getTargetLoweringInfo().isLittleEndian())
08830     StOffset = ByteShift;
08831   else
08832     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
08833 
08834   SDValue Ptr = St->getBasePtr();
08835   if (StOffset) {
08836     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
08837                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
08838     NewAlign = MinAlign(NewAlign, StOffset);
08839   }
08840 
08841   // Truncate down to the new size.
08842   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
08843 
08844   ++OpsNarrowed;
08845   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
08846                       St->getPointerInfo().getWithOffset(StOffset),
08847                       false, false, NewAlign).getNode();
08848 }
08849 
08850 
08851 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
08852 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
08853 /// narrowing the load and store if it would end up being a win for performance
08854 /// or code size.
08855 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
08856   StoreSDNode *ST  = cast<StoreSDNode>(N);
08857   if (ST->isVolatile())
08858     return SDValue();
08859 
08860   SDValue Chain = ST->getChain();
08861   SDValue Value = ST->getValue();
08862   SDValue Ptr   = ST->getBasePtr();
08863   EVT VT = Value.getValueType();
08864 
08865   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
08866     return SDValue();
08867 
08868   unsigned Opc = Value.getOpcode();
08869 
08870   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
08871   // is a byte mask indicating a consecutive number of bytes, check to see if
08872   // Y is known to provide just those bytes.  If so, we try to replace the
08873   // load + replace + store sequence with a single (narrower) store, which makes
08874   // the load dead.
08875   if (Opc == ISD::OR) {
08876     std::pair<unsigned, unsigned> MaskedLoad;
08877     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
08878     if (MaskedLoad.first)
08879       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
08880                                                   Value.getOperand(1), ST,this))
08881         return SDValue(NewST, 0);
08882 
08883     // Or is commutative, so try swapping X and Y.
08884     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
08885     if (MaskedLoad.first)
08886       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
08887                                                   Value.getOperand(0), ST,this))
08888         return SDValue(NewST, 0);
08889   }
08890 
08891   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
08892       Value.getOperand(1).getOpcode() != ISD::Constant)
08893     return SDValue();
08894 
08895   SDValue N0 = Value.getOperand(0);
08896   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
08897       Chain == SDValue(N0.getNode(), 1)) {
08898     LoadSDNode *LD = cast<LoadSDNode>(N0);
08899     if (LD->getBasePtr() != Ptr ||
08900         LD->getPointerInfo().getAddrSpace() !=
08901         ST->getPointerInfo().getAddrSpace())
08902       return SDValue();
08903 
08904     // Find the type to narrow it the load / op / store to.
08905     SDValue N1 = Value.getOperand(1);
08906     unsigned BitWidth = N1.getValueSizeInBits();
08907     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
08908     if (Opc == ISD::AND)
08909       Imm ^= APInt::getAllOnesValue(BitWidth);
08910     if (Imm == 0 || Imm.isAllOnesValue())
08911       return SDValue();
08912     unsigned ShAmt = Imm.countTrailingZeros();
08913     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
08914     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
08915     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
08916     while (NewBW < BitWidth &&
08917            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
08918              TLI.isNarrowingProfitable(VT, NewVT))) {
08919       NewBW = NextPowerOf2(NewBW);
08920       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
08921     }
08922     if (NewBW >= BitWidth)
08923       return SDValue();
08924 
08925     // If the lsb changed does not start at the type bitwidth boundary,
08926     // start at the previous one.
08927     if (ShAmt % NewBW)
08928       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
08929     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
08930                                    std::min(BitWidth, ShAmt + NewBW));
08931     if ((Imm & Mask) == Imm) {
08932       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
08933       if (Opc == ISD::AND)
08934         NewImm ^= APInt::getAllOnesValue(NewBW);
08935       uint64_t PtrOff = ShAmt / 8;
08936       // For big endian targets, we need to adjust the offset to the pointer to
08937       // load the correct bytes.
08938       if (TLI.isBigEndian())
08939         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
08940 
08941       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
08942       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
08943       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
08944         return SDValue();
08945 
08946       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
08947                                    Ptr.getValueType(), Ptr,
08948                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
08949       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
08950                                   LD->getChain(), NewPtr,
08951                                   LD->getPointerInfo().getWithOffset(PtrOff),
08952                                   LD->isVolatile(), LD->isNonTemporal(),
08953                                   LD->isInvariant(), NewAlign,
08954                                   LD->getAAInfo());
08955       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
08956                                    DAG.getConstant(NewImm, NewVT));
08957       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
08958                                    NewVal, NewPtr,
08959                                    ST->getPointerInfo().getWithOffset(PtrOff),
08960                                    false, false, NewAlign);
08961 
08962       AddToWorklist(NewPtr.getNode());
08963       AddToWorklist(NewLD.getNode());
08964       AddToWorklist(NewVal.getNode());
08965       WorklistRemover DeadNodes(*this);
08966       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
08967       ++OpsNarrowed;
08968       return NewST;
08969     }
08970   }
08971 
08972   return SDValue();
08973 }
08974 
08975 /// For a given floating point load / store pair, if the load value isn't used
08976 /// by any other operations, then consider transforming the pair to integer
08977 /// load / store operations if the target deems the transformation profitable.
08978 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
08979   StoreSDNode *ST  = cast<StoreSDNode>(N);
08980   SDValue Chain = ST->getChain();
08981   SDValue Value = ST->getValue();
08982   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
08983       Value.hasOneUse() &&
08984       Chain == SDValue(Value.getNode(), 1)) {
08985     LoadSDNode *LD = cast<LoadSDNode>(Value);
08986     EVT VT = LD->getMemoryVT();
08987     if (!VT.isFloatingPoint() ||
08988         VT != ST->getMemoryVT() ||
08989         LD->isNonTemporal() ||
08990         ST->isNonTemporal() ||
08991         LD->getPointerInfo().getAddrSpace() != 0 ||
08992         ST->getPointerInfo().getAddrSpace() != 0)
08993       return SDValue();
08994 
08995     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
08996     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
08997         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
08998         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
08999         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
09000       return SDValue();
09001 
09002     unsigned LDAlign = LD->getAlignment();
09003     unsigned STAlign = ST->getAlignment();
09004     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
09005     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
09006     if (LDAlign < ABIAlign || STAlign < ABIAlign)
09007       return SDValue();
09008 
09009     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
09010                                 LD->getChain(), LD->getBasePtr(),
09011                                 LD->getPointerInfo(),
09012                                 false, false, false, LDAlign);
09013 
09014     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
09015                                  NewLD, ST->getBasePtr(),
09016                                  ST->getPointerInfo(),
09017                                  false, false, STAlign);
09018 
09019     AddToWorklist(NewLD.getNode());
09020     AddToWorklist(NewST.getNode());
09021     WorklistRemover DeadNodes(*this);
09022     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
09023     ++LdStFP2Int;
09024     return NewST;
09025   }
09026 
09027   return SDValue();
09028 }
09029 
09030 /// Helper struct to parse and store a memory address as base + index + offset.
09031 /// We ignore sign extensions when it is safe to do so.
09032 /// The following two expressions are not equivalent. To differentiate we need
09033 /// to store whether there was a sign extension involved in the index
09034 /// computation.
09035 ///  (load (i64 add (i64 copyfromreg %c)
09036 ///                 (i64 signextend (add (i8 load %index)
09037 ///                                      (i8 1))))
09038 /// vs
09039 ///
09040 /// (load (i64 add (i64 copyfromreg %c)
09041 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
09042 ///                                         (i32 1)))))
09043 struct BaseIndexOffset {
09044   SDValue Base;
09045   SDValue Index;
09046   int64_t Offset;
09047   bool IsIndexSignExt;
09048 
09049   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
09050 
09051   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
09052                   bool IsIndexSignExt) :
09053     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
09054 
09055   bool equalBaseIndex(const BaseIndexOffset &Other) {
09056     return Other.Base == Base && Other.Index == Index &&
09057       Other.IsIndexSignExt == IsIndexSignExt;
09058   }
09059 
09060   /// Parses tree in Ptr for base, index, offset addresses.
09061   static BaseIndexOffset match(SDValue Ptr) {
09062     bool IsIndexSignExt = false;
09063 
09064     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
09065     // instruction, then it could be just the BASE or everything else we don't
09066     // know how to handle. Just use Ptr as BASE and give up.
09067     if (Ptr->getOpcode() != ISD::ADD)
09068       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
09069 
09070     // We know that we have at least an ADD instruction. Try to pattern match
09071     // the simple case of BASE + OFFSET.
09072     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
09073       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
09074       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
09075                               IsIndexSignExt);
09076     }
09077 
09078     // Inside a loop the current BASE pointer is calculated using an ADD and a
09079     // MUL instruction. In this case Ptr is the actual BASE pointer.
09080     // (i64 add (i64 %array_ptr)
09081     //          (i64 mul (i64 %induction_var)
09082     //                   (i64 %element_size)))
09083     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
09084       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
09085 
09086     // Look at Base + Index + Offset cases.
09087     SDValue Base = Ptr->getOperand(0);
09088     SDValue IndexOffset = Ptr->getOperand(1);
09089 
09090     // Skip signextends.
09091     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
09092       IndexOffset = IndexOffset->getOperand(0);
09093       IsIndexSignExt = true;
09094     }
09095 
09096     // Either the case of Base + Index (no offset) or something else.
09097     if (IndexOffset->getOpcode() != ISD::ADD)
09098       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
09099 
09100     // Now we have the case of Base + Index + offset.
09101     SDValue Index = IndexOffset->getOperand(0);
09102     SDValue Offset = IndexOffset->getOperand(1);
09103 
09104     if (!isa<ConstantSDNode>(Offset))
09105       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
09106 
09107     // Ignore signextends.
09108     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
09109       Index = Index->getOperand(0);
09110       IsIndexSignExt = true;
09111     } else IsIndexSignExt = false;
09112 
09113     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
09114     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
09115   }
09116 };
09117 
09118 /// Holds a pointer to an LSBaseSDNode as well as information on where it
09119 /// is located in a sequence of memory operations connected by a chain.
09120 struct MemOpLink {
09121   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
09122     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
09123   // Ptr to the mem node.
09124   LSBaseSDNode *MemNode;
09125   // Offset from the base ptr.
09126   int64_t OffsetFromBase;
09127   // What is the sequence number of this mem node.
09128   // Lowest mem operand in the DAG starts at zero.
09129   unsigned SequenceNum;
09130 };
09131 
09132 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
09133   EVT MemVT = St->getMemoryVT();
09134   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
09135   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
09136     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
09137 
09138   // Don't merge vectors into wider inputs.
09139   if (MemVT.isVector() || !MemVT.isSimple())
09140     return false;
09141 
09142   // Perform an early exit check. Do not bother looking at stored values that
09143   // are not constants or loads.
09144   SDValue StoredVal = St->getValue();
09145   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
09146   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
09147       !IsLoadSrc)
09148     return false;
09149 
09150   // Only look at ends of store sequences.
09151   SDValue Chain = SDValue(St, 0);
09152   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
09153     return false;
09154 
09155   // This holds the base pointer, index, and the offset in bytes from the base
09156   // pointer.
09157   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
09158 
09159   // We must have a base and an offset.
09160   if (!BasePtr.Base.getNode())
09161     return false;
09162 
09163   // Do not handle stores to undef base pointers.
09164   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
09165     return false;
09166 
09167   // Save the LoadSDNodes that we find in the chain.
09168   // We need to make sure that these nodes do not interfere with
09169   // any of the store nodes.
09170   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
09171 
09172   // Save the StoreSDNodes that we find in the chain.
09173   SmallVector<MemOpLink, 8> StoreNodes;
09174 
09175   // Walk up the chain and look for nodes with offsets from the same
09176   // base pointer. Stop when reaching an instruction with a different kind
09177   // or instruction which has a different base pointer.
09178   unsigned Seq = 0;
09179   StoreSDNode *Index = St;
09180   while (Index) {
09181     // If the chain has more than one use, then we can't reorder the mem ops.
09182     if (Index != St && !SDValue(Index, 0)->hasOneUse())
09183       break;
09184 
09185     // Find the base pointer and offset for this memory node.
09186     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
09187 
09188     // Check that the base pointer is the same as the original one.
09189     if (!Ptr.equalBaseIndex(BasePtr))
09190       break;
09191 
09192     // Check that the alignment is the same.
09193     if (Index->getAlignment() != St->getAlignment())
09194       break;
09195 
09196     // The memory operands must not be volatile.
09197     if (Index->isVolatile() || Index->isIndexed())
09198       break;
09199 
09200     // No truncation.
09201     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
09202       if (St->isTruncatingStore())
09203         break;
09204 
09205     // The stored memory type must be the same.
09206     if (Index->getMemoryVT() != MemVT)
09207       break;
09208 
09209     // We do not allow unaligned stores because we want to prevent overriding
09210     // stores.
09211     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
09212       break;
09213 
09214     // We found a potential memory operand to merge.
09215     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
09216 
09217     // Find the next memory operand in the chain. If the next operand in the
09218     // chain is a store then move up and continue the scan with the next
09219     // memory operand. If the next operand is a load save it and use alias
09220     // information to check if it interferes with anything.
09221     SDNode *NextInChain = Index->getChain().getNode();
09222     while (1) {
09223       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
09224         // We found a store node. Use it for the next iteration.
09225         Index = STn;
09226         break;
09227       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
09228         if (Ldn->isVolatile()) {
09229           Index = nullptr;
09230           break;
09231         }
09232 
09233         // Save the load node for later. Continue the scan.
09234         AliasLoadNodes.push_back(Ldn);
09235         NextInChain = Ldn->getChain().getNode();
09236         continue;
09237       } else {
09238         Index = nullptr;
09239         break;
09240       }
09241     }
09242   }
09243 
09244   // Check if there is anything to merge.
09245   if (StoreNodes.size() < 2)
09246     return false;
09247 
09248   // Sort the memory operands according to their distance from the base pointer.
09249   std::sort(StoreNodes.begin(), StoreNodes.end(),
09250             [](MemOpLink LHS, MemOpLink RHS) {
09251     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
09252            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
09253             LHS.SequenceNum > RHS.SequenceNum);
09254   });
09255 
09256   // Scan the memory operations on the chain and find the first non-consecutive
09257   // store memory address.
09258   unsigned LastConsecutiveStore = 0;
09259   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
09260   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
09261 
09262     // Check that the addresses are consecutive starting from the second
09263     // element in the list of stores.
09264     if (i > 0) {
09265       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
09266       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
09267         break;
09268     }
09269 
09270     bool Alias = false;
09271     // Check if this store interferes with any of the loads that we found.
09272     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
09273       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
09274         Alias = true;
09275         break;
09276       }
09277     // We found a load that alias with this store. Stop the sequence.
09278     if (Alias)
09279       break;
09280 
09281     // Mark this node as useful.
09282     LastConsecutiveStore = i;
09283   }
09284 
09285   // The node with the lowest store address.
09286   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
09287 
09288   // Store the constants into memory as one consecutive store.
09289   if (!IsLoadSrc) {
09290     unsigned LastLegalType = 0;
09291     unsigned LastLegalVectorType = 0;
09292     bool NonZero = false;
09293     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
09294       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
09295       SDValue StoredVal = St->getValue();
09296 
09297       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
09298         NonZero |= !C->isNullValue();
09299       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
09300         NonZero |= !C->getConstantFPValue()->isNullValue();
09301       } else {
09302         // Non-constant.
09303         break;
09304       }
09305 
09306       // Find a legal type for the constant store.
09307       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
09308       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
09309       if (TLI.isTypeLegal(StoreTy))
09310         LastLegalType = i+1;
09311       // Or check whether a truncstore is legal.
09312       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
09313                TargetLowering::TypePromoteInteger) {
09314         EVT LegalizedStoredValueTy =
09315           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
09316         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
09317           LastLegalType = i+1;
09318       }
09319 
09320       // Find a legal type for the vector store.
09321       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
09322       if (TLI.isTypeLegal(Ty))
09323         LastLegalVectorType = i + 1;
09324     }
09325 
09326     // We only use vectors if the constant is known to be zero and the
09327     // function is not marked with the noimplicitfloat attribute.
09328     if (NonZero || NoVectors)
09329       LastLegalVectorType = 0;
09330 
09331     // Check if we found a legal integer type to store.
09332     if (LastLegalType == 0 && LastLegalVectorType == 0)
09333       return false;
09334 
09335     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
09336     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
09337 
09338     // Make sure we have something to merge.
09339     if (NumElem < 2)
09340       return false;
09341 
09342     unsigned EarliestNodeUsed = 0;
09343     for (unsigned i=0; i < NumElem; ++i) {
09344       // Find a chain for the new wide-store operand. Notice that some
09345       // of the store nodes that we found may not be selected for inclusion
09346       // in the wide store. The chain we use needs to be the chain of the
09347       // earliest store node which is *used* and replaced by the wide store.
09348       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
09349         EarliestNodeUsed = i;
09350     }
09351 
09352     // The earliest Node in the DAG.
09353     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
09354     SDLoc DL(StoreNodes[0].MemNode);
09355 
09356     SDValue StoredVal;
09357     if (UseVector) {
09358       // Find a legal type for the vector store.
09359       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
09360       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
09361       StoredVal = DAG.getConstant(0, Ty);
09362     } else {
09363       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
09364       APInt StoreInt(StoreBW, 0);
09365 
09366       // Construct a single integer constant which is made of the smaller
09367       // constant inputs.
09368       bool IsLE = TLI.isLittleEndian();
09369       for (unsigned i = 0; i < NumElem ; ++i) {
09370         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
09371         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
09372         SDValue Val = St->getValue();
09373         StoreInt<<=ElementSizeBytes*8;
09374         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
09375           StoreInt|=C->getAPIntValue().zext(StoreBW);
09376         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
09377           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
09378         } else {
09379           assert(false && "Invalid constant element type");
09380         }
09381       }
09382 
09383       // Create the new Load and Store operations.
09384       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
09385       StoredVal = DAG.getConstant(StoreInt, StoreTy);
09386     }
09387 
09388     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
09389                                     FirstInChain->getBasePtr(),
09390                                     FirstInChain->getPointerInfo(),
09391                                     false, false,
09392                                     FirstInChain->getAlignment());
09393 
09394     // Replace the first store with the new store
09395     CombineTo(EarliestOp, NewStore);
09396     // Erase all other stores.
09397     for (unsigned i = 0; i < NumElem ; ++i) {
09398       if (StoreNodes[i].MemNode == EarliestOp)
09399         continue;
09400       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
09401       // ReplaceAllUsesWith will replace all uses that existed when it was
09402       // called, but graph optimizations may cause new ones to appear. For
09403       // example, the case in pr14333 looks like
09404       //
09405       //  St's chain -> St -> another store -> X
09406       //
09407       // And the only difference from St to the other store is the chain.
09408       // When we change it's chain to be St's chain they become identical,
09409       // get CSEed and the net result is that X is now a use of St.
09410       // Since we know that St is redundant, just iterate.
09411       while (!St->use_empty())
09412         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
09413       deleteAndRecombine(St);
09414     }
09415 
09416     return true;
09417   }
09418 
09419   // Below we handle the case of multiple consecutive stores that
09420   // come from multiple consecutive loads. We merge them into a single
09421   // wide load and a single wide store.
09422 
09423   // Look for load nodes which are used by the stored values.
09424   SmallVector<MemOpLink, 8> LoadNodes;
09425 
09426   // Find acceptable loads. Loads need to have the same chain (token factor),
09427   // must not be zext, volatile, indexed, and they must be consecutive.
09428   BaseIndexOffset LdBasePtr;
09429   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
09430     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
09431     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
09432     if (!Ld) break;
09433 
09434     // Loads must only have one use.
09435     if (!Ld->hasNUsesOfValue(1, 0))
09436       break;
09437 
09438     // Check that the alignment is the same as the stores.
09439     if (Ld->getAlignment() != St->getAlignment())
09440       break;
09441 
09442     // The memory operands must not be volatile.
09443     if (Ld->isVolatile() || Ld->isIndexed())
09444       break;
09445 
09446     // We do not accept ext loads.
09447     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
09448       break;
09449 
09450     // The stored memory type must be the same.
09451     if (Ld->getMemoryVT() != MemVT)
09452       break;
09453 
09454     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
09455     // If this is not the first ptr that we check.
09456     if (LdBasePtr.Base.getNode()) {
09457       // The base ptr must be the same.
09458       if (!LdPtr.equalBaseIndex(LdBasePtr))
09459         break;
09460     } else {
09461       // Check that all other base pointers are the same as this one.
09462       LdBasePtr = LdPtr;
09463     }
09464 
09465     // We found a potential memory operand to merge.
09466     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
09467   }
09468 
09469   if (LoadNodes.size() < 2)
09470     return false;
09471 
09472   // If we have load/store pair instructions and we only have two values,
09473   // don't bother.
09474   unsigned RequiredAlignment;
09475   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
09476       St->getAlignment() >= RequiredAlignment)
09477     return false;
09478 
09479   // Scan the memory operations on the chain and find the first non-consecutive
09480   // load memory address. These variables hold the index in the store node
09481   // array.
09482   unsigned LastConsecutiveLoad = 0;
09483   // This variable refers to the size and not index in the array.
09484   unsigned LastLegalVectorType = 0;
09485   unsigned LastLegalIntegerType = 0;
09486   StartAddress = LoadNodes[0].OffsetFromBase;
09487   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
09488   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
09489     // All loads much share the same chain.
09490     if (LoadNodes[i].MemNode->getChain() != FirstChain)
09491       break;
09492 
09493     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
09494     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
09495       break;
09496     LastConsecutiveLoad = i;
09497 
09498     // Find a legal type for the vector store.
09499     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
09500     if (TLI.isTypeLegal(StoreTy))
09501       LastLegalVectorType = i + 1;
09502 
09503     // Find a legal type for the integer store.
09504     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
09505     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
09506     if (TLI.isTypeLegal(StoreTy))
09507       LastLegalIntegerType = i + 1;
09508     // Or check whether a truncstore and extload is legal.
09509     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
09510              TargetLowering::TypePromoteInteger) {
09511       EVT LegalizedStoredValueTy =
09512         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
09513       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
09514           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
09515           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
09516           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
09517         LastLegalIntegerType = i+1;
09518     }
09519   }
09520 
09521   // Only use vector types if the vector type is larger than the integer type.
09522   // If they are the same, use integers.
09523   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
09524   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
09525 
09526   // We add +1 here because the LastXXX variables refer to location while
09527   // the NumElem refers to array/index size.
09528   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
09529   NumElem = std::min(LastLegalType, NumElem);
09530 
09531   if (NumElem < 2)
09532     return false;
09533 
09534   // The earliest Node in the DAG.
09535   unsigned EarliestNodeUsed = 0;
09536   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
09537   for (unsigned i=1; i<NumElem; ++i) {
09538     // Find a chain for the new wide-store operand. Notice that some
09539     // of the store nodes that we found may not be selected for inclusion
09540     // in the wide store. The chain we use needs to be the chain of the
09541     // earliest store node which is *used* and replaced by the wide store.
09542     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
09543       EarliestNodeUsed = i;
09544   }
09545 
09546   // Find if it is better to use vectors or integers to load and store
09547   // to memory.
09548   EVT JointMemOpVT;
09549   if (UseVectorTy) {
09550     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
09551   } else {
09552     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
09553     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
09554   }
09555 
09556   SDLoc LoadDL(LoadNodes[0].MemNode);
09557   SDLoc StoreDL(StoreNodes[0].MemNode);
09558 
09559   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
09560   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
09561                                 FirstLoad->getChain(),
09562                                 FirstLoad->getBasePtr(),
09563                                 FirstLoad->getPointerInfo(),
09564                                 false, false, false,
09565                                 FirstLoad->getAlignment());
09566 
09567   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
09568                                   FirstInChain->getBasePtr(),
09569                                   FirstInChain->getPointerInfo(), false, false,
09570                                   FirstInChain->getAlignment());
09571 
09572   // Replace one of the loads with the new load.
09573   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
09574   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
09575                                 SDValue(NewLoad.getNode(), 1));
09576 
09577   // Remove the rest of the load chains.
09578   for (unsigned i = 1; i < NumElem ; ++i) {
09579     // Replace all chain users of the old load nodes with the chain of the new
09580     // load node.
09581     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
09582     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
09583   }
09584 
09585   // Replace the first store with the new store.
09586   CombineTo(EarliestOp, NewStore);
09587   // Erase all other stores.
09588   for (unsigned i = 0; i < NumElem ; ++i) {
09589     // Remove all Store nodes.
09590     if (StoreNodes[i].MemNode == EarliestOp)
09591       continue;
09592     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
09593     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
09594     deleteAndRecombine(St);
09595   }
09596 
09597   return true;
09598 }
09599 
09600 SDValue DAGCombiner::visitSTORE(SDNode *N) {
09601   StoreSDNode *ST  = cast<StoreSDNode>(N);
09602   SDValue Chain = ST->getChain();
09603   SDValue Value = ST->getValue();
09604   SDValue Ptr   = ST->getBasePtr();
09605 
09606   // If this is a store of a bit convert, store the input value if the
09607   // resultant store does not need a higher alignment than the original.
09608   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
09609       ST->isUnindexed()) {
09610     unsigned OrigAlign = ST->getAlignment();
09611     EVT SVT = Value.getOperand(0).getValueType();
09612     unsigned Align = TLI.getDataLayout()->
09613       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
09614     if (Align <= OrigAlign &&
09615         ((!LegalOperations && !ST->isVolatile()) ||
09616          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
09617       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
09618                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
09619                           ST->isNonTemporal(), OrigAlign,
09620                           ST->getAAInfo());
09621   }
09622 
09623   // Turn 'store undef, Ptr' -> nothing.
09624   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
09625     return Chain;
09626 
09627   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
09628   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
09629     // NOTE: If the original store is volatile, this transform must not increase
09630     // the number of stores.  For example, on x86-32 an f64 can be stored in one
09631     // processor operation but an i64 (which is not legal) requires two.  So the
09632     // transform should not be done in this case.
09633     if (Value.getOpcode() != ISD::TargetConstantFP) {
09634       SDValue Tmp;
09635       switch (CFP->getSimpleValueType(0).SimpleTy) {
09636       default: llvm_unreachable("Unknown FP type");
09637       case MVT::f16:    // We don't do this for these yet.
09638       case MVT::f80:
09639       case MVT::f128:
09640       case MVT::ppcf128:
09641         break;
09642       case MVT::f32:
09643         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
09644             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
09645           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
09646                               bitcastToAPInt().getZExtValue(), MVT::i32);
09647           return DAG.getStore(Chain, SDLoc(N), Tmp,
09648                               Ptr, ST->getMemOperand());
09649         }
09650         break;
09651       case MVT::f64:
09652         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
09653              !ST->isVolatile()) ||
09654             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
09655           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
09656                                 getZExtValue(), MVT::i64);
09657           return DAG.getStore(Chain, SDLoc(N), Tmp,
09658                               Ptr, ST->getMemOperand());
09659         }
09660 
09661         if (!ST->isVolatile() &&
09662             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
09663           // Many FP stores are not made apparent until after legalize, e.g. for
09664           // argument passing.  Since this is so common, custom legalize the
09665           // 64-bit integer store into two 32-bit stores.
09666           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
09667           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
09668           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
09669           if (TLI.isBigEndian()) std::swap(Lo, Hi);
09670 
09671           unsigned Alignment = ST->getAlignment();
09672           bool isVolatile = ST->isVolatile();
09673           bool isNonTemporal = ST->isNonTemporal();
09674           AAMDNodes AAInfo = ST->getAAInfo();
09675 
09676           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
09677                                      Ptr, ST->getPointerInfo(),
09678                                      isVolatile, isNonTemporal,
09679                                      ST->getAlignment(), AAInfo);
09680           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
09681                             DAG.getConstant(4, Ptr.getValueType()));
09682           Alignment = MinAlign(Alignment, 4U);
09683           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
09684                                      Ptr, ST->getPointerInfo().getWithOffset(4),
09685                                      isVolatile, isNonTemporal,
09686                                      Alignment, AAInfo);
09687           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
09688                              St0, St1);
09689         }
09690 
09691         break;
09692       }
09693     }
09694   }
09695 
09696   // Try to infer better alignment information than the store already has.
09697   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
09698     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
09699       if (Align > ST->getAlignment())
09700         return DAG.getTruncStore(Chain, SDLoc(N), Value,
09701                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
09702                                  ST->isVolatile(), ST->isNonTemporal(), Align,
09703                                  ST->getAAInfo());
09704     }
09705   }
09706 
09707   // Try transforming a pair floating point load / store ops to integer
09708   // load / store ops.
09709   SDValue NewST = TransformFPLoadStorePair(N);
09710   if (NewST.getNode())
09711     return NewST;
09712 
09713   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
09714     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
09715 #ifndef NDEBUG
09716   if (CombinerAAOnlyFunc.getNumOccurrences() &&
09717       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
09718     UseAA = false;
09719 #endif
09720   if (UseAA && ST->isUnindexed()) {
09721     // Walk up chain skipping non-aliasing memory nodes.
09722     SDValue BetterChain = FindBetterChain(N, Chain);
09723 
09724     // If there is a better chain.
09725     if (Chain != BetterChain) {
09726       SDValue ReplStore;
09727 
09728       // Replace the chain to avoid dependency.
09729       if (ST->isTruncatingStore()) {
09730         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
09731                                       ST->getMemoryVT(), ST->getMemOperand());
09732       } else {
09733         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
09734                                  ST->getMemOperand());
09735       }
09736 
09737       // Create token to keep both nodes around.
09738       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
09739                                   MVT::Other, Chain, ReplStore);
09740 
09741       // Make sure the new and old chains are cleaned up.
09742       AddToWorklist(Token.getNode());
09743 
09744       // Don't add users to work list.
09745       return CombineTo(N, Token, false);
09746     }
09747   }
09748 
09749   // Try transforming N to an indexed store.
09750   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
09751     return SDValue(N, 0);
09752 
09753   // FIXME: is there such a thing as a truncating indexed store?
09754   if (ST->isTruncatingStore() && ST->isUnindexed() &&
09755       Value.getValueType().isInteger()) {
09756     // See if we can simplify the input to this truncstore with knowledge that
09757     // only the low bits are being used.  For example:
09758     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
09759     SDValue Shorter =
09760       GetDemandedBits(Value,
09761                       APInt::getLowBitsSet(
09762                         Value.getValueType().getScalarType().getSizeInBits(),
09763                         ST->getMemoryVT().getScalarType().getSizeInBits()));
09764     AddToWorklist(Value.getNode());
09765     if (Shorter.getNode())
09766       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
09767                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
09768 
09769     // Otherwise, see if we can simplify the operation with
09770     // SimplifyDemandedBits, which only works if the value has a single use.
09771     if (SimplifyDemandedBits(Value,
09772                         APInt::getLowBitsSet(
09773                           Value.getValueType().getScalarType().getSizeInBits(),
09774                           ST->getMemoryVT().getScalarType().getSizeInBits())))
09775       return SDValue(N, 0);
09776   }
09777 
09778   // If this is a load followed by a store to the same location, then the store
09779   // is dead/noop.
09780   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
09781     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
09782         ST->isUnindexed() && !ST->isVolatile() &&
09783         // There can't be any side effects between the load and store, such as
09784         // a call or store.
09785         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
09786       // The store is dead, remove it.
09787       return Chain;
09788     }
09789   }
09790 
09791   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
09792   // truncating store.  We can do this even if this is already a truncstore.
09793   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
09794       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
09795       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
09796                             ST->getMemoryVT())) {
09797     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
09798                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
09799   }
09800 
09801   // Only perform this optimization before the types are legal, because we
09802   // don't want to perform this optimization on every DAGCombine invocation.
09803   if (!LegalTypes) {
09804     bool EverChanged = false;
09805 
09806     do {
09807       // There can be multiple store sequences on the same chain.
09808       // Keep trying to merge store sequences until we are unable to do so
09809       // or until we merge the last store on the chain.
09810       bool Changed = MergeConsecutiveStores(ST);
09811       EverChanged |= Changed;
09812       if (!Changed) break;
09813     } while (ST->getOpcode() != ISD::DELETED_NODE);
09814 
09815     if (EverChanged)
09816       return SDValue(N, 0);
09817   }
09818 
09819   return ReduceLoadOpStoreWidth(N);
09820 }
09821 
09822 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
09823   SDValue InVec = N->getOperand(0);
09824   SDValue InVal = N->getOperand(1);
09825   SDValue EltNo = N->getOperand(2);
09826   SDLoc dl(N);
09827 
09828   // If the inserted element is an UNDEF, just use the input vector.
09829   if (InVal.getOpcode() == ISD::UNDEF)
09830     return InVec;
09831 
09832   EVT VT = InVec.getValueType();
09833 
09834   // If we can't generate a legal BUILD_VECTOR, exit
09835   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
09836     return SDValue();
09837 
09838   // Check that we know which element is being inserted
09839   if (!isa<ConstantSDNode>(EltNo))
09840     return SDValue();
09841   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
09842 
09843   // Canonicalize insert_vector_elt dag nodes.
09844   // Example:
09845   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
09846   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
09847   //
09848   // Do this only if the child insert_vector node has one use; also
09849   // do this only if indices are both constants and Idx1 < Idx0.
09850   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
09851       && isa<ConstantSDNode>(InVec.getOperand(2))) {
09852     unsigned OtherElt =
09853       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
09854     if (Elt < OtherElt) {
09855       // Swap nodes.
09856       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
09857                                   InVec.getOperand(0), InVal, EltNo);
09858       AddToWorklist(NewOp.getNode());
09859       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
09860                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
09861     }
09862   }
09863 
09864   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
09865   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
09866   // vector elements.
09867   SmallVector<SDValue, 8> Ops;
09868   // Do not combine these two vectors if the output vector will not replace
09869   // the input vector.
09870   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
09871     Ops.append(InVec.getNode()->op_begin(),
09872                InVec.getNode()->op_end());
09873   } else if (InVec.getOpcode() == ISD::UNDEF) {
09874     unsigned NElts = VT.getVectorNumElements();
09875     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
09876   } else {
09877     return SDValue();
09878   }
09879 
09880   // Insert the element
09881   if (Elt < Ops.size()) {
09882     // All the operands of BUILD_VECTOR must have the same type;
09883     // we enforce that here.
09884     EVT OpVT = Ops[0].getValueType();
09885     if (InVal.getValueType() != OpVT)
09886       InVal = OpVT.bitsGT(InVal.getValueType()) ?
09887                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
09888                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
09889     Ops[Elt] = InVal;
09890   }
09891 
09892   // Return the new vector
09893   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
09894 }
09895 
09896 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
09897     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
09898   EVT ResultVT = EVE->getValueType(0);
09899   EVT VecEltVT = InVecVT.getVectorElementType();
09900   unsigned Align = OriginalLoad->getAlignment();
09901   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
09902       VecEltVT.getTypeForEVT(*DAG.getContext()));
09903 
09904   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
09905     return SDValue();
09906 
09907   Align = NewAlign;
09908 
09909   SDValue NewPtr = OriginalLoad->getBasePtr();
09910   SDValue Offset;
09911   EVT PtrType = NewPtr.getValueType();
09912   MachinePointerInfo MPI;
09913   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
09914     int Elt = ConstEltNo->getZExtValue();
09915     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
09916     if (TLI.isBigEndian())
09917       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
09918     Offset = DAG.getConstant(PtrOff, PtrType);
09919     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
09920   } else {
09921     Offset = DAG.getNode(
09922         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
09923         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
09924     if (TLI.isBigEndian())
09925       Offset = DAG.getNode(
09926           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
09927           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
09928     MPI = OriginalLoad->getPointerInfo();
09929   }
09930   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
09931 
09932   // The replacement we need to do here is a little tricky: we need to
09933   // replace an extractelement of a load with a load.
09934   // Use ReplaceAllUsesOfValuesWith to do the replacement.
09935   // Note that this replacement assumes that the extractvalue is the only
09936   // use of the load; that's okay because we don't want to perform this
09937   // transformation in other cases anyway.
09938   SDValue Load;
09939   SDValue Chain;
09940   if (ResultVT.bitsGT(VecEltVT)) {
09941     // If the result type of vextract is wider than the load, then issue an
09942     // extending load instead.
09943     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
09944                                    ? ISD::ZEXTLOAD
09945                                    : ISD::EXTLOAD;
09946     Load = DAG.getExtLoad(
09947         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
09948         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
09949         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
09950     Chain = Load.getValue(1);
09951   } else {
09952     Load = DAG.getLoad(
09953         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
09954         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
09955         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
09956     Chain = Load.getValue(1);
09957     if (ResultVT.bitsLT(VecEltVT))
09958       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
09959     else
09960       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
09961   }
09962   WorklistRemover DeadNodes(*this);
09963   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
09964   SDValue To[] = { Load, Chain };
09965   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
09966   // Since we're explicitly calling ReplaceAllUses, add the new node to the
09967   // worklist explicitly as well.
09968   AddToWorklist(Load.getNode());
09969   AddUsersToWorklist(Load.getNode()); // Add users too
09970   // Make sure to revisit this node to clean it up; it will usually be dead.
09971   AddToWorklist(EVE);
09972   ++OpsNarrowed;
09973   return SDValue(EVE, 0);
09974 }
09975 
09976 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
09977   // (vextract (scalar_to_vector val, 0) -> val
09978   SDValue InVec = N->getOperand(0);
09979   EVT VT = InVec.getValueType();
09980   EVT NVT = N->getValueType(0);
09981 
09982   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
09983     // Check if the result type doesn't match the inserted element type. A
09984     // SCALAR_TO_VECTOR may truncate the inserted element and the
09985     // EXTRACT_VECTOR_ELT may widen the extracted vector.
09986     SDValue InOp = InVec.getOperand(0);
09987     if (InOp.getValueType() != NVT) {
09988       assert(InOp.getValueType().isInteger() && NVT.isInteger());
09989       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
09990     }
09991     return InOp;
09992   }
09993 
09994   SDValue EltNo = N->getOperand(1);
09995   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
09996 
09997   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
09998   // We only perform this optimization before the op legalization phase because
09999   // we may introduce new vector instructions which are not backed by TD
10000   // patterns. For example on AVX, extracting elements from a wide vector
10001   // without using extract_subvector. However, if we can find an underlying
10002   // scalar value, then we can always use that.
10003   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10004       && ConstEltNo) {
10005     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10006     int NumElem = VT.getVectorNumElements();
10007     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10008     // Find the new index to extract from.
10009     int OrigElt = SVOp->getMaskElt(Elt);
10010 
10011     // Extracting an undef index is undef.
10012     if (OrigElt == -1)
10013       return DAG.getUNDEF(NVT);
10014 
10015     // Select the right vector half to extract from.
10016     SDValue SVInVec;
10017     if (OrigElt < NumElem) {
10018       SVInVec = InVec->getOperand(0);
10019     } else {
10020       SVInVec = InVec->getOperand(1);
10021       OrigElt -= NumElem;
10022     }
10023 
10024     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10025       SDValue InOp = SVInVec.getOperand(OrigElt);
10026       if (InOp.getValueType() != NVT) {
10027         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10028         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10029       }
10030 
10031       return InOp;
10032     }
10033 
10034     // FIXME: We should handle recursing on other vector shuffles and
10035     // scalar_to_vector here as well.
10036 
10037     if (!LegalOperations) {
10038       EVT IndexTy = TLI.getVectorIdxTy();
10039       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10040                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10041     }
10042   }
10043 
10044   bool BCNumEltsChanged = false;
10045   EVT ExtVT = VT.getVectorElementType();
10046   EVT LVT = ExtVT;
10047 
10048   // If the result of load has to be truncated, then it's not necessarily
10049   // profitable.
10050   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10051     return SDValue();
10052 
10053   if (InVec.getOpcode() == ISD::BITCAST) {
10054     // Don't duplicate a load with other uses.
10055     if (!InVec.hasOneUse())
10056       return SDValue();
10057 
10058     EVT BCVT = InVec.getOperand(0).getValueType();
10059     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10060       return SDValue();
10061     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10062       BCNumEltsChanged = true;
10063     InVec = InVec.getOperand(0);
10064     ExtVT = BCVT.getVectorElementType();
10065   }
10066 
10067   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10068   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10069       ISD::isNormalLoad(InVec.getNode()) &&
10070       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10071     SDValue Index = N->getOperand(1);
10072     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10073       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10074                                                            OrigLoad);
10075   }
10076 
10077   // Perform only after legalization to ensure build_vector / vector_shuffle
10078   // optimizations have already been done.
10079   if (!LegalOperations) return SDValue();
10080 
10081   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10082   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10083   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10084 
10085   if (ConstEltNo) {
10086     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10087 
10088     LoadSDNode *LN0 = nullptr;
10089     const ShuffleVectorSDNode *SVN = nullptr;
10090     if (ISD::isNormalLoad(InVec.getNode())) {
10091       LN0 = cast<LoadSDNode>(InVec);
10092     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10093                InVec.getOperand(0).getValueType() == ExtVT &&
10094                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10095       // Don't duplicate a load with other uses.
10096       if (!InVec.hasOneUse())
10097         return SDValue();
10098 
10099       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10100     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10101       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10102       // =>
10103       // (load $addr+1*size)
10104 
10105       // Don't duplicate a load with other uses.
10106       if (!InVec.hasOneUse())
10107         return SDValue();
10108 
10109       // If the bit convert changed the number of elements, it is unsafe
10110       // to examine the mask.
10111       if (BCNumEltsChanged)
10112         return SDValue();
10113 
10114       // Select the input vector, guarding against out of range extract vector.
10115       unsigned NumElems = VT.getVectorNumElements();
10116       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10117       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10118 
10119       if (InVec.getOpcode() == ISD::BITCAST) {
10120         // Don't duplicate a load with other uses.
10121         if (!InVec.hasOneUse())
10122           return SDValue();
10123 
10124         InVec = InVec.getOperand(0);
10125       }
10126       if (ISD::isNormalLoad(InVec.getNode())) {
10127         LN0 = cast<LoadSDNode>(InVec);
10128         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10129         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10130       }
10131     }
10132 
10133     // Make sure we found a non-volatile load and the extractelement is
10134     // the only use.
10135     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10136       return SDValue();
10137 
10138     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10139     if (Elt == -1)
10140       return DAG.getUNDEF(LVT);
10141 
10142     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10143   }
10144 
10145   return SDValue();
10146 }
10147 
10148 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10149 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10150   // We perform this optimization post type-legalization because
10151   // the type-legalizer often scalarizes integer-promoted vectors.
10152   // Performing this optimization before may create bit-casts which
10153   // will be type-legalized to complex code sequences.
10154   // We perform this optimization only before the operation legalizer because we
10155   // may introduce illegal operations.
10156   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10157     return SDValue();
10158 
10159   unsigned NumInScalars = N->getNumOperands();
10160   SDLoc dl(N);
10161   EVT VT = N->getValueType(0);
10162 
10163   // Check to see if this is a BUILD_VECTOR of a bunch of values
10164   // which come from any_extend or zero_extend nodes. If so, we can create
10165   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10166   // optimizations. We do not handle sign-extend because we can't fill the sign
10167   // using shuffles.
10168   EVT SourceType = MVT::Other;
10169   bool AllAnyExt = true;
10170 
10171   for (unsigned i = 0; i != NumInScalars; ++i) {
10172     SDValue In = N->getOperand(i);
10173     // Ignore undef inputs.
10174     if (In.getOpcode() == ISD::UNDEF) continue;
10175 
10176     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10177     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10178 
10179     // Abort if the element is not an extension.
10180     if (!ZeroExt && !AnyExt) {
10181       SourceType = MVT::Other;
10182       break;
10183     }
10184 
10185     // The input is a ZeroExt or AnyExt. Check the original type.
10186     EVT InTy = In.getOperand(0).getValueType();
10187 
10188     // Check that all of the widened source types are the same.
10189     if (SourceType == MVT::Other)
10190       // First time.
10191       SourceType = InTy;
10192     else if (InTy != SourceType) {
10193       // Multiple income types. Abort.
10194       SourceType = MVT::Other;
10195       break;
10196     }
10197 
10198     // Check if all of the extends are ANY_EXTENDs.
10199     AllAnyExt &= AnyExt;
10200   }
10201 
10202   // In order to have valid types, all of the inputs must be extended from the
10203   // same source type and all of the inputs must be any or zero extend.
10204   // Scalar sizes must be a power of two.
10205   EVT OutScalarTy = VT.getScalarType();
10206   bool ValidTypes = SourceType != MVT::Other &&
10207                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10208                  isPowerOf2_32(SourceType.getSizeInBits());
10209 
10210   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10211   // turn into a single shuffle instruction.
10212   if (!ValidTypes)
10213     return SDValue();
10214 
10215   bool isLE = TLI.isLittleEndian();
10216   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10217   assert(ElemRatio > 1 && "Invalid element size ratio");
10218   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10219                                DAG.getConstant(0, SourceType);
10220 
10221   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10222   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10223 
10224   // Populate the new build_vector
10225   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10226     SDValue Cast = N->getOperand(i);
10227     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10228             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10229             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10230     SDValue In;
10231     if (Cast.getOpcode() == ISD::UNDEF)
10232       In = DAG.getUNDEF(SourceType);
10233     else
10234       In = Cast->getOperand(0);
10235     unsigned Index = isLE ? (i * ElemRatio) :
10236                             (i * ElemRatio + (ElemRatio - 1));
10237 
10238     assert(Index < Ops.size() && "Invalid index");
10239     Ops[Index] = In;
10240   }
10241 
10242   // The type of the new BUILD_VECTOR node.
10243   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10244   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10245          "Invalid vector size");
10246   // Check if the new vector type is legal.
10247   if (!isTypeLegal(VecVT)) return SDValue();
10248 
10249   // Make the new BUILD_VECTOR.
10250   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10251 
10252   // The new BUILD_VECTOR node has the potential to be further optimized.
10253   AddToWorklist(BV.getNode());
10254   // Bitcast to the desired type.
10255   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10256 }
10257 
10258 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10259   EVT VT = N->getValueType(0);
10260 
10261   unsigned NumInScalars = N->getNumOperands();
10262   SDLoc dl(N);
10263 
10264   EVT SrcVT = MVT::Other;
10265   unsigned Opcode = ISD::DELETED_NODE;
10266   unsigned NumDefs = 0;
10267 
10268   for (unsigned i = 0; i != NumInScalars; ++i) {
10269     SDValue In = N->getOperand(i);
10270     unsigned Opc = In.getOpcode();
10271 
10272     if (Opc == ISD::UNDEF)
10273       continue;
10274 
10275     // If all scalar values are floats and converted from integers.
10276     if (Opcode == ISD::DELETED_NODE &&
10277         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10278       Opcode = Opc;
10279     }
10280 
10281     if (Opc != Opcode)
10282       return SDValue();
10283 
10284     EVT InVT = In.getOperand(0).getValueType();
10285 
10286     // If all scalar values are typed differently, bail out. It's chosen to
10287     // simplify BUILD_VECTOR of integer types.
10288     if (SrcVT == MVT::Other)
10289       SrcVT = InVT;
10290     if (SrcVT != InVT)
10291       return SDValue();
10292     NumDefs++;
10293   }
10294 
10295   // If the vector has just one element defined, it's not worth to fold it into
10296   // a vectorized one.
10297   if (NumDefs < 2)
10298     return SDValue();
10299 
10300   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10301          && "Should only handle conversion from integer to float.");
10302   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10303 
10304   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10305 
10306   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10307     return SDValue();
10308 
10309   SmallVector<SDValue, 8> Opnds;
10310   for (unsigned i = 0; i != NumInScalars; ++i) {
10311     SDValue In = N->getOperand(i);
10312 
10313     if (In.getOpcode() == ISD::UNDEF)
10314       Opnds.push_back(DAG.getUNDEF(SrcVT));
10315     else
10316       Opnds.push_back(In.getOperand(0));
10317   }
10318   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10319   AddToWorklist(BV.getNode());
10320 
10321   return DAG.getNode(Opcode, dl, VT, BV);
10322 }
10323 
10324 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10325   unsigned NumInScalars = N->getNumOperands();
10326   SDLoc dl(N);
10327   EVT VT = N->getValueType(0);
10328 
10329   // A vector built entirely of undefs is undef.
10330   if (ISD::allOperandsUndef(N))
10331     return DAG.getUNDEF(VT);
10332 
10333   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10334   if (V.getNode())
10335     return V;
10336 
10337   V = reduceBuildVecConvertToConvertBuildVec(N);
10338   if (V.getNode())
10339     return V;
10340 
10341   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10342   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10343   // at most two distinct vectors, turn this into a shuffle node.
10344 
10345   // May only combine to shuffle after legalize if shuffle is legal.
10346   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10347     return SDValue();
10348 
10349   SDValue VecIn1, VecIn2;
10350   for (unsigned i = 0; i != NumInScalars; ++i) {
10351     // Ignore undef inputs.
10352     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10353 
10354     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10355     // constant index, bail out.
10356     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10357         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10358       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10359       break;
10360     }
10361 
10362     // We allow up to two distinct input vectors.
10363     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10364     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10365       continue;
10366 
10367     if (!VecIn1.getNode()) {
10368       VecIn1 = ExtractedFromVec;
10369     } else if (!VecIn2.getNode()) {
10370       VecIn2 = ExtractedFromVec;
10371     } else {
10372       // Too many inputs.
10373       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10374       break;
10375     }
10376   }
10377 
10378   // If everything is good, we can make a shuffle operation.
10379   if (VecIn1.getNode()) {
10380     SmallVector<int, 8> Mask;
10381     for (unsigned i = 0; i != NumInScalars; ++i) {
10382       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10383         Mask.push_back(-1);
10384         continue;
10385       }
10386 
10387       // If extracting from the first vector, just use the index directly.
10388       SDValue Extract = N->getOperand(i);
10389       SDValue ExtVal = Extract.getOperand(1);
10390       if (Extract.getOperand(0) == VecIn1) {
10391         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10392         if (ExtIndex > VT.getVectorNumElements())
10393           return SDValue();
10394 
10395         Mask.push_back(ExtIndex);
10396         continue;
10397       }
10398 
10399       // Otherwise, use InIdx + VecSize
10400       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10401       Mask.push_back(Idx+NumInScalars);
10402     }
10403 
10404     // We can't generate a shuffle node with mismatched input and output types.
10405     // Attempt to transform a single input vector to the correct type.
10406     if ((VT != VecIn1.getValueType())) {
10407       // We don't support shuffeling between TWO values of different types.
10408       if (VecIn2.getNode())
10409         return SDValue();
10410 
10411       // We only support widening of vectors which are half the size of the
10412       // output registers. For example XMM->YMM widening on X86 with AVX.
10413       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10414         return SDValue();
10415 
10416       // If the input vector type has a different base type to the output
10417       // vector type, bail out.
10418       if (VecIn1.getValueType().getVectorElementType() !=
10419           VT.getVectorElementType())
10420         return SDValue();
10421 
10422       // Widen the input vector by adding undef values.
10423       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10424                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10425     }
10426 
10427     // If VecIn2 is unused then change it to undef.
10428     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10429 
10430     // Check that we were able to transform all incoming values to the same
10431     // type.
10432     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10433         VecIn1.getValueType() != VT)
10434           return SDValue();
10435 
10436     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10437     if (!isTypeLegal(VT))
10438       return SDValue();
10439 
10440     // Return the new VECTOR_SHUFFLE node.
10441     SDValue Ops[2];
10442     Ops[0] = VecIn1;
10443     Ops[1] = VecIn2;
10444     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10445   }
10446 
10447   return SDValue();
10448 }
10449 
10450 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10451   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10452   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10453   // inputs come from at most two distinct vectors, turn this into a shuffle
10454   // node.
10455 
10456   // If we only have one input vector, we don't need to do any concatenation.
10457   if (N->getNumOperands() == 1)
10458     return N->getOperand(0);
10459 
10460   // Check if all of the operands are undefs.
10461   EVT VT = N->getValueType(0);
10462   if (ISD::allOperandsUndef(N))
10463     return DAG.getUNDEF(VT);
10464 
10465   // Optimize concat_vectors where one of the vectors is undef.
10466   if (N->getNumOperands() == 2 &&
10467       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10468     SDValue In = N->getOperand(0);
10469     assert(In.getValueType().isVector() && "Must concat vectors");
10470 
10471     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10472     if (In->getOpcode() == ISD::BITCAST &&
10473         !In->getOperand(0)->getValueType(0).isVector()) {
10474       SDValue Scalar = In->getOperand(0);
10475       EVT SclTy = Scalar->getValueType(0);
10476 
10477       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10478         return SDValue();
10479 
10480       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10481                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10482       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10483         return SDValue();
10484 
10485       SDLoc dl = SDLoc(N);
10486       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10487       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10488     }
10489   }
10490 
10491   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10492   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10493   if (N->getNumOperands() == 2 &&
10494       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10495       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10496     EVT VT = N->getValueType(0);
10497     SDValue N0 = N->getOperand(0);
10498     SDValue N1 = N->getOperand(1);
10499     SmallVector<SDValue, 8> Opnds;
10500     unsigned BuildVecNumElts =  N0.getNumOperands();
10501 
10502     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10503     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10504     if (SclTy0.isFloatingPoint()) {
10505       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10506         Opnds.push_back(N0.getOperand(i));
10507       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10508         Opnds.push_back(N1.getOperand(i));
10509     } else {
10510       // If BUILD_VECTOR are from built from integer, they may have different
10511       // operand types. Get the smaller type and truncate all operands to it.
10512       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10513       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10514         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10515                         N0.getOperand(i)));
10516       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10517         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10518                         N1.getOperand(i)));
10519     }
10520 
10521     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10522   }
10523 
10524   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10525   // nodes often generate nop CONCAT_VECTOR nodes.
10526   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10527   // place the incoming vectors at the exact same location.
10528   SDValue SingleSource = SDValue();
10529   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10530 
10531   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10532     SDValue Op = N->getOperand(i);
10533 
10534     if (Op.getOpcode() == ISD::UNDEF)
10535       continue;
10536 
10537     // Check if this is the identity extract:
10538     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10539       return SDValue();
10540 
10541     // Find the single incoming vector for the extract_subvector.
10542     if (SingleSource.getNode()) {
10543       if (Op.getOperand(0) != SingleSource)
10544         return SDValue();
10545     } else {
10546       SingleSource = Op.getOperand(0);
10547 
10548       // Check the source type is the same as the type of the result.
10549       // If not, this concat may extend the vector, so we can not
10550       // optimize it away.
10551       if (SingleSource.getValueType() != N->getValueType(0))
10552         return SDValue();
10553     }
10554 
10555     unsigned IdentityIndex = i * PartNumElem;
10556     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10557     // The extract index must be constant.
10558     if (!CS)
10559       return SDValue();
10560 
10561     // Check that we are reading from the identity index.
10562     if (CS->getZExtValue() != IdentityIndex)
10563       return SDValue();
10564   }
10565 
10566   if (SingleSource.getNode())
10567     return SingleSource;
10568 
10569   return SDValue();
10570 }
10571 
10572 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10573   EVT NVT = N->getValueType(0);
10574   SDValue V = N->getOperand(0);
10575 
10576   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10577     // Combine:
10578     //    (extract_subvec (concat V1, V2, ...), i)
10579     // Into:
10580     //    Vi if possible
10581     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10582     // type.
10583     if (V->getOperand(0).getValueType() != NVT)
10584       return SDValue();
10585     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10586     unsigned NumElems = NVT.getVectorNumElements();
10587     assert((Idx % NumElems) == 0 &&
10588            "IDX in concat is not a multiple of the result vector length.");
10589     return V->getOperand(Idx / NumElems);
10590   }
10591 
10592   // Skip bitcasting
10593   if (V->getOpcode() == ISD::BITCAST)
10594     V = V.getOperand(0);
10595 
10596   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10597     SDLoc dl(N);
10598     // Handle only simple case where vector being inserted and vector
10599     // being extracted are of same type, and are half size of larger vectors.
10600     EVT BigVT = V->getOperand(0).getValueType();
10601     EVT SmallVT = V->getOperand(1).getValueType();
10602     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10603       return SDValue();
10604 
10605     // Only handle cases where both indexes are constants with the same type.
10606     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10607     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10608 
10609     if (InsIdx && ExtIdx &&
10610         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10611         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10612       // Combine:
10613       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10614       // Into:
10615       //    indices are equal or bit offsets are equal => V1
10616       //    otherwise => (extract_subvec V1, ExtIdx)
10617       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10618           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10619         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10620       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10621                          DAG.getNode(ISD::BITCAST, dl,
10622                                      N->getOperand(0).getValueType(),
10623                                      V->getOperand(0)), N->getOperand(1));
10624     }
10625   }
10626 
10627   return SDValue();
10628 }
10629 
10630 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10631 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10632   EVT VT = N->getValueType(0);
10633   unsigned NumElts = VT.getVectorNumElements();
10634 
10635   SDValue N0 = N->getOperand(0);
10636   SDValue N1 = N->getOperand(1);
10637   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10638 
10639   SmallVector<SDValue, 4> Ops;
10640   EVT ConcatVT = N0.getOperand(0).getValueType();
10641   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10642   unsigned NumConcats = NumElts / NumElemsPerConcat;
10643 
10644   // Look at every vector that's inserted. We're looking for exact
10645   // subvector-sized copies from a concatenated vector
10646   for (unsigned I = 0; I != NumConcats; ++I) {
10647     // Make sure we're dealing with a copy.
10648     unsigned Begin = I * NumElemsPerConcat;
10649     bool AllUndef = true, NoUndef = true;
10650     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10651       if (SVN->getMaskElt(J) >= 0)
10652         AllUndef = false;
10653       else
10654         NoUndef = false;
10655     }
10656 
10657     if (NoUndef) {
10658       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10659         return SDValue();
10660 
10661       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10662         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10663           return SDValue();
10664 
10665       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10666       if (FirstElt < N0.getNumOperands())
10667         Ops.push_back(N0.getOperand(FirstElt));
10668       else
10669         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10670 
10671     } else if (AllUndef) {
10672       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10673     } else { // Mixed with general masks and undefs, can't do optimization.
10674       return SDValue();
10675     }
10676   }
10677 
10678   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10679 }
10680 
10681 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10682   EVT VT = N->getValueType(0);
10683   unsigned NumElts = VT.getVectorNumElements();
10684 
10685   SDValue N0 = N->getOperand(0);
10686   SDValue N1 = N->getOperand(1);
10687 
10688   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10689 
10690   // Canonicalize shuffle undef, undef -> undef
10691   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10692     return DAG.getUNDEF(VT);
10693 
10694   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10695 
10696   // Canonicalize shuffle v, v -> v, undef
10697   if (N0 == N1) {
10698     SmallVector<int, 8> NewMask;
10699     for (unsigned i = 0; i != NumElts; ++i) {
10700       int Idx = SVN->getMaskElt(i);
10701       if (Idx >= (int)NumElts) Idx -= NumElts;
10702       NewMask.push_back(Idx);
10703     }
10704     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10705                                 &NewMask[0]);
10706   }
10707 
10708   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10709   if (N0.getOpcode() == ISD::UNDEF) {
10710     SmallVector<int, 8> NewMask;
10711     for (unsigned i = 0; i != NumElts; ++i) {
10712       int Idx = SVN->getMaskElt(i);
10713       if (Idx >= 0) {
10714         if (Idx >= (int)NumElts)
10715           Idx -= NumElts;
10716         else
10717           Idx = -1; // remove reference to lhs
10718       }
10719       NewMask.push_back(Idx);
10720     }
10721     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10722                                 &NewMask[0]);
10723   }
10724 
10725   // Remove references to rhs if it is undef
10726   if (N1.getOpcode() == ISD::UNDEF) {
10727     bool Changed = false;
10728     SmallVector<int, 8> NewMask;
10729     for (unsigned i = 0; i != NumElts; ++i) {
10730       int Idx = SVN->getMaskElt(i);
10731       if (Idx >= (int)NumElts) {
10732         Idx = -1;
10733         Changed = true;
10734       }
10735       NewMask.push_back(Idx);
10736     }
10737     if (Changed)
10738       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10739   }
10740 
10741   // If it is a splat, check if the argument vector is another splat or a
10742   // build_vector with all scalar elements the same.
10743   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10744     SDNode *V = N0.getNode();
10745 
10746     // If this is a bit convert that changes the element type of the vector but
10747     // not the number of vector elements, look through it.  Be careful not to
10748     // look though conversions that change things like v4f32 to v2f64.
10749     if (V->getOpcode() == ISD::BITCAST) {
10750       SDValue ConvInput = V->getOperand(0);
10751       if (ConvInput.getValueType().isVector() &&
10752           ConvInput.getValueType().getVectorNumElements() == NumElts)
10753         V = ConvInput.getNode();
10754     }
10755 
10756     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10757       assert(V->getNumOperands() == NumElts &&
10758              "BUILD_VECTOR has wrong number of operands");
10759       SDValue Base;
10760       bool AllSame = true;
10761       for (unsigned i = 0; i != NumElts; ++i) {
10762         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10763           Base = V->getOperand(i);
10764           break;
10765         }
10766       }
10767       // Splat of <u, u, u, u>, return <u, u, u, u>
10768       if (!Base.getNode())
10769         return N0;
10770       for (unsigned i = 0; i != NumElts; ++i) {
10771         if (V->getOperand(i) != Base) {
10772           AllSame = false;
10773           break;
10774         }
10775       }
10776       // Splat of <x, x, x, x>, return <x, x, x, x>
10777       if (AllSame)
10778         return N0;
10779     }
10780   }
10781 
10782   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10783       Level < AfterLegalizeVectorOps &&
10784       (N1.getOpcode() == ISD::UNDEF ||
10785       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10786        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10787     SDValue V = partitionShuffleOfConcats(N, DAG);
10788 
10789     if (V.getNode())
10790       return V;
10791   }
10792 
10793   // If this shuffle node is simply a swizzle of another shuffle node,
10794   // then try to simplify it.
10795   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10796       N1.getOpcode() == ISD::UNDEF) {
10797 
10798     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10799 
10800     // The incoming shuffle must be of the same type as the result of the
10801     // current shuffle.
10802     assert(OtherSV->getOperand(0).getValueType() == VT &&
10803            "Shuffle types don't match");
10804 
10805     SmallVector<int, 4> Mask;
10806     // Compute the combined shuffle mask.
10807     for (unsigned i = 0; i != NumElts; ++i) {
10808       int Idx = SVN->getMaskElt(i);
10809       assert(Idx < (int)NumElts && "Index references undef operand");
10810       // Next, this index comes from the first value, which is the incoming
10811       // shuffle. Adopt the incoming index.
10812       if (Idx >= 0)
10813         Idx = OtherSV->getMaskElt(Idx);
10814       Mask.push_back(Idx);
10815     }
10816 
10817     // Check if all indices in Mask are Undef. In case, propagate Undef.
10818     bool isUndefMask = true;
10819     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10820       isUndefMask &= Mask[i] < 0;
10821 
10822     if (isUndefMask)
10823       return DAG.getUNDEF(VT);
10824     
10825     bool CommuteOperands = false;
10826     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10827       // To be valid, the combine shuffle mask should only reference elements
10828       // from one of the two vectors in input to the inner shufflevector.
10829       bool IsValidMask = true;
10830       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10831         // See if the combined mask only reference undefs or elements coming
10832         // from the first shufflevector operand.
10833         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10834 
10835       if (!IsValidMask) {
10836         IsValidMask = true;
10837         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10838           // Check that all the elements come from the second shuffle operand.
10839           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10840         CommuteOperands = IsValidMask;
10841       }
10842 
10843       // Early exit if the combined shuffle mask is not valid.
10844       if (!IsValidMask)
10845         return SDValue();
10846     }
10847 
10848     // See if this pair of shuffles can be safely folded according to either
10849     // of the following rules:
10850     //   shuffle(shuffle(x, y), undef) -> x
10851     //   shuffle(shuffle(x, undef), undef) -> x
10852     //   shuffle(shuffle(x, y), undef) -> y
10853     bool IsIdentityMask = true;
10854     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10855     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10856       // Skip Undefs.
10857       if (Mask[i] < 0)
10858         continue;
10859 
10860       // The combined shuffle must map each index to itself.
10861       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10862     }
10863     
10864     if (IsIdentityMask) {
10865       if (CommuteOperands)
10866         // optimize shuffle(shuffle(x, y), undef) -> y.
10867         return OtherSV->getOperand(1);
10868       
10869       // optimize shuffle(shuffle(x, undef), undef) -> x
10870       // optimize shuffle(shuffle(x, y), undef) -> x
10871       return OtherSV->getOperand(0);
10872     }
10873 
10874     // It may still be beneficial to combine the two shuffles if the
10875     // resulting shuffle is legal.
10876     if (TLI.isTypeLegal(VT)) {
10877       if (!CommuteOperands) {
10878         if (TLI.isShuffleMaskLegal(Mask, VT))
10879           // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10880           // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10881           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10882                                       &Mask[0]);
10883       } else {
10884         // Compute the commuted shuffle mask.
10885         for (unsigned i = 0; i != NumElts; ++i) {
10886           int idx = Mask[i];
10887           if (idx < 0)
10888             continue;
10889           else if (idx < (int)NumElts)
10890             Mask[i] = idx + NumElts;
10891           else
10892             Mask[i] = idx - NumElts;
10893         }
10894 
10895         if (TLI.isShuffleMaskLegal(Mask, VT))
10896           //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(y, undef, M3)
10897           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(1), N1,
10898                                       &Mask[0]);
10899       }
10900     }
10901   }
10902 
10903   // Canonicalize shuffles according to rules:
10904   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10905   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10906   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10907   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10908       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10909       TLI.isTypeLegal(VT)) {
10910     // The incoming shuffle must be of the same type as the result of the
10911     // current shuffle.
10912     assert(N1->getOperand(0).getValueType() == VT &&
10913            "Shuffle types don't match");
10914 
10915     SDValue SV0 = N1->getOperand(0);
10916     SDValue SV1 = N1->getOperand(1);
10917     bool HasSameOp0 = N0 == SV0;
10918     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10919     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10920       // Commute the operands of this shuffle so that next rule
10921       // will trigger.
10922       return DAG.getCommutedVectorShuffle(*SVN);
10923   }
10924 
10925   // Try to fold according to rules:
10926   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10927   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10928   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10929   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10930   // Don't try to fold shuffles with illegal type.
10931   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10932       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10933     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10934 
10935     // The incoming shuffle must be of the same type as the result of the
10936     // current shuffle.
10937     assert(OtherSV->getOperand(0).getValueType() == VT &&
10938            "Shuffle types don't match");
10939 
10940     SDValue SV0 = OtherSV->getOperand(0);
10941     SDValue SV1 = OtherSV->getOperand(1);
10942     bool HasSameOp0 = N1 == SV0;
10943     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10944     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10945       // Early exit.
10946       return SDValue();
10947 
10948     SmallVector<int, 4> Mask;
10949     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10950     // operand, and SV1 as the second operand.
10951     for (unsigned i = 0; i != NumElts; ++i) {
10952       int Idx = SVN->getMaskElt(i);
10953       if (Idx < 0) {
10954         // Propagate Undef.
10955         Mask.push_back(Idx);
10956         continue;
10957       }
10958 
10959       if (Idx < (int)NumElts) {
10960         Idx = OtherSV->getMaskElt(Idx);
10961         if (IsSV1Undef && Idx >= (int) NumElts)
10962           Idx = -1;  // Propagate Undef.
10963       } else
10964         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10965 
10966       Mask.push_back(Idx);
10967     }
10968 
10969     // Check if all indices in Mask are Undef. In case, propagate Undef.
10970     bool isUndefMask = true;
10971     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
10972       isUndefMask &= Mask[i] < 0;
10973 
10974     if (isUndefMask)
10975       return DAG.getUNDEF(VT);
10976 
10977     // Avoid introducing shuffles with illegal mask.
10978     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10979       if (IsSV1Undef)
10980         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10981         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10982         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10983       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10984     }
10985   }
10986 
10987   return SDValue();
10988 }
10989 
10990 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10991   SDValue N0 = N->getOperand(0);
10992   SDValue N2 = N->getOperand(2);
10993 
10994   // If the input vector is a concatenation, and the insert replaces
10995   // one of the halves, we can optimize into a single concat_vectors.
10996   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10997       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10998     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10999     EVT VT = N->getValueType(0);
11000 
11001     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11002     // (concat_vectors Z, Y)
11003     if (InsIdx == 0)
11004       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11005                          N->getOperand(1), N0.getOperand(1));
11006 
11007     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11008     // (concat_vectors X, Z)
11009     if (InsIdx == VT.getVectorNumElements()/2)
11010       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11011                          N0.getOperand(0), N->getOperand(1));
11012   }
11013 
11014   return SDValue();
11015 }
11016 
11017 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11018 /// with the destination vector and a zero vector.
11019 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11020 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11021 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11022   EVT VT = N->getValueType(0);
11023   SDLoc dl(N);
11024   SDValue LHS = N->getOperand(0);
11025   SDValue RHS = N->getOperand(1);
11026   if (N->getOpcode() == ISD::AND) {
11027     if (RHS.getOpcode() == ISD::BITCAST)
11028       RHS = RHS.getOperand(0);
11029     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11030       SmallVector<int, 8> Indices;
11031       unsigned NumElts = RHS.getNumOperands();
11032       for (unsigned i = 0; i != NumElts; ++i) {
11033         SDValue Elt = RHS.getOperand(i);
11034         if (!isa<ConstantSDNode>(Elt))
11035           return SDValue();
11036 
11037         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11038           Indices.push_back(i);
11039         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11040           Indices.push_back(NumElts);
11041         else
11042           return SDValue();
11043       }
11044 
11045       // Let's see if the target supports this vector_shuffle.
11046       EVT RVT = RHS.getValueType();
11047       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11048         return SDValue();
11049 
11050       // Return the new VECTOR_SHUFFLE node.
11051       EVT EltVT = RVT.getVectorElementType();
11052       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11053                                      DAG.getConstant(0, EltVT));
11054       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11055       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11056       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11057       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11058     }
11059   }
11060 
11061   return SDValue();
11062 }
11063 
11064 /// Visit a binary vector operation, like ADD.
11065 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11066   assert(N->getValueType(0).isVector() &&
11067          "SimplifyVBinOp only works on vectors!");
11068 
11069   SDValue LHS = N->getOperand(0);
11070   SDValue RHS = N->getOperand(1);
11071   SDValue Shuffle = XformToShuffleWithZero(N);
11072   if (Shuffle.getNode()) return Shuffle;
11073 
11074   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11075   // this operation.
11076   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11077       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11078     // Check if both vectors are constants. If not bail out.
11079     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11080           cast<BuildVectorSDNode>(RHS)->isConstant()))
11081       return SDValue();
11082 
11083     SmallVector<SDValue, 8> Ops;
11084     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11085       SDValue LHSOp = LHS.getOperand(i);
11086       SDValue RHSOp = RHS.getOperand(i);
11087 
11088       // Can't fold divide by zero.
11089       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11090           N->getOpcode() == ISD::FDIV) {
11091         if ((RHSOp.getOpcode() == ISD::Constant &&
11092              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11093             (RHSOp.getOpcode() == ISD::ConstantFP &&
11094              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11095           break;
11096       }
11097 
11098       EVT VT = LHSOp.getValueType();
11099       EVT RVT = RHSOp.getValueType();
11100       if (RVT != VT) {
11101         // Integer BUILD_VECTOR operands may have types larger than the element
11102         // size (e.g., when the element type is not legal).  Prior to type
11103         // legalization, the types may not match between the two BUILD_VECTORS.
11104         // Truncate one of the operands to make them match.
11105         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11106           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11107         } else {
11108           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11109           VT = RVT;
11110         }
11111       }
11112       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11113                                    LHSOp, RHSOp);
11114       if (FoldOp.getOpcode() != ISD::UNDEF &&
11115           FoldOp.getOpcode() != ISD::Constant &&
11116           FoldOp.getOpcode() != ISD::ConstantFP)
11117         break;
11118       Ops.push_back(FoldOp);
11119       AddToWorklist(FoldOp.getNode());
11120     }
11121 
11122     if (Ops.size() == LHS.getNumOperands())
11123       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11124   }
11125 
11126   // Type legalization might introduce new shuffles in the DAG.
11127   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11128   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11129   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11130       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11131       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11132       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11133     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11134     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11135 
11136     if (SVN0->getMask().equals(SVN1->getMask())) {
11137       EVT VT = N->getValueType(0);
11138       SDValue UndefVector = LHS.getOperand(1);
11139       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11140                                      LHS.getOperand(0), RHS.getOperand(0));
11141       AddUsersToWorklist(N);
11142       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11143                                   &SVN0->getMask()[0]);
11144     }
11145   }
11146 
11147   return SDValue();
11148 }
11149 
11150 /// Visit a binary vector operation, like FABS/FNEG.
11151 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11152   assert(N->getValueType(0).isVector() &&
11153          "SimplifyVUnaryOp only works on vectors!");
11154 
11155   SDValue N0 = N->getOperand(0);
11156 
11157   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11158     return SDValue();
11159 
11160   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11161   SmallVector<SDValue, 8> Ops;
11162   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11163     SDValue Op = N0.getOperand(i);
11164     if (Op.getOpcode() != ISD::UNDEF &&
11165         Op.getOpcode() != ISD::ConstantFP)
11166       break;
11167     EVT EltVT = Op.getValueType();
11168     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11169     if (FoldOp.getOpcode() != ISD::UNDEF &&
11170         FoldOp.getOpcode() != ISD::ConstantFP)
11171       break;
11172     Ops.push_back(FoldOp);
11173     AddToWorklist(FoldOp.getNode());
11174   }
11175 
11176   if (Ops.size() != N0.getNumOperands())
11177     return SDValue();
11178 
11179   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11180 }
11181 
11182 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11183                                     SDValue N1, SDValue N2){
11184   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11185 
11186   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11187                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11188 
11189   // If we got a simplified select_cc node back from SimplifySelectCC, then
11190   // break it down into a new SETCC node, and a new SELECT node, and then return
11191   // the SELECT node, since we were called with a SELECT node.
11192   if (SCC.getNode()) {
11193     // Check to see if we got a select_cc back (to turn into setcc/select).
11194     // Otherwise, just return whatever node we got back, like fabs.
11195     if (SCC.getOpcode() == ISD::SELECT_CC) {
11196       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11197                                   N0.getValueType(),
11198                                   SCC.getOperand(0), SCC.getOperand(1),
11199                                   SCC.getOperand(4));
11200       AddToWorklist(SETCC.getNode());
11201       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11202                            SCC.getOperand(2), SCC.getOperand(3));
11203     }
11204 
11205     return SCC;
11206   }
11207   return SDValue();
11208 }
11209 
11210 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11211 /// being selected between, see if we can simplify the select.  Callers of this
11212 /// should assume that TheSelect is deleted if this returns true.  As such, they
11213 /// should return the appropriate thing (e.g. the node) back to the top-level of
11214 /// the DAG combiner loop to avoid it being looked at.
11215 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11216                                     SDValue RHS) {
11217 
11218   // Cannot simplify select with vector condition
11219   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11220 
11221   // If this is a select from two identical things, try to pull the operation
11222   // through the select.
11223   if (LHS.getOpcode() != RHS.getOpcode() ||
11224       !LHS.hasOneUse() || !RHS.hasOneUse())
11225     return false;
11226 
11227   // If this is a load and the token chain is identical, replace the select
11228   // of two loads with a load through a select of the address to load from.
11229   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11230   // constants have been dropped into the constant pool.
11231   if (LHS.getOpcode() == ISD::LOAD) {
11232     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11233     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11234 
11235     // Token chains must be identical.
11236     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11237         // Do not let this transformation reduce the number of volatile loads.
11238         LLD->isVolatile() || RLD->isVolatile() ||
11239         // If this is an EXTLOAD, the VT's must match.
11240         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11241         // If this is an EXTLOAD, the kind of extension must match.
11242         (LLD->getExtensionType() != RLD->getExtensionType() &&
11243          // The only exception is if one of the extensions is anyext.
11244          LLD->getExtensionType() != ISD::EXTLOAD &&
11245          RLD->getExtensionType() != ISD::EXTLOAD) ||
11246         // FIXME: this discards src value information.  This is
11247         // over-conservative. It would be beneficial to be able to remember
11248         // both potential memory locations.  Since we are discarding
11249         // src value info, don't do the transformation if the memory
11250         // locations are not in the default address space.
11251         LLD->getPointerInfo().getAddrSpace() != 0 ||
11252         RLD->getPointerInfo().getAddrSpace() != 0 ||
11253         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11254                                       LLD->getBasePtr().getValueType()))
11255       return false;
11256 
11257     // Check that the select condition doesn't reach either load.  If so,
11258     // folding this will induce a cycle into the DAG.  If not, this is safe to
11259     // xform, so create a select of the addresses.
11260     SDValue Addr;
11261     if (TheSelect->getOpcode() == ISD::SELECT) {
11262       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11263       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11264           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11265         return false;
11266       // The loads must not depend on one another.
11267       if (LLD->isPredecessorOf(RLD) ||
11268           RLD->isPredecessorOf(LLD))
11269         return false;
11270       Addr = DAG.getSelect(SDLoc(TheSelect),
11271                            LLD->getBasePtr().getValueType(),
11272                            TheSelect->getOperand(0), LLD->getBasePtr(),
11273                            RLD->getBasePtr());
11274     } else {  // Otherwise SELECT_CC
11275       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11276       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11277 
11278       if ((LLD->hasAnyUseOfValue(1) &&
11279            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11280           (RLD->hasAnyUseOfValue(1) &&
11281            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11282         return false;
11283 
11284       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11285                          LLD->getBasePtr().getValueType(),
11286                          TheSelect->getOperand(0),
11287                          TheSelect->getOperand(1),
11288                          LLD->getBasePtr(), RLD->getBasePtr(),
11289                          TheSelect->getOperand(4));
11290     }
11291 
11292     SDValue Load;
11293     // It is safe to replace the two loads if they have different alignments,
11294     // but the new load must be the minimum (most restrictive) alignment of the
11295     // inputs.
11296     bool isInvariant = LLD->getAlignment() & RLD->getAlignment();
11297     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11298     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11299       Load = DAG.getLoad(TheSelect->getValueType(0),
11300                          SDLoc(TheSelect),
11301                          // FIXME: Discards pointer and AA info.
11302                          LLD->getChain(), Addr, MachinePointerInfo(),
11303                          LLD->isVolatile(), LLD->isNonTemporal(),
11304                          isInvariant, Alignment);
11305     } else {
11306       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11307                             RLD->getExtensionType() : LLD->getExtensionType(),
11308                             SDLoc(TheSelect),
11309                             TheSelect->getValueType(0),
11310                             // FIXME: Discards pointer and AA info.
11311                             LLD->getChain(), Addr, MachinePointerInfo(),
11312                             LLD->getMemoryVT(), LLD->isVolatile(),
11313                             LLD->isNonTemporal(), isInvariant, Alignment);
11314     }
11315 
11316     // Users of the select now use the result of the load.
11317     CombineTo(TheSelect, Load);
11318 
11319     // Users of the old loads now use the new load's chain.  We know the
11320     // old-load value is dead now.
11321     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11322     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11323     return true;
11324   }
11325 
11326   return false;
11327 }
11328 
11329 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11330 /// where 'cond' is the comparison specified by CC.
11331 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11332                                       SDValue N2, SDValue N3,
11333                                       ISD::CondCode CC, bool NotExtCompare) {
11334   // (x ? y : y) -> y.
11335   if (N2 == N3) return N2;
11336 
11337   EVT VT = N2.getValueType();
11338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11339   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11340   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11341 
11342   // Determine if the condition we're dealing with is constant
11343   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11344                               N0, N1, CC, DL, false);
11345   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11346   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11347 
11348   // fold select_cc true, x, y -> x
11349   if (SCCC && !SCCC->isNullValue())
11350     return N2;
11351   // fold select_cc false, x, y -> y
11352   if (SCCC && SCCC->isNullValue())
11353     return N3;
11354 
11355   // Check to see if we can simplify the select into an fabs node
11356   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11357     // Allow either -0.0 or 0.0
11358     if (CFP->getValueAPF().isZero()) {
11359       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11360       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11361           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11362           N2 == N3.getOperand(0))
11363         return DAG.getNode(ISD::FABS, DL, VT, N0);
11364 
11365       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11366       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11367           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11368           N2.getOperand(0) == N3)
11369         return DAG.getNode(ISD::FABS, DL, VT, N3);
11370     }
11371   }
11372 
11373   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11374   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11375   // in it.  This is a win when the constant is not otherwise available because
11376   // it replaces two constant pool loads with one.  We only do this if the FP
11377   // type is known to be legal, because if it isn't, then we are before legalize
11378   // types an we want the other legalization to happen first (e.g. to avoid
11379   // messing with soft float) and if the ConstantFP is not legal, because if
11380   // it is legal, we may not need to store the FP constant in a constant pool.
11381   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11382     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11383       if (TLI.isTypeLegal(N2.getValueType()) &&
11384           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11385                TargetLowering::Legal &&
11386            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11387            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11388           // If both constants have multiple uses, then we won't need to do an
11389           // extra load, they are likely around in registers for other users.
11390           (TV->hasOneUse() || FV->hasOneUse())) {
11391         Constant *Elts[] = {
11392           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11393           const_cast<ConstantFP*>(TV->getConstantFPValue())
11394         };
11395         Type *FPTy = Elts[0]->getType();
11396         const DataLayout &TD = *TLI.getDataLayout();
11397 
11398         // Create a ConstantArray of the two constants.
11399         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11400         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11401                                             TD.getPrefTypeAlignment(FPTy));
11402         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11403 
11404         // Get the offsets to the 0 and 1 element of the array so that we can
11405         // select between them.
11406         SDValue Zero = DAG.getIntPtrConstant(0);
11407         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11408         SDValue One = DAG.getIntPtrConstant(EltSize);
11409 
11410         SDValue Cond = DAG.getSetCC(DL,
11411                                     getSetCCResultType(N0.getValueType()),
11412                                     N0, N1, CC);
11413         AddToWorklist(Cond.getNode());
11414         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11415                                           Cond, One, Zero);
11416         AddToWorklist(CstOffset.getNode());
11417         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11418                             CstOffset);
11419         AddToWorklist(CPIdx.getNode());
11420         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11421                            MachinePointerInfo::getConstantPool(), false,
11422                            false, false, Alignment);
11423 
11424       }
11425     }
11426 
11427   // Check to see if we can perform the "gzip trick", transforming
11428   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11429   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11430       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11431        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11432     EVT XType = N0.getValueType();
11433     EVT AType = N2.getValueType();
11434     if (XType.bitsGE(AType)) {
11435       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11436       // single-bit constant.
11437       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11438         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11439         ShCtV = XType.getSizeInBits()-ShCtV-1;
11440         SDValue ShCt = DAG.getConstant(ShCtV,
11441                                        getShiftAmountTy(N0.getValueType()));
11442         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11443                                     XType, N0, ShCt);
11444         AddToWorklist(Shift.getNode());
11445 
11446         if (XType.bitsGT(AType)) {
11447           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11448           AddToWorklist(Shift.getNode());
11449         }
11450 
11451         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11452       }
11453 
11454       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11455                                   XType, N0,
11456                                   DAG.getConstant(XType.getSizeInBits()-1,
11457                                          getShiftAmountTy(N0.getValueType())));
11458       AddToWorklist(Shift.getNode());
11459 
11460       if (XType.bitsGT(AType)) {
11461         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11462         AddToWorklist(Shift.getNode());
11463       }
11464 
11465       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11466     }
11467   }
11468 
11469   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11470   // where y is has a single bit set.
11471   // A plaintext description would be, we can turn the SELECT_CC into an AND
11472   // when the condition can be materialized as an all-ones register.  Any
11473   // single bit-test can be materialized as an all-ones register with
11474   // shift-left and shift-right-arith.
11475   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11476       N0->getValueType(0) == VT &&
11477       N1C && N1C->isNullValue() &&
11478       N2C && N2C->isNullValue()) {
11479     SDValue AndLHS = N0->getOperand(0);
11480     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11481     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11482       // Shift the tested bit over the sign bit.
11483       APInt AndMask = ConstAndRHS->getAPIntValue();
11484       SDValue ShlAmt =
11485         DAG.getConstant(AndMask.countLeadingZeros(),
11486                         getShiftAmountTy(AndLHS.getValueType()));
11487       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11488 
11489       // Now arithmetic right shift it all the way over, so the result is either
11490       // all-ones, or zero.
11491       SDValue ShrAmt =
11492         DAG.getConstant(AndMask.getBitWidth()-1,
11493                         getShiftAmountTy(Shl.getValueType()));
11494       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11495 
11496       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11497     }
11498   }
11499 
11500   // fold select C, 16, 0 -> shl C, 4
11501   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11502       TLI.getBooleanContents(N0.getValueType()) ==
11503           TargetLowering::ZeroOrOneBooleanContent) {
11504 
11505     // If the caller doesn't want us to simplify this into a zext of a compare,
11506     // don't do it.
11507     if (NotExtCompare && N2C->getAPIntValue() == 1)
11508       return SDValue();
11509 
11510     // Get a SetCC of the condition
11511     // NOTE: Don't create a SETCC if it's not legal on this target.
11512     if (!LegalOperations ||
11513         TLI.isOperationLegal(ISD::SETCC,
11514           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11515       SDValue Temp, SCC;
11516       // cast from setcc result type to select result type
11517       if (LegalTypes) {
11518         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11519                             N0, N1, CC);
11520         if (N2.getValueType().bitsLT(SCC.getValueType()))
11521           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11522                                         N2.getValueType());
11523         else
11524           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11525                              N2.getValueType(), SCC);
11526       } else {
11527         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11528         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11529                            N2.getValueType(), SCC);
11530       }
11531 
11532       AddToWorklist(SCC.getNode());
11533       AddToWorklist(Temp.getNode());
11534 
11535       if (N2C->getAPIntValue() == 1)
11536         return Temp;
11537 
11538       // shl setcc result by log2 n2c
11539       return DAG.getNode(
11540           ISD::SHL, DL, N2.getValueType(), Temp,
11541           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11542                           getShiftAmountTy(Temp.getValueType())));
11543     }
11544   }
11545 
11546   // Check to see if this is the equivalent of setcc
11547   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11548   // otherwise, go ahead with the folds.
11549   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11550     EVT XType = N0.getValueType();
11551     if (!LegalOperations ||
11552         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11553       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11554       if (Res.getValueType() != VT)
11555         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11556       return Res;
11557     }
11558 
11559     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11560     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11561         (!LegalOperations ||
11562          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11563       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11564       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11565                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11566                                        getShiftAmountTy(Ctlz.getValueType())));
11567     }
11568     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11569     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11570       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11571                                   XType, DAG.getConstant(0, XType), N0);
11572       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11573       return DAG.getNode(ISD::SRL, DL, XType,
11574                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11575                          DAG.getConstant(XType.getSizeInBits()-1,
11576                                          getShiftAmountTy(XType)));
11577     }
11578     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11579     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11580       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11581                                  DAG.getConstant(XType.getSizeInBits()-1,
11582                                          getShiftAmountTy(N0.getValueType())));
11583       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11584     }
11585   }
11586 
11587   // Check to see if this is an integer abs.
11588   // select_cc setg[te] X,  0,  X, -X ->
11589   // select_cc setgt    X, -1,  X, -X ->
11590   // select_cc setl[te] X,  0, -X,  X ->
11591   // select_cc setlt    X,  1, -X,  X ->
11592   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11593   if (N1C) {
11594     ConstantSDNode *SubC = nullptr;
11595     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11596          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11597         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11598       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11599     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11600               (N1C->isOne() && CC == ISD::SETLT)) &&
11601              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11602       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11603 
11604     EVT XType = N0.getValueType();
11605     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11606       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11607                                   N0,
11608                                   DAG.getConstant(XType.getSizeInBits()-1,
11609                                          getShiftAmountTy(N0.getValueType())));
11610       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11611                                 XType, N0, Shift);
11612       AddToWorklist(Shift.getNode());
11613       AddToWorklist(Add.getNode());
11614       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11615     }
11616   }
11617 
11618   return SDValue();
11619 }
11620 
11621 /// This is a stub for TargetLowering::SimplifySetCC.
11622 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11623                                    SDValue N1, ISD::CondCode Cond,
11624                                    SDLoc DL, bool foldBooleans) {
11625   TargetLowering::DAGCombinerInfo
11626     DagCombineInfo(DAG, Level, false, this);
11627   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11628 }
11629 
11630 /// Given an ISD::SDIV node expressing a divide by constant, return
11631 /// a DAG expression to select that will generate the same value by multiplying
11632 /// by a magic number.
11633 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11634 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11635   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11636   if (!C)
11637     return SDValue();
11638 
11639   // Avoid division by zero.
11640   if (!C->getAPIntValue())
11641     return SDValue();
11642 
11643   std::vector<SDNode*> Built;
11644   SDValue S =
11645       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11646 
11647   for (SDNode *N : Built)
11648     AddToWorklist(N);
11649   return S;
11650 }
11651 
11652 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11653 /// DAG expression that will generate the same value by right shifting.
11654 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11655   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11656   if (!C)
11657     return SDValue();
11658 
11659   // Avoid division by zero.
11660   if (!C->getAPIntValue())
11661     return SDValue();
11662 
11663   std::vector<SDNode *> Built;
11664   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11665 
11666   for (SDNode *N : Built)
11667     AddToWorklist(N);
11668   return S;
11669 }
11670 
11671 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11672 /// expression that will generate the same value by multiplying by a magic
11673 /// number.
11674 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11675 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11676   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11677   if (!C)
11678     return SDValue();
11679 
11680   // Avoid division by zero.
11681   if (!C->getAPIntValue())
11682     return SDValue();
11683 
11684   std::vector<SDNode*> Built;
11685   SDValue S =
11686       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11687 
11688   for (SDNode *N : Built)
11689     AddToWorklist(N);
11690   return S;
11691 }
11692 
11693 /// Return true if base is a frame index, which is known not to alias with
11694 /// anything but itself.  Provides base object and offset as results.
11695 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11696                            const GlobalValue *&GV, const void *&CV) {
11697   // Assume it is a primitive operation.
11698   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11699 
11700   // If it's an adding a simple constant then integrate the offset.
11701   if (Base.getOpcode() == ISD::ADD) {
11702     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11703       Base = Base.getOperand(0);
11704       Offset += C->getZExtValue();
11705     }
11706   }
11707 
11708   // Return the underlying GlobalValue, and update the Offset.  Return false
11709   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11710   // by multiple nodes with different offsets.
11711   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11712     GV = G->getGlobal();
11713     Offset += G->getOffset();
11714     return false;
11715   }
11716 
11717   // Return the underlying Constant value, and update the Offset.  Return false
11718   // for ConstantSDNodes since the same constant pool entry may be represented
11719   // by multiple nodes with different offsets.
11720   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11721     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11722                                          : (const void *)C->getConstVal();
11723     Offset += C->getOffset();
11724     return false;
11725   }
11726   // If it's any of the following then it can't alias with anything but itself.
11727   return isa<FrameIndexSDNode>(Base);
11728 }
11729 
11730 /// Return true if there is any possibility that the two addresses overlap.
11731 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11732   // If they are the same then they must be aliases.
11733   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11734 
11735   // If they are both volatile then they cannot be reordered.
11736   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11737 
11738   // Gather base node and offset information.
11739   SDValue Base1, Base2;
11740   int64_t Offset1, Offset2;
11741   const GlobalValue *GV1, *GV2;
11742   const void *CV1, *CV2;
11743   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11744                                       Base1, Offset1, GV1, CV1);
11745   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11746                                       Base2, Offset2, GV2, CV2);
11747 
11748   // If they have a same base address then check to see if they overlap.
11749   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11750     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11751              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11752 
11753   // It is possible for different frame indices to alias each other, mostly
11754   // when tail call optimization reuses return address slots for arguments.
11755   // To catch this case, look up the actual index of frame indices to compute
11756   // the real alias relationship.
11757   if (isFrameIndex1 && isFrameIndex2) {
11758     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11759     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11760     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11761     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11762              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11763   }
11764 
11765   // Otherwise, if we know what the bases are, and they aren't identical, then
11766   // we know they cannot alias.
11767   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11768     return false;
11769 
11770   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11771   // compared to the size and offset of the access, we may be able to prove they
11772   // do not alias.  This check is conservative for now to catch cases created by
11773   // splitting vector types.
11774   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11775       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11776       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11777        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11778       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11779     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11780     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11781 
11782     // There is no overlap between these relatively aligned accesses of similar
11783     // size, return no alias.
11784     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11785         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11786       return false;
11787   }
11788 
11789   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11790     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11791 #ifndef NDEBUG
11792   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11793       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11794     UseAA = false;
11795 #endif
11796   if (UseAA &&
11797       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11798     // Use alias analysis information.
11799     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11800                                  Op1->getSrcValueOffset());
11801     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11802         Op0->getSrcValueOffset() - MinOffset;
11803     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11804         Op1->getSrcValueOffset() - MinOffset;
11805     AliasAnalysis::AliasResult AAResult =
11806         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11807                                          Overlap1,
11808                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11809                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11810                                          Overlap2,
11811                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11812     if (AAResult == AliasAnalysis::NoAlias)
11813       return false;
11814   }
11815 
11816   // Otherwise we have to assume they alias.
11817   return true;
11818 }
11819 
11820 /// Walk up chain skipping non-aliasing memory nodes,
11821 /// looking for aliasing nodes and adding them to the Aliases vector.
11822 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11823                                    SmallVectorImpl<SDValue> &Aliases) {
11824   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11825   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11826 
11827   // Get alias information for node.
11828   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11829 
11830   // Starting off.
11831   Chains.push_back(OriginalChain);
11832   unsigned Depth = 0;
11833 
11834   // Look at each chain and determine if it is an alias.  If so, add it to the
11835   // aliases list.  If not, then continue up the chain looking for the next
11836   // candidate.
11837   while (!Chains.empty()) {
11838     SDValue Chain = Chains.back();
11839     Chains.pop_back();
11840 
11841     // For TokenFactor nodes, look at each operand and only continue up the
11842     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11843     // find more and revert to original chain since the xform is unlikely to be
11844     // profitable.
11845     //
11846     // FIXME: The depth check could be made to return the last non-aliasing
11847     // chain we found before we hit a tokenfactor rather than the original
11848     // chain.
11849     if (Depth > 6 || Aliases.size() == 2) {
11850       Aliases.clear();
11851       Aliases.push_back(OriginalChain);
11852       return;
11853     }
11854 
11855     // Don't bother if we've been before.
11856     if (!Visited.insert(Chain.getNode()))
11857       continue;
11858 
11859     switch (Chain.getOpcode()) {
11860     case ISD::EntryToken:
11861       // Entry token is ideal chain operand, but handled in FindBetterChain.
11862       break;
11863 
11864     case ISD::LOAD:
11865     case ISD::STORE: {
11866       // Get alias information for Chain.
11867       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11868           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11869 
11870       // If chain is alias then stop here.
11871       if (!(IsLoad && IsOpLoad) &&
11872           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11873         Aliases.push_back(Chain);
11874       } else {
11875         // Look further up the chain.
11876         Chains.push_back(Chain.getOperand(0));
11877         ++Depth;
11878       }
11879       break;
11880     }
11881 
11882     case ISD::TokenFactor:
11883       // We have to check each of the operands of the token factor for "small"
11884       // token factors, so we queue them up.  Adding the operands to the queue
11885       // (stack) in reverse order maintains the original order and increases the
11886       // likelihood that getNode will find a matching token factor (CSE.)
11887       if (Chain.getNumOperands() > 16) {
11888         Aliases.push_back(Chain);
11889         break;
11890       }
11891       for (unsigned n = Chain.getNumOperands(); n;)
11892         Chains.push_back(Chain.getOperand(--n));
11893       ++Depth;
11894       break;
11895 
11896     default:
11897       // For all other instructions we will just have to take what we can get.
11898       Aliases.push_back(Chain);
11899       break;
11900     }
11901   }
11902 
11903   // We need to be careful here to also search for aliases through the
11904   // value operand of a store, etc. Consider the following situation:
11905   //   Token1 = ...
11906   //   L1 = load Token1, %52
11907   //   S1 = store Token1, L1, %51
11908   //   L2 = load Token1, %52+8
11909   //   S2 = store Token1, L2, %51+8
11910   //   Token2 = Token(S1, S2)
11911   //   L3 = load Token2, %53
11912   //   S3 = store Token2, L3, %52
11913   //   L4 = load Token2, %53+8
11914   //   S4 = store Token2, L4, %52+8
11915   // If we search for aliases of S3 (which loads address %52), and we look
11916   // only through the chain, then we'll miss the trivial dependence on L1
11917   // (which also loads from %52). We then might change all loads and
11918   // stores to use Token1 as their chain operand, which could result in
11919   // copying %53 into %52 before copying %52 into %51 (which should
11920   // happen first).
11921   //
11922   // The problem is, however, that searching for such data dependencies
11923   // can become expensive, and the cost is not directly related to the
11924   // chain depth. Instead, we'll rule out such configurations here by
11925   // insisting that we've visited all chain users (except for users
11926   // of the original chain, which is not necessary). When doing this,
11927   // we need to look through nodes we don't care about (otherwise, things
11928   // like register copies will interfere with trivial cases).
11929 
11930   SmallVector<const SDNode *, 16> Worklist;
11931   for (const SDNode *N : Visited)
11932     if (N != OriginalChain.getNode())
11933       Worklist.push_back(N);
11934 
11935   while (!Worklist.empty()) {
11936     const SDNode *M = Worklist.pop_back_val();
11937 
11938     // We have already visited M, and want to make sure we've visited any uses
11939     // of M that we care about. For uses that we've not visisted, and don't
11940     // care about, queue them to the worklist.
11941 
11942     for (SDNode::use_iterator UI = M->use_begin(),
11943          UIE = M->use_end(); UI != UIE; ++UI)
11944       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11945         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11946           // We've not visited this use, and we care about it (it could have an
11947           // ordering dependency with the original node).
11948           Aliases.clear();
11949           Aliases.push_back(OriginalChain);
11950           return;
11951         }
11952 
11953         // We've not visited this use, but we don't care about it. Mark it as
11954         // visited and enqueue it to the worklist.
11955         Worklist.push_back(*UI);
11956       }
11957   }
11958 }
11959 
11960 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
11961 /// (aliasing node.)
11962 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11963   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11964 
11965   // Accumulate all the aliases to this node.
11966   GatherAllAliases(N, OldChain, Aliases);
11967 
11968   // If no operands then chain to entry token.
11969   if (Aliases.size() == 0)
11970     return DAG.getEntryNode();
11971 
11972   // If a single operand then chain to it.  We don't need to revisit it.
11973   if (Aliases.size() == 1)
11974     return Aliases[0];
11975 
11976   // Construct a custom tailored token factor.
11977   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11978 }
11979 
11980 /// This is the entry point for the file.
11981 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11982                            CodeGenOpt::Level OptLevel) {
11983   /// This is the main entry point to this class.
11984   DAGCombiner(*this, AA, OptLevel).Run(Level);
11985 }