[SDAG] When performing post-legalize DAG combining, run the legalizer
[oota-llvm.git] / lib / CodeGen / SelectionDAG / DAGCombiner.cpp
1 //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This pass combines dag nodes to form fewer, simpler DAG nodes.  It can be run
11 // both before and after the DAG is legalized.
12 //
13 // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
14 // primarily intended to handle simplification opportunities that are implicit
15 // in the LLVM IR and exposed by the various codegen lowering phases.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/ADT/SmallPtrSet.h"
21 #include "llvm/ADT/SetVector.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/Analysis/AliasAnalysis.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/DerivedTypes.h"
28 #include "llvm/IR/Function.h"
29 #include "llvm/IR/LLVMContext.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/ErrorHandling.h"
33 #include "llvm/Support/MathExtras.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/Target/TargetLowering.h"
36 #include "llvm/Target/TargetMachine.h"
37 #include "llvm/Target/TargetOptions.h"
38 #include "llvm/Target/TargetRegisterInfo.h"
39 #include "llvm/Target/TargetSubtargetInfo.h"
40 #include <algorithm>
41 using namespace llvm;
42
43 #define DEBUG_TYPE "dagcombine"
44
45 STATISTIC(NodesCombined   , "Number of dag nodes combined");
46 STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
47 STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
48 STATISTIC(OpsNarrowed     , "Number of load/op/store narrowed");
49 STATISTIC(LdStFP2Int      , "Number of fp load/store pairs transformed to int");
50 STATISTIC(SlicedLoads, "Number of load sliced");
51
52 namespace {
53   static cl::opt<bool>
54     CombinerAA("combiner-alias-analysis", cl::Hidden,
55                cl::desc("Enable DAG combiner alias-analysis heuristics"));
56
57   static cl::opt<bool>
58     CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
59                cl::desc("Enable DAG combiner's use of IR alias analysis"));
60
61   static cl::opt<bool>
62     UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
63                cl::desc("Enable DAG combiner's use of TBAA"));
64
65 #ifndef NDEBUG
66   static cl::opt<std::string>
67     CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
68                cl::desc("Only use DAG-combiner alias analysis in this"
69                         " function"));
70 #endif
71
72   /// Hidden option to stress test load slicing, i.e., when this option
73   /// is enabled, load slicing bypasses most of its profitability guards.
74   static cl::opt<bool>
75   StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
76                     cl::desc("Bypass the profitability model of load "
77                              "slicing"),
78                     cl::init(false));
79
80 //------------------------------ DAGCombiner ---------------------------------//
81
82   class DAGCombiner {
83     SelectionDAG &DAG;
84     const TargetLowering &TLI;
85     CombineLevel Level;
86     CodeGenOpt::Level OptLevel;
87     bool LegalOperations;
88     bool LegalTypes;
89     bool ForCodeSize;
90
91     /// \brief Worklist of all of the nodes that need to be simplified.
92     ///
93     /// This must behave as a stack -- new nodes to process are pushed onto the
94     /// back and when processing we pop off of the back.
95     ///
96     /// The worklist will not contain duplicates but may contain null entries
97     /// due to nodes being deleted from the underlying DAG.
98     SmallVector<SDNode *, 64> Worklist;
99
100     /// \brief Mapping from an SDNode to its position on the worklist.
101     ///
102     /// This is used to find and remove nodes from the worklist (by nulling
103     /// them) when they are deleted from the underlying DAG. It relies on
104     /// stable indices of nodes within the worklist.
105     DenseMap<SDNode *, unsigned> WorklistMap;
106
107     /// \brief Set of nodes which have been combined (at least once).
108     ///
109     /// This is used to allow us to reliably add any operands of a DAG node
110     /// which have not yet been combined to the worklist.
111     SmallPtrSet<SDNode *, 64> CombinedNodes;
112
113     // AA - Used for DAG load/store alias analysis.
114     AliasAnalysis &AA;
115
116     /// AddUsersToWorklist - When an instruction is simplified, add all users of
117     /// the instruction to the work lists because they might get more simplified
118     /// now.
119     ///
120     void AddUsersToWorklist(SDNode *N) {
121       for (SDNode *Node : N->uses())
122         AddToWorklist(Node);
123     }
124
125     /// visit - call the node-specific routine that knows how to fold each
126     /// particular type of node.
127     SDValue visit(SDNode *N);
128
129   public:
130     /// AddToWorklist - Add to the work list making sure its instance is at the
131     /// back (next to be processed.)
132     void AddToWorklist(SDNode *N) {
133       // Skip handle nodes as they can't usefully be combined and confuse the
134       // zero-use deletion strategy.
135       if (N->getOpcode() == ISD::HANDLENODE)
136         return;
137
138       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
139         Worklist.push_back(N);
140     }
141
142     /// removeFromWorklist - remove all instances of N from the worklist.
143     ///
144     void removeFromWorklist(SDNode *N) {
145       CombinedNodes.erase(N);
146
147       auto It = WorklistMap.find(N);
148       if (It == WorklistMap.end())
149         return; // Not in the worklist.
150
151       // Null out the entry rather than erasing it to avoid a linear operation.
152       Worklist[It->second] = nullptr;
153       WorklistMap.erase(It);
154     }
155
156     bool recursivelyDeleteUnusedNodes(SDNode *N);
157
158     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
159                       bool AddTo = true);
160
161     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
162       return CombineTo(N, &Res, 1, AddTo);
163     }
164
165     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
166                       bool AddTo = true) {
167       SDValue To[] = { Res0, Res1 };
168       return CombineTo(N, To, 2, AddTo);
169     }
170
171     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
172
173   private:
174
175     /// SimplifyDemandedBits - Check the specified integer node value to see if
176     /// it can be simplified or if things it uses can be simplified by bit
177     /// propagation.  If so, return true.
178     bool SimplifyDemandedBits(SDValue Op) {
179       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
180       APInt Demanded = APInt::getAllOnesValue(BitWidth);
181       return SimplifyDemandedBits(Op, Demanded);
182     }
183
184     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
185
186     bool CombineToPreIndexedLoadStore(SDNode *N);
187     bool CombineToPostIndexedLoadStore(SDNode *N);
188     bool SliceUpLoad(SDNode *N);
189
190     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
191     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
192     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
193     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
194     SDValue PromoteIntBinOp(SDValue Op);
195     SDValue PromoteIntShiftOp(SDValue Op);
196     SDValue PromoteExtend(SDValue Op);
197     bool PromoteLoad(SDValue Op);
198
199     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
200                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
201                          ISD::NodeType ExtType);
202
203     /// combine - call the node-specific routine that knows how to fold each
204     /// particular type of node. If that doesn't do anything, try the
205     /// target-specific DAG combines.
206     SDValue combine(SDNode *N);
207
208     // Visitation implementation - Implement dag node combining for different
209     // node types.  The semantics are as follows:
210     // Return Value:
211     //   SDValue.getNode() == 0 - No change was made
212     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
213     //   otherwise              - N should be replaced by the returned Operand.
214     //
215     SDValue visitTokenFactor(SDNode *N);
216     SDValue visitMERGE_VALUES(SDNode *N);
217     SDValue visitADD(SDNode *N);
218     SDValue visitSUB(SDNode *N);
219     SDValue visitADDC(SDNode *N);
220     SDValue visitSUBC(SDNode *N);
221     SDValue visitADDE(SDNode *N);
222     SDValue visitSUBE(SDNode *N);
223     SDValue visitMUL(SDNode *N);
224     SDValue visitSDIV(SDNode *N);
225     SDValue visitUDIV(SDNode *N);
226     SDValue visitSREM(SDNode *N);
227     SDValue visitUREM(SDNode *N);
228     SDValue visitMULHU(SDNode *N);
229     SDValue visitMULHS(SDNode *N);
230     SDValue visitSMUL_LOHI(SDNode *N);
231     SDValue visitUMUL_LOHI(SDNode *N);
232     SDValue visitSMULO(SDNode *N);
233     SDValue visitUMULO(SDNode *N);
234     SDValue visitSDIVREM(SDNode *N);
235     SDValue visitUDIVREM(SDNode *N);
236     SDValue visitAND(SDNode *N);
237     SDValue visitOR(SDNode *N);
238     SDValue visitXOR(SDNode *N);
239     SDValue SimplifyVBinOp(SDNode *N);
240     SDValue SimplifyVUnaryOp(SDNode *N);
241     SDValue visitSHL(SDNode *N);
242     SDValue visitSRA(SDNode *N);
243     SDValue visitSRL(SDNode *N);
244     SDValue visitRotate(SDNode *N);
245     SDValue visitCTLZ(SDNode *N);
246     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
247     SDValue visitCTTZ(SDNode *N);
248     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
249     SDValue visitCTPOP(SDNode *N);
250     SDValue visitSELECT(SDNode *N);
251     SDValue visitVSELECT(SDNode *N);
252     SDValue visitSELECT_CC(SDNode *N);
253     SDValue visitSETCC(SDNode *N);
254     SDValue visitSIGN_EXTEND(SDNode *N);
255     SDValue visitZERO_EXTEND(SDNode *N);
256     SDValue visitANY_EXTEND(SDNode *N);
257     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
258     SDValue visitTRUNCATE(SDNode *N);
259     SDValue visitBITCAST(SDNode *N);
260     SDValue visitBUILD_PAIR(SDNode *N);
261     SDValue visitFADD(SDNode *N);
262     SDValue visitFSUB(SDNode *N);
263     SDValue visitFMUL(SDNode *N);
264     SDValue visitFMA(SDNode *N);
265     SDValue visitFDIV(SDNode *N);
266     SDValue visitFREM(SDNode *N);
267     SDValue visitFCOPYSIGN(SDNode *N);
268     SDValue visitSINT_TO_FP(SDNode *N);
269     SDValue visitUINT_TO_FP(SDNode *N);
270     SDValue visitFP_TO_SINT(SDNode *N);
271     SDValue visitFP_TO_UINT(SDNode *N);
272     SDValue visitFP_ROUND(SDNode *N);
273     SDValue visitFP_ROUND_INREG(SDNode *N);
274     SDValue visitFP_EXTEND(SDNode *N);
275     SDValue visitFNEG(SDNode *N);
276     SDValue visitFABS(SDNode *N);
277     SDValue visitFCEIL(SDNode *N);
278     SDValue visitFTRUNC(SDNode *N);
279     SDValue visitFFLOOR(SDNode *N);
280     SDValue visitBRCOND(SDNode *N);
281     SDValue visitBR_CC(SDNode *N);
282     SDValue visitLOAD(SDNode *N);
283     SDValue visitSTORE(SDNode *N);
284     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
285     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
286     SDValue visitBUILD_VECTOR(SDNode *N);
287     SDValue visitCONCAT_VECTORS(SDNode *N);
288     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
289     SDValue visitVECTOR_SHUFFLE(SDNode *N);
290     SDValue visitINSERT_SUBVECTOR(SDNode *N);
291
292     SDValue XformToShuffleWithZero(SDNode *N);
293     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
294
295     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
296
297     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
298     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
299     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
300     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
301                              SDValue N3, ISD::CondCode CC,
302                              bool NotExtCompare = false);
303     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
304                           SDLoc DL, bool foldBooleans = true);
305
306     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
307                            SDValue &CC) const;
308     bool isOneUseSetCC(SDValue N) const;
309
310     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
311                                          unsigned HiOp);
312     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
313     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
314     SDValue BuildSDIV(SDNode *N);
315     SDValue BuildSDIVPow2(SDNode *N);
316     SDValue BuildUDIV(SDNode *N);
317     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
318                                bool DemandHighBits = true);
319     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
320     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
321                               SDValue InnerPos, SDValue InnerNeg,
322                               unsigned PosOpcode, unsigned NegOpcode,
323                               SDLoc DL);
324     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
325     SDValue ReduceLoadWidth(SDNode *N);
326     SDValue ReduceLoadOpStoreWidth(SDNode *N);
327     SDValue TransformFPLoadStorePair(SDNode *N);
328     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
329     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
330
331     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
332
333     /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
334     /// looking for aliasing nodes and adding them to the Aliases vector.
335     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
336                           SmallVectorImpl<SDValue> &Aliases);
337
338     /// isAlias - Return true if there is any possibility that the two addresses
339     /// overlap.
340     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
341
342     /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
343     /// looking for a better chain (aliasing node.)
344     SDValue FindBetterChain(SDNode *N, SDValue Chain);
345
346     /// Merge consecutive store operations into a wide store.
347     /// This optimization uses wide integers or vectors when possible.
348     /// \return True if some memory operations were changed.
349     bool MergeConsecutiveStores(StoreSDNode *N);
350
351     /// \brief Try to transform a truncation where C is a constant:
352     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
353     ///
354     /// \p N needs to be a truncation and its first operand an AND. Other
355     /// requirements are checked by the function (e.g. that trunc is
356     /// single-use) and if missed an empty SDValue is returned.
357     SDValue distributeTruncateThroughAnd(SDNode *N);
358
359   public:
360     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
361         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
362           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
363       AttributeSet FnAttrs =
364           DAG.getMachineFunction().getFunction()->getAttributes();
365       ForCodeSize =
366           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
367                                Attribute::OptimizeForSize) ||
368           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
369     }
370
371     /// Run - runs the dag combiner on all nodes in the work list
372     void Run(CombineLevel AtLevel);
373
374     SelectionDAG &getDAG() const { return DAG; }
375
376     /// getShiftAmountTy - Returns a type large enough to hold any valid
377     /// shift amount - before type legalization these can be huge.
378     EVT getShiftAmountTy(EVT LHSTy) {
379       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
380       if (LHSTy.isVector())
381         return LHSTy;
382       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
383                         : TLI.getPointerTy();
384     }
385
386     /// isTypeLegal - This method returns true if we are running before type
387     /// legalization or if the specified VT is legal.
388     bool isTypeLegal(const EVT &VT) {
389       if (!LegalTypes) return true;
390       return TLI.isTypeLegal(VT);
391     }
392
393     /// getSetCCResultType - Convenience wrapper around
394     /// TargetLowering::getSetCCResultType
395     EVT getSetCCResultType(EVT VT) const {
396       return TLI.getSetCCResultType(*DAG.getContext(), VT);
397     }
398   };
399 }
400
401
402 namespace {
403 /// WorklistRemover - This class is a DAGUpdateListener that removes any deleted
404 /// nodes from the worklist.
405 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
406   DAGCombiner &DC;
407 public:
408   explicit WorklistRemover(DAGCombiner &dc)
409     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
410
411   void NodeDeleted(SDNode *N, SDNode *E) override {
412     DC.removeFromWorklist(N);
413   }
414 };
415 }
416
417 //===----------------------------------------------------------------------===//
418 //  TargetLowering::DAGCombinerInfo implementation
419 //===----------------------------------------------------------------------===//
420
421 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
422   ((DAGCombiner*)DC)->AddToWorklist(N);
423 }
424
425 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
426   ((DAGCombiner*)DC)->removeFromWorklist(N);
427 }
428
429 SDValue TargetLowering::DAGCombinerInfo::
430 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
431   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
432 }
433
434 SDValue TargetLowering::DAGCombinerInfo::
435 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
436   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
437 }
438
439
440 SDValue TargetLowering::DAGCombinerInfo::
441 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
442   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
443 }
444
445 void TargetLowering::DAGCombinerInfo::
446 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
447   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
448 }
449
450 //===----------------------------------------------------------------------===//
451 // Helper Functions
452 //===----------------------------------------------------------------------===//
453
454 /// isNegatibleForFree - Return 1 if we can compute the negated form of the
455 /// specified expression for the same cost as the expression itself, or 2 if we
456 /// can compute the negated form more cheaply than the expression itself.
457 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
458                                const TargetLowering &TLI,
459                                const TargetOptions *Options,
460                                unsigned Depth = 0) {
461   // fneg is removable even if it has multiple uses.
462   if (Op.getOpcode() == ISD::FNEG) return 2;
463
464   // Don't allow anything with multiple uses.
465   if (!Op.hasOneUse()) return 0;
466
467   // Don't recurse exponentially.
468   if (Depth > 6) return 0;
469
470   switch (Op.getOpcode()) {
471   default: return false;
472   case ISD::ConstantFP:
473     // Don't invert constant FP values after legalize.  The negated constant
474     // isn't necessarily legal.
475     return LegalOperations ? 0 : 1;
476   case ISD::FADD:
477     // FIXME: determine better conditions for this xform.
478     if (!Options->UnsafeFPMath) return 0;
479
480     // After operation legalization, it might not be legal to create new FSUBs.
481     if (LegalOperations &&
482         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
483       return 0;
484
485     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
486     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
487                                     Options, Depth + 1))
488       return V;
489     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
490     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
491                               Depth + 1);
492   case ISD::FSUB:
493     // We can't turn -(A-B) into B-A when we honor signed zeros.
494     if (!Options->UnsafeFPMath) return 0;
495
496     // fold (fneg (fsub A, B)) -> (fsub B, A)
497     return 1;
498
499   case ISD::FMUL:
500   case ISD::FDIV:
501     if (Options->HonorSignDependentRoundingFPMath()) return 0;
502
503     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
504     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
505                                     Options, Depth + 1))
506       return V;
507
508     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
509                               Depth + 1);
510
511   case ISD::FP_EXTEND:
512   case ISD::FP_ROUND:
513   case ISD::FSIN:
514     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
515                               Depth + 1);
516   }
517 }
518
519 /// GetNegatedExpression - If isNegatibleForFree returns true, this function
520 /// returns the newly negated expression.
521 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
522                                     bool LegalOperations, unsigned Depth = 0) {
523   // fneg is removable even if it has multiple uses.
524   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
525
526   // Don't allow anything with multiple uses.
527   assert(Op.hasOneUse() && "Unknown reuse!");
528
529   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
530   switch (Op.getOpcode()) {
531   default: llvm_unreachable("Unknown code");
532   case ISD::ConstantFP: {
533     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
534     V.changeSign();
535     return DAG.getConstantFP(V, Op.getValueType());
536   }
537   case ISD::FADD:
538     // FIXME: determine better conditions for this xform.
539     assert(DAG.getTarget().Options.UnsafeFPMath);
540
541     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
542     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
543                            DAG.getTargetLoweringInfo(),
544                            &DAG.getTarget().Options, Depth+1))
545       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
546                          GetNegatedExpression(Op.getOperand(0), DAG,
547                                               LegalOperations, Depth+1),
548                          Op.getOperand(1));
549     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
550     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
551                        GetNegatedExpression(Op.getOperand(1), DAG,
552                                             LegalOperations, Depth+1),
553                        Op.getOperand(0));
554   case ISD::FSUB:
555     // We can't turn -(A-B) into B-A when we honor signed zeros.
556     assert(DAG.getTarget().Options.UnsafeFPMath);
557
558     // fold (fneg (fsub 0, B)) -> B
559     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
560       if (N0CFP->getValueAPF().isZero())
561         return Op.getOperand(1);
562
563     // fold (fneg (fsub A, B)) -> (fsub B, A)
564     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
565                        Op.getOperand(1), Op.getOperand(0));
566
567   case ISD::FMUL:
568   case ISD::FDIV:
569     assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
570
571     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
572     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
573                            DAG.getTargetLoweringInfo(),
574                            &DAG.getTarget().Options, Depth+1))
575       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
576                          GetNegatedExpression(Op.getOperand(0), DAG,
577                                               LegalOperations, Depth+1),
578                          Op.getOperand(1));
579
580     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
581     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
582                        Op.getOperand(0),
583                        GetNegatedExpression(Op.getOperand(1), DAG,
584                                             LegalOperations, Depth+1));
585
586   case ISD::FP_EXTEND:
587   case ISD::FSIN:
588     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
589                        GetNegatedExpression(Op.getOperand(0), DAG,
590                                             LegalOperations, Depth+1));
591   case ISD::FP_ROUND:
592       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
593                          GetNegatedExpression(Op.getOperand(0), DAG,
594                                               LegalOperations, Depth+1),
595                          Op.getOperand(1));
596   }
597 }
598
599 // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
600 // that selects between the target values used for true and false, making it
601 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
602 // the appropriate nodes based on the type of node we are checking. This
603 // simplifies life a bit for the callers.
604 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
605                                     SDValue &CC) const {
606   if (N.getOpcode() == ISD::SETCC) {
607     LHS = N.getOperand(0);
608     RHS = N.getOperand(1);
609     CC  = N.getOperand(2);
610     return true;
611   }
612
613   if (N.getOpcode() != ISD::SELECT_CC ||
614       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
615       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
616     return false;
617
618   LHS = N.getOperand(0);
619   RHS = N.getOperand(1);
620   CC  = N.getOperand(4);
621   return true;
622 }
623
624 // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
625 // one use.  If this is true, it allows the users to invert the operation for
626 // free when it is profitable to do so.
627 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
628   SDValue N0, N1, N2;
629   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
630     return true;
631   return false;
632 }
633
634 /// isConstantSplatVector - Returns true if N is a BUILD_VECTOR node whose
635 /// elements are all the same constant or undefined.
636 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
637   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
638   if (!C)
639     return false;
640
641   APInt SplatUndef;
642   unsigned SplatBitSize;
643   bool HasAnyUndefs;
644   EVT EltVT = N->getValueType(0).getVectorElementType();
645   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
646                              HasAnyUndefs) &&
647           EltVT.getSizeInBits() >= SplatBitSize);
648 }
649
650 // \brief Returns the SDNode if it is a constant BuildVector or constant.
651 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
652   if (isa<ConstantSDNode>(N))
653     return N.getNode();
654   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
655   if(BV && BV->isConstant())
656     return BV;
657   return nullptr;
658 }
659
660 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
661 // int.
662 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
663   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
664     return CN;
665
666   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
667     BitVector UndefElements;
668     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
669
670     // BuildVectors can truncate their operands. Ignore that case here.
671     // FIXME: We blindly ignore splats which include undef which is overly
672     // pessimistic.
673     if (CN && UndefElements.none() &&
674         CN->getValueType(0) == N.getValueType().getScalarType())
675       return CN;
676   }
677
678   return nullptr;
679 }
680
681 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
682                                     SDValue N0, SDValue N1) {
683   EVT VT = N0.getValueType();
684   if (N0.getOpcode() == Opc) {
685     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
686       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
687         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
688         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
689         if (!OpNode.getNode())
690           return SDValue();
691         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
692       }
693       if (N0.hasOneUse()) {
694         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
695         // use
696         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
697         if (!OpNode.getNode())
698           return SDValue();
699         AddToWorklist(OpNode.getNode());
700         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
701       }
702     }
703   }
704
705   if (N1.getOpcode() == Opc) {
706     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
707       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
708         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
709         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
710         if (!OpNode.getNode())
711           return SDValue();
712         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
713       }
714       if (N1.hasOneUse()) {
715         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
716         // use
717         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
718         if (!OpNode.getNode())
719           return SDValue();
720         AddToWorklist(OpNode.getNode());
721         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
722       }
723     }
724   }
725
726   return SDValue();
727 }
728
729 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
730                                bool AddTo) {
731   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
732   ++NodesCombined;
733   DEBUG(dbgs() << "\nReplacing.1 ";
734         N->dump(&DAG);
735         dbgs() << "\nWith: ";
736         To[0].getNode()->dump(&DAG);
737         dbgs() << " and " << NumTo-1 << " other values\n";
738         for (unsigned i = 0, e = NumTo; i != e; ++i)
739           assert((!To[i].getNode() ||
740                   N->getValueType(i) == To[i].getValueType()) &&
741                  "Cannot combine value to value of different type!"));
742   WorklistRemover DeadNodes(*this);
743   DAG.ReplaceAllUsesWith(N, To);
744   if (AddTo) {
745     // Push the new nodes and any users onto the worklist
746     for (unsigned i = 0, e = NumTo; i != e; ++i) {
747       if (To[i].getNode()) {
748         AddToWorklist(To[i].getNode());
749         AddUsersToWorklist(To[i].getNode());
750       }
751     }
752   }
753
754   // Finally, if the node is now dead, remove it from the graph.  The node
755   // may not be dead if the replacement process recursively simplified to
756   // something else needing this node.
757   if (N->use_empty()) {
758     // Nodes can be reintroduced into the worklist.  Make sure we do not
759     // process a node that has been replaced.
760     removeFromWorklist(N);
761
762     // Finally, since the node is now dead, remove it from the graph.
763     DAG.DeleteNode(N);
764   }
765   return SDValue(N, 0);
766 }
767
768 void DAGCombiner::
769 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
770   // Replace all uses.  If any nodes become isomorphic to other nodes and
771   // are deleted, make sure to remove them from our worklist.
772   WorklistRemover DeadNodes(*this);
773   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
774
775   // Push the new node and any (possibly new) users onto the worklist.
776   AddToWorklist(TLO.New.getNode());
777   AddUsersToWorklist(TLO.New.getNode());
778
779   // Finally, if the node is now dead, remove it from the graph.  The node
780   // may not be dead if the replacement process recursively simplified to
781   // something else needing this node.
782   if (TLO.Old.getNode()->use_empty()) {
783     removeFromWorklist(TLO.Old.getNode());
784
785     // If the operands of this node are only used by the node, they will now
786     // be dead.  Make sure to visit them first to delete dead nodes early.
787     for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
788       if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
789         AddToWorklist(TLO.Old.getNode()->getOperand(i).getNode());
790
791     DAG.DeleteNode(TLO.Old.getNode());
792   }
793 }
794
795 /// SimplifyDemandedBits - Check the specified integer node value to see if
796 /// it can be simplified or if things it uses can be simplified by bit
797 /// propagation.  If so, return true.
798 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
799   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
800   APInt KnownZero, KnownOne;
801   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
802     return false;
803
804   // Revisit the node.
805   AddToWorklist(Op.getNode());
806
807   // Replace the old value with the new one.
808   ++NodesCombined;
809   DEBUG(dbgs() << "\nReplacing.2 ";
810         TLO.Old.getNode()->dump(&DAG);
811         dbgs() << "\nWith: ";
812         TLO.New.getNode()->dump(&DAG);
813         dbgs() << '\n');
814
815   CommitTargetLoweringOpt(TLO);
816   return true;
817 }
818
819 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
820   SDLoc dl(Load);
821   EVT VT = Load->getValueType(0);
822   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
823
824   DEBUG(dbgs() << "\nReplacing.9 ";
825         Load->dump(&DAG);
826         dbgs() << "\nWith: ";
827         Trunc.getNode()->dump(&DAG);
828         dbgs() << '\n');
829   WorklistRemover DeadNodes(*this);
830   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
831   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
832   removeFromWorklist(Load);
833   DAG.DeleteNode(Load);
834   AddToWorklist(Trunc.getNode());
835 }
836
837 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
838   Replace = false;
839   SDLoc dl(Op);
840   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
841     EVT MemVT = LD->getMemoryVT();
842     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
843       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
844                                                   : ISD::EXTLOAD)
845       : LD->getExtensionType();
846     Replace = true;
847     return DAG.getExtLoad(ExtType, dl, PVT,
848                           LD->getChain(), LD->getBasePtr(),
849                           MemVT, LD->getMemOperand());
850   }
851
852   unsigned Opc = Op.getOpcode();
853   switch (Opc) {
854   default: break;
855   case ISD::AssertSext:
856     return DAG.getNode(ISD::AssertSext, dl, PVT,
857                        SExtPromoteOperand(Op.getOperand(0), PVT),
858                        Op.getOperand(1));
859   case ISD::AssertZext:
860     return DAG.getNode(ISD::AssertZext, dl, PVT,
861                        ZExtPromoteOperand(Op.getOperand(0), PVT),
862                        Op.getOperand(1));
863   case ISD::Constant: {
864     unsigned ExtOpc =
865       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
866     return DAG.getNode(ExtOpc, dl, PVT, Op);
867   }
868   }
869
870   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
871     return SDValue();
872   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
873 }
874
875 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
876   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
877     return SDValue();
878   EVT OldVT = Op.getValueType();
879   SDLoc dl(Op);
880   bool Replace = false;
881   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
882   if (!NewOp.getNode())
883     return SDValue();
884   AddToWorklist(NewOp.getNode());
885
886   if (Replace)
887     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
888   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
889                      DAG.getValueType(OldVT));
890 }
891
892 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
893   EVT OldVT = Op.getValueType();
894   SDLoc dl(Op);
895   bool Replace = false;
896   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
897   if (!NewOp.getNode())
898     return SDValue();
899   AddToWorklist(NewOp.getNode());
900
901   if (Replace)
902     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
903   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
904 }
905
906 /// PromoteIntBinOp - Promote the specified integer binary operation if the
907 /// target indicates it is beneficial. e.g. On x86, it's usually better to
908 /// promote i16 operations to i32 since i16 instructions are longer.
909 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
910   if (!LegalOperations)
911     return SDValue();
912
913   EVT VT = Op.getValueType();
914   if (VT.isVector() || !VT.isInteger())
915     return SDValue();
916
917   // If operation type is 'undesirable', e.g. i16 on x86, consider
918   // promoting it.
919   unsigned Opc = Op.getOpcode();
920   if (TLI.isTypeDesirableForOp(Opc, VT))
921     return SDValue();
922
923   EVT PVT = VT;
924   // Consult target whether it is a good idea to promote this operation and
925   // what's the right type to promote it to.
926   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
927     assert(PVT != VT && "Don't know what type to promote to!");
928
929     bool Replace0 = false;
930     SDValue N0 = Op.getOperand(0);
931     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
932     if (!NN0.getNode())
933       return SDValue();
934
935     bool Replace1 = false;
936     SDValue N1 = Op.getOperand(1);
937     SDValue NN1;
938     if (N0 == N1)
939       NN1 = NN0;
940     else {
941       NN1 = PromoteOperand(N1, PVT, Replace1);
942       if (!NN1.getNode())
943         return SDValue();
944     }
945
946     AddToWorklist(NN0.getNode());
947     if (NN1.getNode())
948       AddToWorklist(NN1.getNode());
949
950     if (Replace0)
951       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
952     if (Replace1)
953       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
954
955     DEBUG(dbgs() << "\nPromoting ";
956           Op.getNode()->dump(&DAG));
957     SDLoc dl(Op);
958     return DAG.getNode(ISD::TRUNCATE, dl, VT,
959                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
960   }
961   return SDValue();
962 }
963
964 /// PromoteIntShiftOp - Promote the specified integer shift operation if the
965 /// target indicates it is beneficial. e.g. On x86, it's usually better to
966 /// promote i16 operations to i32 since i16 instructions are longer.
967 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
968   if (!LegalOperations)
969     return SDValue();
970
971   EVT VT = Op.getValueType();
972   if (VT.isVector() || !VT.isInteger())
973     return SDValue();
974
975   // If operation type is 'undesirable', e.g. i16 on x86, consider
976   // promoting it.
977   unsigned Opc = Op.getOpcode();
978   if (TLI.isTypeDesirableForOp(Opc, VT))
979     return SDValue();
980
981   EVT PVT = VT;
982   // Consult target whether it is a good idea to promote this operation and
983   // what's the right type to promote it to.
984   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
985     assert(PVT != VT && "Don't know what type to promote to!");
986
987     bool Replace = false;
988     SDValue N0 = Op.getOperand(0);
989     if (Opc == ISD::SRA)
990       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
991     else if (Opc == ISD::SRL)
992       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
993     else
994       N0 = PromoteOperand(N0, PVT, Replace);
995     if (!N0.getNode())
996       return SDValue();
997
998     AddToWorklist(N0.getNode());
999     if (Replace)
1000       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1001
1002     DEBUG(dbgs() << "\nPromoting ";
1003           Op.getNode()->dump(&DAG));
1004     SDLoc dl(Op);
1005     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1006                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1007   }
1008   return SDValue();
1009 }
1010
1011 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1012   if (!LegalOperations)
1013     return SDValue();
1014
1015   EVT VT = Op.getValueType();
1016   if (VT.isVector() || !VT.isInteger())
1017     return SDValue();
1018
1019   // If operation type is 'undesirable', e.g. i16 on x86, consider
1020   // promoting it.
1021   unsigned Opc = Op.getOpcode();
1022   if (TLI.isTypeDesirableForOp(Opc, VT))
1023     return SDValue();
1024
1025   EVT PVT = VT;
1026   // Consult target whether it is a good idea to promote this operation and
1027   // what's the right type to promote it to.
1028   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1029     assert(PVT != VT && "Don't know what type to promote to!");
1030     // fold (aext (aext x)) -> (aext x)
1031     // fold (aext (zext x)) -> (zext x)
1032     // fold (aext (sext x)) -> (sext x)
1033     DEBUG(dbgs() << "\nPromoting ";
1034           Op.getNode()->dump(&DAG));
1035     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1036   }
1037   return SDValue();
1038 }
1039
1040 bool DAGCombiner::PromoteLoad(SDValue Op) {
1041   if (!LegalOperations)
1042     return false;
1043
1044   EVT VT = Op.getValueType();
1045   if (VT.isVector() || !VT.isInteger())
1046     return false;
1047
1048   // If operation type is 'undesirable', e.g. i16 on x86, consider
1049   // promoting it.
1050   unsigned Opc = Op.getOpcode();
1051   if (TLI.isTypeDesirableForOp(Opc, VT))
1052     return false;
1053
1054   EVT PVT = VT;
1055   // Consult target whether it is a good idea to promote this operation and
1056   // what's the right type to promote it to.
1057   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1058     assert(PVT != VT && "Don't know what type to promote to!");
1059
1060     SDLoc dl(Op);
1061     SDNode *N = Op.getNode();
1062     LoadSDNode *LD = cast<LoadSDNode>(N);
1063     EVT MemVT = LD->getMemoryVT();
1064     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1065       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1066                                                   : ISD::EXTLOAD)
1067       : LD->getExtensionType();
1068     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1069                                    LD->getChain(), LD->getBasePtr(),
1070                                    MemVT, LD->getMemOperand());
1071     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1072
1073     DEBUG(dbgs() << "\nPromoting ";
1074           N->dump(&DAG);
1075           dbgs() << "\nTo: ";
1076           Result.getNode()->dump(&DAG);
1077           dbgs() << '\n');
1078     WorklistRemover DeadNodes(*this);
1079     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1080     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1081     removeFromWorklist(N);
1082     DAG.DeleteNode(N);
1083     AddToWorklist(Result.getNode());
1084     return true;
1085   }
1086   return false;
1087 }
1088
1089 /// \brief Recursively delete a node which has no uses and any operands for
1090 /// which it is the only use.
1091 ///
1092 /// Note that this both deletes the nodes and removes them from the worklist.
1093 /// It also adds any nodes who have had a user deleted to the worklist as they
1094 /// may now have only one use and subject to other combines.
1095 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1096   if (!N->use_empty())
1097     return false;
1098
1099   SmallSetVector<SDNode *, 16> Nodes;
1100   Nodes.insert(N);
1101   do {
1102     N = Nodes.pop_back_val();
1103     if (!N)
1104       continue;
1105
1106     if (N->use_empty()) {
1107       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1108         Nodes.insert(N->getOperand(i).getNode());
1109
1110       removeFromWorklist(N);
1111       DAG.DeleteNode(N);
1112     } else {
1113       AddToWorklist(N);
1114     }
1115   } while (!Nodes.empty());
1116   return true;
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 //  Main DAG Combiner implementation
1121 //===----------------------------------------------------------------------===//
1122
1123 void DAGCombiner::Run(CombineLevel AtLevel) {
1124   // set the instance variables, so that the various visit routines may use it.
1125   Level = AtLevel;
1126   LegalOperations = Level >= AfterLegalizeVectorOps;
1127   LegalTypes = Level >= AfterLegalizeTypes;
1128
1129   // Add all the dag nodes to the worklist.
1130   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1131        E = DAG.allnodes_end(); I != E; ++I)
1132     AddToWorklist(I);
1133
1134   // Create a dummy node (which is not added to allnodes), that adds a reference
1135   // to the root node, preventing it from being deleted, and tracking any
1136   // changes of the root.
1137   HandleSDNode Dummy(DAG.getRoot());
1138
1139   // while the worklist isn't empty, find a node and
1140   // try and combine it.
1141   while (!WorklistMap.empty()) {
1142     SDNode *N;
1143     // The Worklist holds the SDNodes in order, but it may contain null entries.
1144     do {
1145       N = Worklist.pop_back_val();
1146     } while (!N);
1147
1148     bool GoodWorklistEntry = WorklistMap.erase(N);
1149     (void)GoodWorklistEntry;
1150     assert(GoodWorklistEntry &&
1151            "Found a worklist entry without a corresponding map entry!");
1152
1153     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1154     // N is deleted from the DAG, since they too may now be dead or may have a
1155     // reduced number of uses, allowing other xforms.
1156     if (recursivelyDeleteUnusedNodes(N))
1157       continue;
1158
1159     DEBUG(dbgs() << "\nCombining: ";
1160           N->dump(&DAG));
1161
1162     // Add any operands of the new node which have not yet been combined to the
1163     // worklist as well. Because the worklist uniques things already, this
1164     // won't repeatedly process the same operand.
1165     CombinedNodes.insert(N);
1166     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1167       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1168         AddToWorklist(N->getOperand(i).getNode());
1169
1170     WorklistRemover DeadNodes(*this);
1171
1172     // If this combine is running after legalizing the DAG, re-legalize any
1173     // nodes pulled off the worklist.
1174     if (Level == AfterLegalizeDAG) {
1175       SmallSetVector<SDNode *, 16> UpdatedNodes;
1176       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1177
1178       for (SDNode *LN : UpdatedNodes) {
1179         AddToWorklist(LN);
1180         AddUsersToWorklist(LN);
1181       }
1182       if (!NIsValid)
1183         continue;
1184     }
1185
1186     SDValue RV = combine(N);
1187
1188     if (!RV.getNode())
1189       continue;
1190
1191     ++NodesCombined;
1192
1193     // If we get back the same node we passed in, rather than a new node or
1194     // zero, we know that the node must have defined multiple values and
1195     // CombineTo was used.  Since CombineTo takes care of the worklist
1196     // mechanics for us, we have no work to do in this case.
1197     if (RV.getNode() == N)
1198       continue;
1199
1200     assert(N->getOpcode() != ISD::DELETED_NODE &&
1201            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1202            "Node was deleted but visit returned new node!");
1203
1204     DEBUG(dbgs() << " ... into: ";
1205           RV.getNode()->dump(&DAG));
1206
1207     // Transfer debug value.
1208     DAG.TransferDbgValues(SDValue(N, 0), RV);
1209     if (N->getNumValues() == RV.getNode()->getNumValues())
1210       DAG.ReplaceAllUsesWith(N, RV.getNode());
1211     else {
1212       assert(N->getValueType(0) == RV.getValueType() &&
1213              N->getNumValues() == 1 && "Type mismatch");
1214       SDValue OpV = RV;
1215       DAG.ReplaceAllUsesWith(N, &OpV);
1216     }
1217
1218     // Push the new node and any users onto the worklist
1219     AddToWorklist(RV.getNode());
1220     AddUsersToWorklist(RV.getNode());
1221
1222     // Finally, if the node is now dead, remove it from the graph.  The node
1223     // may not be dead if the replacement process recursively simplified to
1224     // something else needing this node. This will also take care of adding any
1225     // operands which have lost a user to the worklist.
1226     recursivelyDeleteUnusedNodes(N);
1227   }
1228
1229   // If the root changed (e.g. it was a dead load, update the root).
1230   DAG.setRoot(Dummy.getValue());
1231   DAG.RemoveDeadNodes();
1232 }
1233
1234 SDValue DAGCombiner::visit(SDNode *N) {
1235   switch (N->getOpcode()) {
1236   default: break;
1237   case ISD::TokenFactor:        return visitTokenFactor(N);
1238   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1239   case ISD::ADD:                return visitADD(N);
1240   case ISD::SUB:                return visitSUB(N);
1241   case ISD::ADDC:               return visitADDC(N);
1242   case ISD::SUBC:               return visitSUBC(N);
1243   case ISD::ADDE:               return visitADDE(N);
1244   case ISD::SUBE:               return visitSUBE(N);
1245   case ISD::MUL:                return visitMUL(N);
1246   case ISD::SDIV:               return visitSDIV(N);
1247   case ISD::UDIV:               return visitUDIV(N);
1248   case ISD::SREM:               return visitSREM(N);
1249   case ISD::UREM:               return visitUREM(N);
1250   case ISD::MULHU:              return visitMULHU(N);
1251   case ISD::MULHS:              return visitMULHS(N);
1252   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1253   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1254   case ISD::SMULO:              return visitSMULO(N);
1255   case ISD::UMULO:              return visitUMULO(N);
1256   case ISD::SDIVREM:            return visitSDIVREM(N);
1257   case ISD::UDIVREM:            return visitUDIVREM(N);
1258   case ISD::AND:                return visitAND(N);
1259   case ISD::OR:                 return visitOR(N);
1260   case ISD::XOR:                return visitXOR(N);
1261   case ISD::SHL:                return visitSHL(N);
1262   case ISD::SRA:                return visitSRA(N);
1263   case ISD::SRL:                return visitSRL(N);
1264   case ISD::ROTR:
1265   case ISD::ROTL:               return visitRotate(N);
1266   case ISD::CTLZ:               return visitCTLZ(N);
1267   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1268   case ISD::CTTZ:               return visitCTTZ(N);
1269   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1270   case ISD::CTPOP:              return visitCTPOP(N);
1271   case ISD::SELECT:             return visitSELECT(N);
1272   case ISD::VSELECT:            return visitVSELECT(N);
1273   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1274   case ISD::SETCC:              return visitSETCC(N);
1275   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1276   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1277   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1278   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1279   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1280   case ISD::BITCAST:            return visitBITCAST(N);
1281   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1282   case ISD::FADD:               return visitFADD(N);
1283   case ISD::FSUB:               return visitFSUB(N);
1284   case ISD::FMUL:               return visitFMUL(N);
1285   case ISD::FMA:                return visitFMA(N);
1286   case ISD::FDIV:               return visitFDIV(N);
1287   case ISD::FREM:               return visitFREM(N);
1288   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1289   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1290   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1291   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1292   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1293   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1294   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1295   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1296   case ISD::FNEG:               return visitFNEG(N);
1297   case ISD::FABS:               return visitFABS(N);
1298   case ISD::FFLOOR:             return visitFFLOOR(N);
1299   case ISD::FCEIL:              return visitFCEIL(N);
1300   case ISD::FTRUNC:             return visitFTRUNC(N);
1301   case ISD::BRCOND:             return visitBRCOND(N);
1302   case ISD::BR_CC:              return visitBR_CC(N);
1303   case ISD::LOAD:               return visitLOAD(N);
1304   case ISD::STORE:              return visitSTORE(N);
1305   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1306   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1307   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1308   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1309   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1310   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1311   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1312   }
1313   return SDValue();
1314 }
1315
1316 SDValue DAGCombiner::combine(SDNode *N) {
1317   SDValue RV = visit(N);
1318
1319   // If nothing happened, try a target-specific DAG combine.
1320   if (!RV.getNode()) {
1321     assert(N->getOpcode() != ISD::DELETED_NODE &&
1322            "Node was deleted but visit returned NULL!");
1323
1324     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1325         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1326
1327       // Expose the DAG combiner to the target combiner impls.
1328       TargetLowering::DAGCombinerInfo
1329         DagCombineInfo(DAG, Level, false, this);
1330
1331       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1332     }
1333   }
1334
1335   // If nothing happened still, try promoting the operation.
1336   if (!RV.getNode()) {
1337     switch (N->getOpcode()) {
1338     default: break;
1339     case ISD::ADD:
1340     case ISD::SUB:
1341     case ISD::MUL:
1342     case ISD::AND:
1343     case ISD::OR:
1344     case ISD::XOR:
1345       RV = PromoteIntBinOp(SDValue(N, 0));
1346       break;
1347     case ISD::SHL:
1348     case ISD::SRA:
1349     case ISD::SRL:
1350       RV = PromoteIntShiftOp(SDValue(N, 0));
1351       break;
1352     case ISD::SIGN_EXTEND:
1353     case ISD::ZERO_EXTEND:
1354     case ISD::ANY_EXTEND:
1355       RV = PromoteExtend(SDValue(N, 0));
1356       break;
1357     case ISD::LOAD:
1358       if (PromoteLoad(SDValue(N, 0)))
1359         RV = SDValue(N, 0);
1360       break;
1361     }
1362   }
1363
1364   // If N is a commutative binary node, try commuting it to enable more
1365   // sdisel CSE.
1366   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1367       N->getNumValues() == 1) {
1368     SDValue N0 = N->getOperand(0);
1369     SDValue N1 = N->getOperand(1);
1370
1371     // Constant operands are canonicalized to RHS.
1372     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1373       SDValue Ops[] = {N1, N0};
1374       SDNode *CSENode;
1375       if (const BinaryWithFlagsSDNode *BinNode =
1376               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1377         CSENode = DAG.getNodeIfExists(
1378             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1379             BinNode->hasNoSignedWrap(), BinNode->isExact());
1380       } else {
1381         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1382       }
1383       if (CSENode)
1384         return SDValue(CSENode, 0);
1385     }
1386   }
1387
1388   return RV;
1389 }
1390
1391 /// getInputChainForNode - Given a node, return its input chain if it has one,
1392 /// otherwise return a null sd operand.
1393 static SDValue getInputChainForNode(SDNode *N) {
1394   if (unsigned NumOps = N->getNumOperands()) {
1395     if (N->getOperand(0).getValueType() == MVT::Other)
1396       return N->getOperand(0);
1397     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1398       return N->getOperand(NumOps-1);
1399     for (unsigned i = 1; i < NumOps-1; ++i)
1400       if (N->getOperand(i).getValueType() == MVT::Other)
1401         return N->getOperand(i);
1402   }
1403   return SDValue();
1404 }
1405
1406 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1407   // If N has two operands, where one has an input chain equal to the other,
1408   // the 'other' chain is redundant.
1409   if (N->getNumOperands() == 2) {
1410     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1411       return N->getOperand(0);
1412     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1413       return N->getOperand(1);
1414   }
1415
1416   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1417   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1418   SmallPtrSet<SDNode*, 16> SeenOps;
1419   bool Changed = false;             // If we should replace this token factor.
1420
1421   // Start out with this token factor.
1422   TFs.push_back(N);
1423
1424   // Iterate through token factors.  The TFs grows when new token factors are
1425   // encountered.
1426   for (unsigned i = 0; i < TFs.size(); ++i) {
1427     SDNode *TF = TFs[i];
1428
1429     // Check each of the operands.
1430     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1431       SDValue Op = TF->getOperand(i);
1432
1433       switch (Op.getOpcode()) {
1434       case ISD::EntryToken:
1435         // Entry tokens don't need to be added to the list. They are
1436         // rededundant.
1437         Changed = true;
1438         break;
1439
1440       case ISD::TokenFactor:
1441         if (Op.hasOneUse() &&
1442             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1443           // Queue up for processing.
1444           TFs.push_back(Op.getNode());
1445           // Clean up in case the token factor is removed.
1446           AddToWorklist(Op.getNode());
1447           Changed = true;
1448           break;
1449         }
1450         // Fall thru
1451
1452       default:
1453         // Only add if it isn't already in the list.
1454         if (SeenOps.insert(Op.getNode()))
1455           Ops.push_back(Op);
1456         else
1457           Changed = true;
1458         break;
1459       }
1460     }
1461   }
1462
1463   SDValue Result;
1464
1465   // If we've change things around then replace token factor.
1466   if (Changed) {
1467     if (Ops.empty()) {
1468       // The entry token is the only possible outcome.
1469       Result = DAG.getEntryNode();
1470     } else {
1471       // New and improved token factor.
1472       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1473     }
1474
1475     // Don't add users to work list.
1476     return CombineTo(N, Result, false);
1477   }
1478
1479   return Result;
1480 }
1481
1482 /// MERGE_VALUES can always be eliminated.
1483 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1484   WorklistRemover DeadNodes(*this);
1485   // Replacing results may cause a different MERGE_VALUES to suddenly
1486   // be CSE'd with N, and carry its uses with it. Iterate until no
1487   // uses remain, to ensure that the node can be safely deleted.
1488   // First add the users of this node to the work list so that they
1489   // can be tried again once they have new operands.
1490   AddUsersToWorklist(N);
1491   do {
1492     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1493       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1494   } while (!N->use_empty());
1495   removeFromWorklist(N);
1496   DAG.DeleteNode(N);
1497   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1498 }
1499
1500 static
1501 SDValue combineShlAddConstant(SDLoc DL, SDValue N0, SDValue N1,
1502                               SelectionDAG &DAG) {
1503   EVT VT = N0.getValueType();
1504   SDValue N00 = N0.getOperand(0);
1505   SDValue N01 = N0.getOperand(1);
1506   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
1507
1508   if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
1509       isa<ConstantSDNode>(N00.getOperand(1))) {
1510     // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1511     N0 = DAG.getNode(ISD::ADD, SDLoc(N0), VT,
1512                      DAG.getNode(ISD::SHL, SDLoc(N00), VT,
1513                                  N00.getOperand(0), N01),
1514                      DAG.getNode(ISD::SHL, SDLoc(N01), VT,
1515                                  N00.getOperand(1), N01));
1516     return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
1517   }
1518
1519   return SDValue();
1520 }
1521
1522 SDValue DAGCombiner::visitADD(SDNode *N) {
1523   SDValue N0 = N->getOperand(0);
1524   SDValue N1 = N->getOperand(1);
1525   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1526   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1527   EVT VT = N0.getValueType();
1528
1529   // fold vector ops
1530   if (VT.isVector()) {
1531     SDValue FoldedVOp = SimplifyVBinOp(N);
1532     if (FoldedVOp.getNode()) return FoldedVOp;
1533
1534     // fold (add x, 0) -> x, vector edition
1535     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1536       return N0;
1537     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1538       return N1;
1539   }
1540
1541   // fold (add x, undef) -> undef
1542   if (N0.getOpcode() == ISD::UNDEF)
1543     return N0;
1544   if (N1.getOpcode() == ISD::UNDEF)
1545     return N1;
1546   // fold (add c1, c2) -> c1+c2
1547   if (N0C && N1C)
1548     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1549   // canonicalize constant to RHS
1550   if (N0C && !N1C)
1551     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1552   // fold (add x, 0) -> x
1553   if (N1C && N1C->isNullValue())
1554     return N0;
1555   // fold (add Sym, c) -> Sym+c
1556   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1557     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1558         GA->getOpcode() == ISD::GlobalAddress)
1559       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1560                                   GA->getOffset() +
1561                                     (uint64_t)N1C->getSExtValue());
1562   // fold ((c1-A)+c2) -> (c1+c2)-A
1563   if (N1C && N0.getOpcode() == ISD::SUB)
1564     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1565       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1566                          DAG.getConstant(N1C->getAPIntValue()+
1567                                          N0C->getAPIntValue(), VT),
1568                          N0.getOperand(1));
1569   // reassociate add
1570   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1571   if (RADD.getNode())
1572     return RADD;
1573   // fold ((0-A) + B) -> B-A
1574   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1575       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1576     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1577   // fold (A + (0-B)) -> A-B
1578   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1579       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1580     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1581   // fold (A+(B-A)) -> B
1582   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1583     return N1.getOperand(0);
1584   // fold ((B-A)+A) -> B
1585   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1586     return N0.getOperand(0);
1587   // fold (A+(B-(A+C))) to (B-C)
1588   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1589       N0 == N1.getOperand(1).getOperand(0))
1590     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1591                        N1.getOperand(1).getOperand(1));
1592   // fold (A+(B-(C+A))) to (B-C)
1593   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1594       N0 == N1.getOperand(1).getOperand(1))
1595     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1596                        N1.getOperand(1).getOperand(0));
1597   // fold (A+((B-A)+or-C)) to (B+or-C)
1598   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1599       N1.getOperand(0).getOpcode() == ISD::SUB &&
1600       N0 == N1.getOperand(0).getOperand(1))
1601     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1602                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1603
1604   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1605   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1606     SDValue N00 = N0.getOperand(0);
1607     SDValue N01 = N0.getOperand(1);
1608     SDValue N10 = N1.getOperand(0);
1609     SDValue N11 = N1.getOperand(1);
1610
1611     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1612       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1613                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1614                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1615   }
1616
1617   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1618     return SDValue(N, 0);
1619
1620   // fold (a+b) -> (a|b) iff a and b share no bits.
1621   if (VT.isInteger() && !VT.isVector()) {
1622     APInt LHSZero, LHSOne;
1623     APInt RHSZero, RHSOne;
1624     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1625
1626     if (LHSZero.getBoolValue()) {
1627       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1628
1629       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1630       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1631       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1632         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1633           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1634       }
1635     }
1636   }
1637
1638   // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
1639   if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
1640     SDValue Result = combineShlAddConstant(SDLoc(N), N0, N1, DAG);
1641     if (Result.getNode()) return Result;
1642   }
1643   if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
1644     SDValue Result = combineShlAddConstant(SDLoc(N), N1, N0, DAG);
1645     if (Result.getNode()) return Result;
1646   }
1647
1648   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1649   if (N1.getOpcode() == ISD::SHL &&
1650       N1.getOperand(0).getOpcode() == ISD::SUB)
1651     if (ConstantSDNode *C =
1652           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1653       if (C->getAPIntValue() == 0)
1654         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1655                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1656                                        N1.getOperand(0).getOperand(1),
1657                                        N1.getOperand(1)));
1658   if (N0.getOpcode() == ISD::SHL &&
1659       N0.getOperand(0).getOpcode() == ISD::SUB)
1660     if (ConstantSDNode *C =
1661           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1662       if (C->getAPIntValue() == 0)
1663         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1664                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1665                                        N0.getOperand(0).getOperand(1),
1666                                        N0.getOperand(1)));
1667
1668   if (N1.getOpcode() == ISD::AND) {
1669     SDValue AndOp0 = N1.getOperand(0);
1670     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1671     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1672     unsigned DestBits = VT.getScalarType().getSizeInBits();
1673
1674     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1675     // and similar xforms where the inner op is either ~0 or 0.
1676     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1677       SDLoc DL(N);
1678       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1679     }
1680   }
1681
1682   // add (sext i1), X -> sub X, (zext i1)
1683   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1684       N0.getOperand(0).getValueType() == MVT::i1 &&
1685       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1686     SDLoc DL(N);
1687     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1688     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1689   }
1690
1691   return SDValue();
1692 }
1693
1694 SDValue DAGCombiner::visitADDC(SDNode *N) {
1695   SDValue N0 = N->getOperand(0);
1696   SDValue N1 = N->getOperand(1);
1697   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1698   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1699   EVT VT = N0.getValueType();
1700
1701   // If the flag result is dead, turn this into an ADD.
1702   if (!N->hasAnyUseOfValue(1))
1703     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1704                      DAG.getNode(ISD::CARRY_FALSE,
1705                                  SDLoc(N), MVT::Glue));
1706
1707   // canonicalize constant to RHS.
1708   if (N0C && !N1C)
1709     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1710
1711   // fold (addc x, 0) -> x + no carry out
1712   if (N1C && N1C->isNullValue())
1713     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1714                                         SDLoc(N), MVT::Glue));
1715
1716   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1717   APInt LHSZero, LHSOne;
1718   APInt RHSZero, RHSOne;
1719   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1720
1721   if (LHSZero.getBoolValue()) {
1722     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1723
1724     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1725     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1726     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1727       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1728                        DAG.getNode(ISD::CARRY_FALSE,
1729                                    SDLoc(N), MVT::Glue));
1730   }
1731
1732   return SDValue();
1733 }
1734
1735 SDValue DAGCombiner::visitADDE(SDNode *N) {
1736   SDValue N0 = N->getOperand(0);
1737   SDValue N1 = N->getOperand(1);
1738   SDValue CarryIn = N->getOperand(2);
1739   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1740   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1741
1742   // canonicalize constant to RHS
1743   if (N0C && !N1C)
1744     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1745                        N1, N0, CarryIn);
1746
1747   // fold (adde x, y, false) -> (addc x, y)
1748   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1749     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1750
1751   return SDValue();
1752 }
1753
1754 // Since it may not be valid to emit a fold to zero for vector initializers
1755 // check if we can before folding.
1756 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1757                              SelectionDAG &DAG,
1758                              bool LegalOperations, bool LegalTypes) {
1759   if (!VT.isVector())
1760     return DAG.getConstant(0, VT);
1761   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1762     return DAG.getConstant(0, VT);
1763   return SDValue();
1764 }
1765
1766 SDValue DAGCombiner::visitSUB(SDNode *N) {
1767   SDValue N0 = N->getOperand(0);
1768   SDValue N1 = N->getOperand(1);
1769   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1770   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1771   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1772     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1773   EVT VT = N0.getValueType();
1774
1775   // fold vector ops
1776   if (VT.isVector()) {
1777     SDValue FoldedVOp = SimplifyVBinOp(N);
1778     if (FoldedVOp.getNode()) return FoldedVOp;
1779
1780     // fold (sub x, 0) -> x, vector edition
1781     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1782       return N0;
1783   }
1784
1785   // fold (sub x, x) -> 0
1786   // FIXME: Refactor this and xor and other similar operations together.
1787   if (N0 == N1)
1788     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1789   // fold (sub c1, c2) -> c1-c2
1790   if (N0C && N1C)
1791     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1792   // fold (sub x, c) -> (add x, -c)
1793   if (N1C)
1794     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1795                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1796   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1797   if (N0C && N0C->isAllOnesValue())
1798     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1799   // fold A-(A-B) -> B
1800   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1801     return N1.getOperand(1);
1802   // fold (A+B)-A -> B
1803   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1804     return N0.getOperand(1);
1805   // fold (A+B)-B -> A
1806   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1807     return N0.getOperand(0);
1808   // fold C2-(A+C1) -> (C2-C1)-A
1809   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1810     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1811                                    VT);
1812     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1813                        N1.getOperand(0));
1814   }
1815   // fold ((A+(B+or-C))-B) -> A+or-C
1816   if (N0.getOpcode() == ISD::ADD &&
1817       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1818        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1819       N0.getOperand(1).getOperand(0) == N1)
1820     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1821                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1822   // fold ((A+(C+B))-B) -> A+C
1823   if (N0.getOpcode() == ISD::ADD &&
1824       N0.getOperand(1).getOpcode() == ISD::ADD &&
1825       N0.getOperand(1).getOperand(1) == N1)
1826     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1827                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1828   // fold ((A-(B-C))-C) -> A-B
1829   if (N0.getOpcode() == ISD::SUB &&
1830       N0.getOperand(1).getOpcode() == ISD::SUB &&
1831       N0.getOperand(1).getOperand(1) == N1)
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1833                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1834
1835   // If either operand of a sub is undef, the result is undef
1836   if (N0.getOpcode() == ISD::UNDEF)
1837     return N0;
1838   if (N1.getOpcode() == ISD::UNDEF)
1839     return N1;
1840
1841   // If the relocation model supports it, consider symbol offsets.
1842   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1843     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1844       // fold (sub Sym, c) -> Sym-c
1845       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1846         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1847                                     GA->getOffset() -
1848                                       (uint64_t)N1C->getSExtValue());
1849       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1850       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1851         if (GA->getGlobal() == GB->getGlobal())
1852           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1853                                  VT);
1854     }
1855
1856   return SDValue();
1857 }
1858
1859 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1860   SDValue N0 = N->getOperand(0);
1861   SDValue N1 = N->getOperand(1);
1862   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1863   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1864   EVT VT = N0.getValueType();
1865
1866   // If the flag result is dead, turn this into an SUB.
1867   if (!N->hasAnyUseOfValue(1))
1868     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1869                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1870                                  MVT::Glue));
1871
1872   // fold (subc x, x) -> 0 + no borrow
1873   if (N0 == N1)
1874     return CombineTo(N, DAG.getConstant(0, VT),
1875                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1876                                  MVT::Glue));
1877
1878   // fold (subc x, 0) -> x + no borrow
1879   if (N1C && N1C->isNullValue())
1880     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1881                                         MVT::Glue));
1882
1883   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1884   if (N0C && N0C->isAllOnesValue())
1885     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1886                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1887                                  MVT::Glue));
1888
1889   return SDValue();
1890 }
1891
1892 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1893   SDValue N0 = N->getOperand(0);
1894   SDValue N1 = N->getOperand(1);
1895   SDValue CarryIn = N->getOperand(2);
1896
1897   // fold (sube x, y, false) -> (subc x, y)
1898   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1899     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1900
1901   return SDValue();
1902 }
1903
1904 SDValue DAGCombiner::visitMUL(SDNode *N) {
1905   SDValue N0 = N->getOperand(0);
1906   SDValue N1 = N->getOperand(1);
1907   EVT VT = N0.getValueType();
1908
1909   // fold (mul x, undef) -> 0
1910   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1911     return DAG.getConstant(0, VT);
1912
1913   bool N0IsConst = false;
1914   bool N1IsConst = false;
1915   APInt ConstValue0, ConstValue1;
1916   // fold vector ops
1917   if (VT.isVector()) {
1918     SDValue FoldedVOp = SimplifyVBinOp(N);
1919     if (FoldedVOp.getNode()) return FoldedVOp;
1920
1921     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1922     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1923   } else {
1924     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1925     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1926                             : APInt();
1927     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1928     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1929                             : APInt();
1930   }
1931
1932   // fold (mul c1, c2) -> c1*c2
1933   if (N0IsConst && N1IsConst)
1934     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1935
1936   // canonicalize constant to RHS
1937   if (N0IsConst && !N1IsConst)
1938     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1939   // fold (mul x, 0) -> 0
1940   if (N1IsConst && ConstValue1 == 0)
1941     return N1;
1942   // We require a splat of the entire scalar bit width for non-contiguous
1943   // bit patterns.
1944   bool IsFullSplat =
1945     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1946   // fold (mul x, 1) -> x
1947   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1948     return N0;
1949   // fold (mul x, -1) -> 0-x
1950   if (N1IsConst && ConstValue1.isAllOnesValue())
1951     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1952                        DAG.getConstant(0, VT), N0);
1953   // fold (mul x, (1 << c)) -> x << c
1954   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1955     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1956                        DAG.getConstant(ConstValue1.logBase2(),
1957                                        getShiftAmountTy(N0.getValueType())));
1958   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1959   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1960     unsigned Log2Val = (-ConstValue1).logBase2();
1961     // FIXME: If the input is something that is easily negated (e.g. a
1962     // single-use add), we should put the negate there.
1963     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1964                        DAG.getConstant(0, VT),
1965                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1966                             DAG.getConstant(Log2Val,
1967                                       getShiftAmountTy(N0.getValueType()))));
1968   }
1969
1970   APInt Val;
1971   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
1972   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
1973       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1974                      isa<ConstantSDNode>(N0.getOperand(1)))) {
1975     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
1976                              N1, N0.getOperand(1));
1977     AddToWorklist(C3.getNode());
1978     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
1979                        N0.getOperand(0), C3);
1980   }
1981
1982   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
1983   // use.
1984   {
1985     SDValue Sh(nullptr,0), Y(nullptr,0);
1986     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
1987     if (N0.getOpcode() == ISD::SHL &&
1988         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
1989                        isa<ConstantSDNode>(N0.getOperand(1))) &&
1990         N0.getNode()->hasOneUse()) {
1991       Sh = N0; Y = N1;
1992     } else if (N1.getOpcode() == ISD::SHL &&
1993                isa<ConstantSDNode>(N1.getOperand(1)) &&
1994                N1.getNode()->hasOneUse()) {
1995       Sh = N1; Y = N0;
1996     }
1997
1998     if (Sh.getNode()) {
1999       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2000                                 Sh.getOperand(0), Y);
2001       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2002                          Mul, Sh.getOperand(1));
2003     }
2004   }
2005
2006   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2007   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2008       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                      isa<ConstantSDNode>(N0.getOperand(1))))
2010     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2011                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2012                                    N0.getOperand(0), N1),
2013                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2014                                    N0.getOperand(1), N1));
2015
2016   // reassociate mul
2017   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2018   if (RMUL.getNode())
2019     return RMUL;
2020
2021   return SDValue();
2022 }
2023
2024 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2025   SDValue N0 = N->getOperand(0);
2026   SDValue N1 = N->getOperand(1);
2027   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2028   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2029   EVT VT = N->getValueType(0);
2030
2031   // fold vector ops
2032   if (VT.isVector()) {
2033     SDValue FoldedVOp = SimplifyVBinOp(N);
2034     if (FoldedVOp.getNode()) return FoldedVOp;
2035   }
2036
2037   // fold (sdiv c1, c2) -> c1/c2
2038   if (N0C && N1C && !N1C->isNullValue())
2039     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2040   // fold (sdiv X, 1) -> X
2041   if (N1C && N1C->getAPIntValue() == 1LL)
2042     return N0;
2043   // fold (sdiv X, -1) -> 0-X
2044   if (N1C && N1C->isAllOnesValue())
2045     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2046                        DAG.getConstant(0, VT), N0);
2047   // If we know the sign bits of both operands are zero, strength reduce to a
2048   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2049   if (!VT.isVector()) {
2050     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2051       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2052                          N0, N1);
2053   }
2054
2055   // fold (sdiv X, pow2) -> simple ops after legalize
2056   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2057                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2058     // If dividing by powers of two is cheap, then don't perform the following
2059     // fold.
2060     if (TLI.isPow2DivCheap())
2061       return SDValue();
2062
2063     // Target-specific implementation of sdiv x, pow2.
2064     SDValue Res = BuildSDIVPow2(N);
2065     if (Res.getNode())
2066       return Res;
2067
2068     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2069
2070     // Splat the sign bit into the register
2071     SDValue SGN =
2072         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2073                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2074                                     getShiftAmountTy(N0.getValueType())));
2075     AddToWorklist(SGN.getNode());
2076
2077     // Add (N0 < 0) ? abs2 - 1 : 0;
2078     SDValue SRL =
2079         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2080                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2081                                     getShiftAmountTy(SGN.getValueType())));
2082     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2083     AddToWorklist(SRL.getNode());
2084     AddToWorklist(ADD.getNode());    // Divide by pow2
2085     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2086                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2087
2088     // If we're dividing by a positive value, we're done.  Otherwise, we must
2089     // negate the result.
2090     if (N1C->getAPIntValue().isNonNegative())
2091       return SRA;
2092
2093     AddToWorklist(SRA.getNode());
2094     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2095   }
2096
2097   // if integer divide is expensive and we satisfy the requirements, emit an
2098   // alternate sequence.
2099   if (N1C && !TLI.isIntDivCheap()) {
2100     SDValue Op = BuildSDIV(N);
2101     if (Op.getNode()) return Op;
2102   }
2103
2104   // undef / X -> 0
2105   if (N0.getOpcode() == ISD::UNDEF)
2106     return DAG.getConstant(0, VT);
2107   // X / undef -> undef
2108   if (N1.getOpcode() == ISD::UNDEF)
2109     return N1;
2110
2111   return SDValue();
2112 }
2113
2114 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2115   SDValue N0 = N->getOperand(0);
2116   SDValue N1 = N->getOperand(1);
2117   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2118   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2119   EVT VT = N->getValueType(0);
2120
2121   // fold vector ops
2122   if (VT.isVector()) {
2123     SDValue FoldedVOp = SimplifyVBinOp(N);
2124     if (FoldedVOp.getNode()) return FoldedVOp;
2125   }
2126
2127   // fold (udiv c1, c2) -> c1/c2
2128   if (N0C && N1C && !N1C->isNullValue())
2129     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2130   // fold (udiv x, (1 << c)) -> x >>u c
2131   if (N1C && N1C->getAPIntValue().isPowerOf2())
2132     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2133                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2134                                        getShiftAmountTy(N0.getValueType())));
2135   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2136   if (N1.getOpcode() == ISD::SHL) {
2137     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2138       if (SHC->getAPIntValue().isPowerOf2()) {
2139         EVT ADDVT = N1.getOperand(1).getValueType();
2140         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2141                                   N1.getOperand(1),
2142                                   DAG.getConstant(SHC->getAPIntValue()
2143                                                                   .logBase2(),
2144                                                   ADDVT));
2145         AddToWorklist(Add.getNode());
2146         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2147       }
2148     }
2149   }
2150   // fold (udiv x, c) -> alternate
2151   if (N1C && !TLI.isIntDivCheap()) {
2152     SDValue Op = BuildUDIV(N);
2153     if (Op.getNode()) return Op;
2154   }
2155
2156   // undef / X -> 0
2157   if (N0.getOpcode() == ISD::UNDEF)
2158     return DAG.getConstant(0, VT);
2159   // X / undef -> undef
2160   if (N1.getOpcode() == ISD::UNDEF)
2161     return N1;
2162
2163   return SDValue();
2164 }
2165
2166 SDValue DAGCombiner::visitSREM(SDNode *N) {
2167   SDValue N0 = N->getOperand(0);
2168   SDValue N1 = N->getOperand(1);
2169   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2170   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2171   EVT VT = N->getValueType(0);
2172
2173   // fold (srem c1, c2) -> c1%c2
2174   if (N0C && N1C && !N1C->isNullValue())
2175     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2176   // If we know the sign bits of both operands are zero, strength reduce to a
2177   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2178   if (!VT.isVector()) {
2179     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2180       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2181   }
2182
2183   // If X/C can be simplified by the division-by-constant logic, lower
2184   // X%C to the equivalent of X-X/C*C.
2185   if (N1C && !N1C->isNullValue()) {
2186     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2187     AddToWorklist(Div.getNode());
2188     SDValue OptimizedDiv = combine(Div.getNode());
2189     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2190       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2191                                 OptimizedDiv, N1);
2192       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2193       AddToWorklist(Mul.getNode());
2194       return Sub;
2195     }
2196   }
2197
2198   // undef % X -> 0
2199   if (N0.getOpcode() == ISD::UNDEF)
2200     return DAG.getConstant(0, VT);
2201   // X % undef -> undef
2202   if (N1.getOpcode() == ISD::UNDEF)
2203     return N1;
2204
2205   return SDValue();
2206 }
2207
2208 SDValue DAGCombiner::visitUREM(SDNode *N) {
2209   SDValue N0 = N->getOperand(0);
2210   SDValue N1 = N->getOperand(1);
2211   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2212   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2213   EVT VT = N->getValueType(0);
2214
2215   // fold (urem c1, c2) -> c1%c2
2216   if (N0C && N1C && !N1C->isNullValue())
2217     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2218   // fold (urem x, pow2) -> (and x, pow2-1)
2219   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2220     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2221                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2222   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2223   if (N1.getOpcode() == ISD::SHL) {
2224     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2225       if (SHC->getAPIntValue().isPowerOf2()) {
2226         SDValue Add =
2227           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2228                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2229                                  VT));
2230         AddToWorklist(Add.getNode());
2231         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2232       }
2233     }
2234   }
2235
2236   // If X/C can be simplified by the division-by-constant logic, lower
2237   // X%C to the equivalent of X-X/C*C.
2238   if (N1C && !N1C->isNullValue()) {
2239     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2240     AddToWorklist(Div.getNode());
2241     SDValue OptimizedDiv = combine(Div.getNode());
2242     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2243       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2244                                 OptimizedDiv, N1);
2245       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2246       AddToWorklist(Mul.getNode());
2247       return Sub;
2248     }
2249   }
2250
2251   // undef % X -> 0
2252   if (N0.getOpcode() == ISD::UNDEF)
2253     return DAG.getConstant(0, VT);
2254   // X % undef -> undef
2255   if (N1.getOpcode() == ISD::UNDEF)
2256     return N1;
2257
2258   return SDValue();
2259 }
2260
2261 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2262   SDValue N0 = N->getOperand(0);
2263   SDValue N1 = N->getOperand(1);
2264   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2265   EVT VT = N->getValueType(0);
2266   SDLoc DL(N);
2267
2268   // fold (mulhs x, 0) -> 0
2269   if (N1C && N1C->isNullValue())
2270     return N1;
2271   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2272   if (N1C && N1C->getAPIntValue() == 1)
2273     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2274                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2275                                        getShiftAmountTy(N0.getValueType())));
2276   // fold (mulhs x, undef) -> 0
2277   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2278     return DAG.getConstant(0, VT);
2279
2280   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2281   // plus a shift.
2282   if (VT.isSimple() && !VT.isVector()) {
2283     MVT Simple = VT.getSimpleVT();
2284     unsigned SimpleSize = Simple.getSizeInBits();
2285     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2286     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2287       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2288       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2289       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2290       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2291             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2292       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2293     }
2294   }
2295
2296   return SDValue();
2297 }
2298
2299 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2300   SDValue N0 = N->getOperand(0);
2301   SDValue N1 = N->getOperand(1);
2302   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2303   EVT VT = N->getValueType(0);
2304   SDLoc DL(N);
2305
2306   // fold (mulhu x, 0) -> 0
2307   if (N1C && N1C->isNullValue())
2308     return N1;
2309   // fold (mulhu x, 1) -> 0
2310   if (N1C && N1C->getAPIntValue() == 1)
2311     return DAG.getConstant(0, N0.getValueType());
2312   // fold (mulhu x, undef) -> 0
2313   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2314     return DAG.getConstant(0, VT);
2315
2316   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2317   // plus a shift.
2318   if (VT.isSimple() && !VT.isVector()) {
2319     MVT Simple = VT.getSimpleVT();
2320     unsigned SimpleSize = Simple.getSizeInBits();
2321     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2322     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2323       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2324       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2325       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2326       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2327             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2328       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2329     }
2330   }
2331
2332   return SDValue();
2333 }
2334
2335 /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
2336 /// compute two values. LoOp and HiOp give the opcodes for the two computations
2337 /// that are being performed. Return true if a simplification was made.
2338 ///
2339 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2340                                                 unsigned HiOp) {
2341   // If the high half is not needed, just compute the low half.
2342   bool HiExists = N->hasAnyUseOfValue(1);
2343   if (!HiExists &&
2344       (!LegalOperations ||
2345        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2346     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2347                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2348     return CombineTo(N, Res, Res);
2349   }
2350
2351   // If the low half is not needed, just compute the high half.
2352   bool LoExists = N->hasAnyUseOfValue(0);
2353   if (!LoExists &&
2354       (!LegalOperations ||
2355        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2356     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2357                               ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2358     return CombineTo(N, Res, Res);
2359   }
2360
2361   // If both halves are used, return as it is.
2362   if (LoExists && HiExists)
2363     return SDValue();
2364
2365   // If the two computed results can be simplified separately, separate them.
2366   if (LoExists) {
2367     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0),
2368                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2369     AddToWorklist(Lo.getNode());
2370     SDValue LoOpt = combine(Lo.getNode());
2371     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2372         (!LegalOperations ||
2373          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2374       return CombineTo(N, LoOpt, LoOpt);
2375   }
2376
2377   if (HiExists) {
2378     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1),
2379                              ArrayRef<SDUse>(N->op_begin(), N->op_end()));
2380     AddToWorklist(Hi.getNode());
2381     SDValue HiOpt = combine(Hi.getNode());
2382     if (HiOpt.getNode() && HiOpt != Hi &&
2383         (!LegalOperations ||
2384          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2385       return CombineTo(N, HiOpt, HiOpt);
2386   }
2387
2388   return SDValue();
2389 }
2390
2391 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2392   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2393   if (Res.getNode()) return Res;
2394
2395   EVT VT = N->getValueType(0);
2396   SDLoc DL(N);
2397
2398   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2399   // plus a shift.
2400   if (VT.isSimple() && !VT.isVector()) {
2401     MVT Simple = VT.getSimpleVT();
2402     unsigned SimpleSize = Simple.getSizeInBits();
2403     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2404     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2405       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2406       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2407       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2408       // Compute the high part as N1.
2409       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2410             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2411       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2412       // Compute the low part as N0.
2413       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2414       return CombineTo(N, Lo, Hi);
2415     }
2416   }
2417
2418   return SDValue();
2419 }
2420
2421 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2422   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2423   if (Res.getNode()) return Res;
2424
2425   EVT VT = N->getValueType(0);
2426   SDLoc DL(N);
2427
2428   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2429   // plus a shift.
2430   if (VT.isSimple() && !VT.isVector()) {
2431     MVT Simple = VT.getSimpleVT();
2432     unsigned SimpleSize = Simple.getSizeInBits();
2433     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2436       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2437       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438       // Compute the high part as N1.
2439       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2440             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2441       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442       // Compute the low part as N0.
2443       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444       return CombineTo(N, Lo, Hi);
2445     }
2446   }
2447
2448   return SDValue();
2449 }
2450
2451 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2452   // (smulo x, 2) -> (saddo x, x)
2453   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2454     if (C2->getAPIntValue() == 2)
2455       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2456                          N->getOperand(0), N->getOperand(0));
2457
2458   return SDValue();
2459 }
2460
2461 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2462   // (umulo x, 2) -> (uaddo x, x)
2463   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2464     if (C2->getAPIntValue() == 2)
2465       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2466                          N->getOperand(0), N->getOperand(0));
2467
2468   return SDValue();
2469 }
2470
2471 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2472   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2473   if (Res.getNode()) return Res;
2474
2475   return SDValue();
2476 }
2477
2478 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2479   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2480   if (Res.getNode()) return Res;
2481
2482   return SDValue();
2483 }
2484
2485 /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
2486 /// two operands of the same opcode, try to simplify it.
2487 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2488   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2489   EVT VT = N0.getValueType();
2490   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2491
2492   // Bail early if none of these transforms apply.
2493   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2494
2495   // For each of OP in AND/OR/XOR:
2496   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2497   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2498   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2499   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2500   //
2501   // do not sink logical op inside of a vector extend, since it may combine
2502   // into a vsetcc.
2503   EVT Op0VT = N0.getOperand(0).getValueType();
2504   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2505        N0.getOpcode() == ISD::SIGN_EXTEND ||
2506        // Avoid infinite looping with PromoteIntBinOp.
2507        (N0.getOpcode() == ISD::ANY_EXTEND &&
2508         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2509        (N0.getOpcode() == ISD::TRUNCATE &&
2510         (!TLI.isZExtFree(VT, Op0VT) ||
2511          !TLI.isTruncateFree(Op0VT, VT)) &&
2512         TLI.isTypeLegal(Op0VT))) &&
2513       !VT.isVector() &&
2514       Op0VT == N1.getOperand(0).getValueType() &&
2515       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2516     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2517                                  N0.getOperand(0).getValueType(),
2518                                  N0.getOperand(0), N1.getOperand(0));
2519     AddToWorklist(ORNode.getNode());
2520     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2521   }
2522
2523   // For each of OP in SHL/SRL/SRA/AND...
2524   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2525   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2526   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2527   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2528        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2529       N0.getOperand(1) == N1.getOperand(1)) {
2530     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2531                                  N0.getOperand(0).getValueType(),
2532                                  N0.getOperand(0), N1.getOperand(0));
2533     AddToWorklist(ORNode.getNode());
2534     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2535                        ORNode, N0.getOperand(1));
2536   }
2537
2538   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2539   // Only perform this optimization after type legalization and before
2540   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2541   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2542   // we don't want to undo this promotion.
2543   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2544   // on scalars.
2545   if ((N0.getOpcode() == ISD::BITCAST ||
2546        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2547       Level == AfterLegalizeTypes) {
2548     SDValue In0 = N0.getOperand(0);
2549     SDValue In1 = N1.getOperand(0);
2550     EVT In0Ty = In0.getValueType();
2551     EVT In1Ty = In1.getValueType();
2552     SDLoc DL(N);
2553     // If both incoming values are integers, and the original types are the
2554     // same.
2555     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2556       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2557       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2558       AddToWorklist(Op.getNode());
2559       return BC;
2560     }
2561   }
2562
2563   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2564   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2565   // If both shuffles use the same mask, and both shuffle within a single
2566   // vector, then it is worthwhile to move the swizzle after the operation.
2567   // The type-legalizer generates this pattern when loading illegal
2568   // vector types from memory. In many cases this allows additional shuffle
2569   // optimizations.
2570   // There are other cases where moving the shuffle after the xor/and/or
2571   // is profitable even if shuffles don't perform a swizzle.
2572   // If both shuffles use the same mask, and both shuffles have the same first
2573   // or second operand, then it might still be profitable to move the shuffle
2574   // after the xor/and/or operation.
2575   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2576     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2577     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2578
2579     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2580            "Inputs to shuffles are not the same type");
2581
2582     // Check that both shuffles use the same mask. The masks are known to be of
2583     // the same length because the result vector type is the same.
2584     // Check also that shuffles have only one use to avoid introducing extra
2585     // instructions.
2586     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2587         SVN0->getMask().equals(SVN1->getMask())) {
2588       SDValue ShOp = N0->getOperand(1);
2589
2590       // Don't try to fold this node if it requires introducing a
2591       // build vector of all zeros that might be illegal at this stage.
2592       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2593         if (!LegalTypes)
2594           ShOp = DAG.getConstant(0, VT);
2595         else
2596           ShOp = SDValue();
2597       }
2598
2599       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2600       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2601       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2602       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2603         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2604                                       N0->getOperand(0), N1->getOperand(0));
2605         AddToWorklist(NewNode.getNode());
2606         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2607                                     &SVN0->getMask()[0]);
2608       }
2609
2610       // Don't try to fold this node if it requires introducing a
2611       // build vector of all zeros that might be illegal at this stage.
2612       ShOp = N0->getOperand(0);
2613       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2614         if (!LegalTypes)
2615           ShOp = DAG.getConstant(0, VT);
2616         else
2617           ShOp = SDValue();
2618       }
2619
2620       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2621       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2622       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2623       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2624         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2625                                       N0->getOperand(1), N1->getOperand(1));
2626         AddToWorklist(NewNode.getNode());
2627         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2628                                     &SVN0->getMask()[0]);
2629       }
2630     }
2631   }
2632
2633   return SDValue();
2634 }
2635
2636 SDValue DAGCombiner::visitAND(SDNode *N) {
2637   SDValue N0 = N->getOperand(0);
2638   SDValue N1 = N->getOperand(1);
2639   SDValue LL, LR, RL, RR, CC0, CC1;
2640   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2641   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2642   EVT VT = N1.getValueType();
2643   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2644
2645   // fold vector ops
2646   if (VT.isVector()) {
2647     SDValue FoldedVOp = SimplifyVBinOp(N);
2648     if (FoldedVOp.getNode()) return FoldedVOp;
2649
2650     // fold (and x, 0) -> 0, vector edition
2651     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2652       return N0;
2653     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2654       return N1;
2655
2656     // fold (and x, -1) -> x, vector edition
2657     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2658       return N1;
2659     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2660       return N0;
2661   }
2662
2663   // fold (and x, undef) -> 0
2664   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2665     return DAG.getConstant(0, VT);
2666   // fold (and c1, c2) -> c1&c2
2667   if (N0C && N1C)
2668     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2669   // canonicalize constant to RHS
2670   if (N0C && !N1C)
2671     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2672   // fold (and x, -1) -> x
2673   if (N1C && N1C->isAllOnesValue())
2674     return N0;
2675   // if (and x, c) is known to be zero, return 0
2676   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2677                                    APInt::getAllOnesValue(BitWidth)))
2678     return DAG.getConstant(0, VT);
2679   // reassociate and
2680   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2681   if (RAND.getNode())
2682     return RAND;
2683   // fold (and (or x, C), D) -> D if (C & D) == D
2684   if (N1C && N0.getOpcode() == ISD::OR)
2685     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2686       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2687         return N1;
2688   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2689   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2690     SDValue N0Op0 = N0.getOperand(0);
2691     APInt Mask = ~N1C->getAPIntValue();
2692     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2693     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2694       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2695                                  N0.getValueType(), N0Op0);
2696
2697       // Replace uses of the AND with uses of the Zero extend node.
2698       CombineTo(N, Zext);
2699
2700       // We actually want to replace all uses of the any_extend with the
2701       // zero_extend, to avoid duplicating things.  This will later cause this
2702       // AND to be folded.
2703       CombineTo(N0.getNode(), Zext);
2704       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2705     }
2706   }
2707   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2708   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2709   // already be zero by virtue of the width of the base type of the load.
2710   //
2711   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2712   // more cases.
2713   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2714        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2715       N0.getOpcode() == ISD::LOAD) {
2716     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2717                                          N0 : N0.getOperand(0) );
2718
2719     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2720     // This can be a pure constant or a vector splat, in which case we treat the
2721     // vector as a scalar and use the splat value.
2722     APInt Constant = APInt::getNullValue(1);
2723     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2724       Constant = C->getAPIntValue();
2725     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2726       APInt SplatValue, SplatUndef;
2727       unsigned SplatBitSize;
2728       bool HasAnyUndefs;
2729       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2730                                              SplatBitSize, HasAnyUndefs);
2731       if (IsSplat) {
2732         // Undef bits can contribute to a possible optimisation if set, so
2733         // set them.
2734         SplatValue |= SplatUndef;
2735
2736         // The splat value may be something like "0x00FFFFFF", which means 0 for
2737         // the first vector value and FF for the rest, repeating. We need a mask
2738         // that will apply equally to all members of the vector, so AND all the
2739         // lanes of the constant together.
2740         EVT VT = Vector->getValueType(0);
2741         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2742
2743         // If the splat value has been compressed to a bitlength lower
2744         // than the size of the vector lane, we need to re-expand it to
2745         // the lane size.
2746         if (BitWidth > SplatBitSize)
2747           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2748                SplatBitSize < BitWidth;
2749                SplatBitSize = SplatBitSize * 2)
2750             SplatValue |= SplatValue.shl(SplatBitSize);
2751
2752         Constant = APInt::getAllOnesValue(BitWidth);
2753         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2754           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2755       }
2756     }
2757
2758     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2759     // actually legal and isn't going to get expanded, else this is a false
2760     // optimisation.
2761     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2762                                                     Load->getMemoryVT());
2763
2764     // Resize the constant to the same size as the original memory access before
2765     // extension. If it is still the AllOnesValue then this AND is completely
2766     // unneeded.
2767     Constant =
2768       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2769
2770     bool B;
2771     switch (Load->getExtensionType()) {
2772     default: B = false; break;
2773     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2774     case ISD::ZEXTLOAD:
2775     case ISD::NON_EXTLOAD: B = true; break;
2776     }
2777
2778     if (B && Constant.isAllOnesValue()) {
2779       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2780       // preserve semantics once we get rid of the AND.
2781       SDValue NewLoad(Load, 0);
2782       if (Load->getExtensionType() == ISD::EXTLOAD) {
2783         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2784                               Load->getValueType(0), SDLoc(Load),
2785                               Load->getChain(), Load->getBasePtr(),
2786                               Load->getOffset(), Load->getMemoryVT(),
2787                               Load->getMemOperand());
2788         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2789         if (Load->getNumValues() == 3) {
2790           // PRE/POST_INC loads have 3 values.
2791           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2792                            NewLoad.getValue(2) };
2793           CombineTo(Load, To, 3, true);
2794         } else {
2795           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2796         }
2797       }
2798
2799       // Fold the AND away, taking care not to fold to the old load node if we
2800       // replaced it.
2801       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2802
2803       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2804     }
2805   }
2806   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2807   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2808     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2809     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2810
2811     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2812         LL.getValueType().isInteger()) {
2813       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2814       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2815         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2816                                      LR.getValueType(), LL, RL);
2817         AddToWorklist(ORNode.getNode());
2818         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2819       }
2820       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2821       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2822         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2823                                       LR.getValueType(), LL, RL);
2824         AddToWorklist(ANDNode.getNode());
2825         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2826       }
2827       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2828       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2829         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2830                                      LR.getValueType(), LL, RL);
2831         AddToWorklist(ORNode.getNode());
2832         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2833       }
2834     }
2835     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2836     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2837         Op0 == Op1 && LL.getValueType().isInteger() &&
2838       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2839                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2840                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2841                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2842       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2843                                     LL, DAG.getConstant(1, LL.getValueType()));
2844       AddToWorklist(ADDNode.getNode());
2845       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2846                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2847     }
2848     // canonicalize equivalent to ll == rl
2849     if (LL == RR && LR == RL) {
2850       Op1 = ISD::getSetCCSwappedOperands(Op1);
2851       std::swap(RL, RR);
2852     }
2853     if (LL == RL && LR == RR) {
2854       bool isInteger = LL.getValueType().isInteger();
2855       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2856       if (Result != ISD::SETCC_INVALID &&
2857           (!LegalOperations ||
2858            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2859             TLI.isOperationLegal(ISD::SETCC,
2860                             getSetCCResultType(N0.getSimpleValueType())))))
2861         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2862                             LL, LR, Result);
2863     }
2864   }
2865
2866   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2867   if (N0.getOpcode() == N1.getOpcode()) {
2868     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2869     if (Tmp.getNode()) return Tmp;
2870   }
2871
2872   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2873   // fold (and (sra)) -> (and (srl)) when possible.
2874   if (!VT.isVector() &&
2875       SimplifyDemandedBits(SDValue(N, 0)))
2876     return SDValue(N, 0);
2877
2878   // fold (zext_inreg (extload x)) -> (zextload x)
2879   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2880     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2881     EVT MemVT = LN0->getMemoryVT();
2882     // If we zero all the possible extended bits, then we can turn this into
2883     // a zextload if we are running before legalize or the operation is legal.
2884     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2885     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2886                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2887         ((!LegalOperations && !LN0->isVolatile()) ||
2888          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2889       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2890                                        LN0->getChain(), LN0->getBasePtr(),
2891                                        MemVT, LN0->getMemOperand());
2892       AddToWorklist(N);
2893       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2894       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2895     }
2896   }
2897   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2898   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2899       N0.hasOneUse()) {
2900     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2901     EVT MemVT = LN0->getMemoryVT();
2902     // If we zero all the possible extended bits, then we can turn this into
2903     // a zextload if we are running before legalize or the operation is legal.
2904     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2905     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2906                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2907         ((!LegalOperations && !LN0->isVolatile()) ||
2908          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2909       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2910                                        LN0->getChain(), LN0->getBasePtr(),
2911                                        MemVT, LN0->getMemOperand());
2912       AddToWorklist(N);
2913       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2914       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2915     }
2916   }
2917
2918   // fold (and (load x), 255) -> (zextload x, i8)
2919   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2920   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2921   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2922               (N0.getOpcode() == ISD::ANY_EXTEND &&
2923                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2924     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2925     LoadSDNode *LN0 = HasAnyExt
2926       ? cast<LoadSDNode>(N0.getOperand(0))
2927       : cast<LoadSDNode>(N0);
2928     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2929         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2930       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2931       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2932         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2933         EVT LoadedVT = LN0->getMemoryVT();
2934
2935         if (ExtVT == LoadedVT &&
2936             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2937           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2938
2939           SDValue NewLoad =
2940             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2941                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2942                            LN0->getMemOperand());
2943           AddToWorklist(N);
2944           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2945           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2946         }
2947
2948         // Do not change the width of a volatile load.
2949         // Do not generate loads of non-round integer types since these can
2950         // be expensive (and would be wrong if the type is not byte sized).
2951         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2952             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2953           EVT PtrType = LN0->getOperand(1).getValueType();
2954
2955           unsigned Alignment = LN0->getAlignment();
2956           SDValue NewPtr = LN0->getBasePtr();
2957
2958           // For big endian targets, we need to add an offset to the pointer
2959           // to load the correct bytes.  For little endian systems, we merely
2960           // need to read fewer bytes from the same pointer.
2961           if (TLI.isBigEndian()) {
2962             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2963             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2964             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2965             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
2966                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
2967             Alignment = MinAlign(Alignment, PtrOff);
2968           }
2969
2970           AddToWorklist(NewPtr.getNode());
2971
2972           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2973           SDValue Load =
2974             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2975                            LN0->getChain(), NewPtr,
2976                            LN0->getPointerInfo(),
2977                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
2978                            Alignment, LN0->getAAInfo());
2979           AddToWorklist(N);
2980           CombineTo(LN0, Load, Load.getValue(1));
2981           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2982         }
2983       }
2984     }
2985   }
2986
2987   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
2988       VT.getSizeInBits() <= 64) {
2989     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
2990       APInt ADDC = ADDI->getAPIntValue();
2991       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
2992         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
2993         // immediate for an add, but it is legal if its top c2 bits are set,
2994         // transform the ADD so the immediate doesn't need to be materialized
2995         // in a register.
2996         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
2997           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
2998                                              SRLI->getZExtValue());
2999           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3000             ADDC |= Mask;
3001             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3002               SDValue NewAdd =
3003                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3004                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3005               CombineTo(N0.getNode(), NewAdd);
3006               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3007             }
3008           }
3009         }
3010       }
3011     }
3012   }
3013
3014   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3015   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3016     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3017                                        N0.getOperand(1), false);
3018     if (BSwap.getNode())
3019       return BSwap;
3020   }
3021
3022   return SDValue();
3023 }
3024
3025 /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
3026 ///
3027 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3028                                         bool DemandHighBits) {
3029   if (!LegalOperations)
3030     return SDValue();
3031
3032   EVT VT = N->getValueType(0);
3033   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3034     return SDValue();
3035   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3036     return SDValue();
3037
3038   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3039   bool LookPassAnd0 = false;
3040   bool LookPassAnd1 = false;
3041   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3042       std::swap(N0, N1);
3043   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3044       std::swap(N0, N1);
3045   if (N0.getOpcode() == ISD::AND) {
3046     if (!N0.getNode()->hasOneUse())
3047       return SDValue();
3048     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3049     if (!N01C || N01C->getZExtValue() != 0xFF00)
3050       return SDValue();
3051     N0 = N0.getOperand(0);
3052     LookPassAnd0 = true;
3053   }
3054
3055   if (N1.getOpcode() == ISD::AND) {
3056     if (!N1.getNode()->hasOneUse())
3057       return SDValue();
3058     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3059     if (!N11C || N11C->getZExtValue() != 0xFF)
3060       return SDValue();
3061     N1 = N1.getOperand(0);
3062     LookPassAnd1 = true;
3063   }
3064
3065   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3066     std::swap(N0, N1);
3067   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3068     return SDValue();
3069   if (!N0.getNode()->hasOneUse() ||
3070       !N1.getNode()->hasOneUse())
3071     return SDValue();
3072
3073   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3074   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3075   if (!N01C || !N11C)
3076     return SDValue();
3077   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3078     return SDValue();
3079
3080   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3081   SDValue N00 = N0->getOperand(0);
3082   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3083     if (!N00.getNode()->hasOneUse())
3084       return SDValue();
3085     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3086     if (!N001C || N001C->getZExtValue() != 0xFF)
3087       return SDValue();
3088     N00 = N00.getOperand(0);
3089     LookPassAnd0 = true;
3090   }
3091
3092   SDValue N10 = N1->getOperand(0);
3093   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3094     if (!N10.getNode()->hasOneUse())
3095       return SDValue();
3096     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3097     if (!N101C || N101C->getZExtValue() != 0xFF00)
3098       return SDValue();
3099     N10 = N10.getOperand(0);
3100     LookPassAnd1 = true;
3101   }
3102
3103   if (N00 != N10)
3104     return SDValue();
3105
3106   // Make sure everything beyond the low halfword gets set to zero since the SRL
3107   // 16 will clear the top bits.
3108   unsigned OpSizeInBits = VT.getSizeInBits();
3109   if (DemandHighBits && OpSizeInBits > 16) {
3110     // If the left-shift isn't masked out then the only way this is a bswap is
3111     // if all bits beyond the low 8 are 0. In that case the entire pattern
3112     // reduces to a left shift anyway: leave it for other parts of the combiner.
3113     if (!LookPassAnd0)
3114       return SDValue();
3115
3116     // However, if the right shift isn't masked out then it might be because
3117     // it's not needed. See if we can spot that too.
3118     if (!LookPassAnd1 &&
3119         !DAG.MaskedValueIsZero(
3120             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3121       return SDValue();
3122   }
3123
3124   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3125   if (OpSizeInBits > 16)
3126     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3127                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3128   return Res;
3129 }
3130
3131 /// isBSwapHWordElement - Return true if the specified node is an element
3132 /// that makes up a 32-bit packed halfword byteswap. i.e.
3133 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3134 static bool isBSwapHWordElement(SDValue N, SmallVectorImpl<SDNode *> &Parts) {
3135   if (!N.getNode()->hasOneUse())
3136     return false;
3137
3138   unsigned Opc = N.getOpcode();
3139   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3140     return false;
3141
3142   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3143   if (!N1C)
3144     return false;
3145
3146   unsigned Num;
3147   switch (N1C->getZExtValue()) {
3148   default:
3149     return false;
3150   case 0xFF:       Num = 0; break;
3151   case 0xFF00:     Num = 1; break;
3152   case 0xFF0000:   Num = 2; break;
3153   case 0xFF000000: Num = 3; break;
3154   }
3155
3156   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3157   SDValue N0 = N.getOperand(0);
3158   if (Opc == ISD::AND) {
3159     if (Num == 0 || Num == 2) {
3160       // (x >> 8) & 0xff
3161       // (x >> 8) & 0xff0000
3162       if (N0.getOpcode() != ISD::SRL)
3163         return false;
3164       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3165       if (!C || C->getZExtValue() != 8)
3166         return false;
3167     } else {
3168       // (x << 8) & 0xff00
3169       // (x << 8) & 0xff000000
3170       if (N0.getOpcode() != ISD::SHL)
3171         return false;
3172       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3173       if (!C || C->getZExtValue() != 8)
3174         return false;
3175     }
3176   } else if (Opc == ISD::SHL) {
3177     // (x & 0xff) << 8
3178     // (x & 0xff0000) << 8
3179     if (Num != 0 && Num != 2)
3180       return false;
3181     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3182     if (!C || C->getZExtValue() != 8)
3183       return false;
3184   } else { // Opc == ISD::SRL
3185     // (x & 0xff00) >> 8
3186     // (x & 0xff000000) >> 8
3187     if (Num != 1 && Num != 3)
3188       return false;
3189     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3190     if (!C || C->getZExtValue() != 8)
3191       return false;
3192   }
3193
3194   if (Parts[Num])
3195     return false;
3196
3197   Parts[Num] = N0.getOperand(0).getNode();
3198   return true;
3199 }
3200
3201 /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
3202 /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
3203 /// => (rotl (bswap x), 16)
3204 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3205   if (!LegalOperations)
3206     return SDValue();
3207
3208   EVT VT = N->getValueType(0);
3209   if (VT != MVT::i32)
3210     return SDValue();
3211   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3212     return SDValue();
3213
3214   SmallVector<SDNode*,4> Parts(4, (SDNode*)nullptr);
3215   // Look for either
3216   // (or (or (and), (and)), (or (and), (and)))
3217   // (or (or (or (and), (and)), (and)), (and))
3218   if (N0.getOpcode() != ISD::OR)
3219     return SDValue();
3220   SDValue N00 = N0.getOperand(0);
3221   SDValue N01 = N0.getOperand(1);
3222
3223   if (N1.getOpcode() == ISD::OR &&
3224       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3225     // (or (or (and), (and)), (or (and), (and)))
3226     SDValue N000 = N00.getOperand(0);
3227     if (!isBSwapHWordElement(N000, Parts))
3228       return SDValue();
3229
3230     SDValue N001 = N00.getOperand(1);
3231     if (!isBSwapHWordElement(N001, Parts))
3232       return SDValue();
3233     SDValue N010 = N01.getOperand(0);
3234     if (!isBSwapHWordElement(N010, Parts))
3235       return SDValue();
3236     SDValue N011 = N01.getOperand(1);
3237     if (!isBSwapHWordElement(N011, Parts))
3238       return SDValue();
3239   } else {
3240     // (or (or (or (and), (and)), (and)), (and))
3241     if (!isBSwapHWordElement(N1, Parts))
3242       return SDValue();
3243     if (!isBSwapHWordElement(N01, Parts))
3244       return SDValue();
3245     if (N00.getOpcode() != ISD::OR)
3246       return SDValue();
3247     SDValue N000 = N00.getOperand(0);
3248     if (!isBSwapHWordElement(N000, Parts))
3249       return SDValue();
3250     SDValue N001 = N00.getOperand(1);
3251     if (!isBSwapHWordElement(N001, Parts))
3252       return SDValue();
3253   }
3254
3255   // Make sure the parts are all coming from the same node.
3256   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3257     return SDValue();
3258
3259   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3260                               SDValue(Parts[0],0));
3261
3262   // Result of the bswap should be rotated by 16. If it's not legal, then
3263   // do  (x << 16) | (x >> 16).
3264   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3265   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3266     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3267   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3268     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3269   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3270                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3271                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3272 }
3273
3274 SDValue DAGCombiner::visitOR(SDNode *N) {
3275   SDValue N0 = N->getOperand(0);
3276   SDValue N1 = N->getOperand(1);
3277   SDValue LL, LR, RL, RR, CC0, CC1;
3278   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3279   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3280   EVT VT = N1.getValueType();
3281
3282   // fold vector ops
3283   if (VT.isVector()) {
3284     SDValue FoldedVOp = SimplifyVBinOp(N);
3285     if (FoldedVOp.getNode()) return FoldedVOp;
3286
3287     // fold (or x, 0) -> x, vector edition
3288     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3289       return N1;
3290     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3291       return N0;
3292
3293     // fold (or x, -1) -> -1, vector edition
3294     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3295       return N0;
3296     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3297       return N1;
3298
3299     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3300     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3301     // Do this only if the resulting shuffle is legal.
3302     if (isa<ShuffleVectorSDNode>(N0) &&
3303         isa<ShuffleVectorSDNode>(N1) &&
3304         // Avoid folding a node with illegal type.
3305         TLI.isTypeLegal(VT) &&
3306         N0->getOperand(1) == N1->getOperand(1) &&
3307         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3308       bool CanFold = true;
3309       unsigned NumElts = VT.getVectorNumElements();
3310       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3311       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3312       // We construct two shuffle masks:
3313       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3314       // and N1 as the second operand.
3315       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3316       // and N0 as the second operand.
3317       // We do this because OR is commutable and therefore there might be
3318       // two ways to fold this node into a shuffle.
3319       SmallVector<int,4> Mask1;
3320       SmallVector<int,4> Mask2;
3321
3322       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3323         int M0 = SV0->getMaskElt(i);
3324         int M1 = SV1->getMaskElt(i);
3325
3326         // Both shuffle indexes are undef. Propagate Undef.
3327         if (M0 < 0 && M1 < 0) {
3328           Mask1.push_back(M0);
3329           Mask2.push_back(M0);
3330           continue;
3331         }
3332
3333         if (M0 < 0 || M1 < 0 ||
3334             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3335             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3336           CanFold = false;
3337           break;
3338         }
3339
3340         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3341         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3342       }
3343
3344       if (CanFold) {
3345         // Fold this sequence only if the resulting shuffle is 'legal'.
3346         if (TLI.isShuffleMaskLegal(Mask1, VT))
3347           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3348                                       N1->getOperand(0), &Mask1[0]);
3349         if (TLI.isShuffleMaskLegal(Mask2, VT))
3350           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3351                                       N0->getOperand(0), &Mask2[0]);
3352       }
3353     }
3354   }
3355
3356   // fold (or x, undef) -> -1
3357   if (!LegalOperations &&
3358       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3359     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3360     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3361   }
3362   // fold (or c1, c2) -> c1|c2
3363   if (N0C && N1C)
3364     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3365   // canonicalize constant to RHS
3366   if (N0C && !N1C)
3367     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3368   // fold (or x, 0) -> x
3369   if (N1C && N1C->isNullValue())
3370     return N0;
3371   // fold (or x, -1) -> -1
3372   if (N1C && N1C->isAllOnesValue())
3373     return N1;
3374   // fold (or x, c) -> c iff (x & ~c) == 0
3375   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3376     return N1;
3377
3378   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3379   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3380   if (BSwap.getNode())
3381     return BSwap;
3382   BSwap = MatchBSwapHWordLow(N, N0, N1);
3383   if (BSwap.getNode())
3384     return BSwap;
3385
3386   // reassociate or
3387   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3388   if (ROR.getNode())
3389     return ROR;
3390   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3391   // iff (c1 & c2) == 0.
3392   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3393              isa<ConstantSDNode>(N0.getOperand(1))) {
3394     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3395     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3396       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3397       if (!COR.getNode())
3398         return SDValue();
3399       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3400                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3401                                      N0.getOperand(0), N1), COR);
3402     }
3403   }
3404   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3405   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3406     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3407     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3408
3409     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3410         LL.getValueType().isInteger()) {
3411       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3412       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3413       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3414           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3415         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3416                                      LR.getValueType(), LL, RL);
3417         AddToWorklist(ORNode.getNode());
3418         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3419       }
3420       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3421       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3422       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3423           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3424         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3425                                       LR.getValueType(), LL, RL);
3426         AddToWorklist(ANDNode.getNode());
3427         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3428       }
3429     }
3430     // canonicalize equivalent to ll == rl
3431     if (LL == RR && LR == RL) {
3432       Op1 = ISD::getSetCCSwappedOperands(Op1);
3433       std::swap(RL, RR);
3434     }
3435     if (LL == RL && LR == RR) {
3436       bool isInteger = LL.getValueType().isInteger();
3437       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3438       if (Result != ISD::SETCC_INVALID &&
3439           (!LegalOperations ||
3440            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3441             TLI.isOperationLegal(ISD::SETCC,
3442               getSetCCResultType(N0.getValueType())))))
3443         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3444                             LL, LR, Result);
3445     }
3446   }
3447
3448   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3449   if (N0.getOpcode() == N1.getOpcode()) {
3450     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3451     if (Tmp.getNode()) return Tmp;
3452   }
3453
3454   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3455   if (N0.getOpcode() == ISD::AND &&
3456       N1.getOpcode() == ISD::AND &&
3457       N0.getOperand(1).getOpcode() == ISD::Constant &&
3458       N1.getOperand(1).getOpcode() == ISD::Constant &&
3459       // Don't increase # computations.
3460       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3461     // We can only do this xform if we know that bits from X that are set in C2
3462     // but not in C1 are already zero.  Likewise for Y.
3463     const APInt &LHSMask =
3464       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3465     const APInt &RHSMask =
3466       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3467
3468     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3469         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3470       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3471                               N0.getOperand(0), N1.getOperand(0));
3472       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3473                          DAG.getConstant(LHSMask | RHSMask, VT));
3474     }
3475   }
3476
3477   // See if this is some rotate idiom.
3478   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3479     return SDValue(Rot, 0);
3480
3481   // Simplify the operands using demanded-bits information.
3482   if (!VT.isVector() &&
3483       SimplifyDemandedBits(SDValue(N, 0)))
3484     return SDValue(N, 0);
3485
3486   return SDValue();
3487 }
3488
3489 /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
3490 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3491   if (Op.getOpcode() == ISD::AND) {
3492     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3493       Mask = Op.getOperand(1);
3494       Op = Op.getOperand(0);
3495     } else {
3496       return false;
3497     }
3498   }
3499
3500   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3501     Shift = Op;
3502     return true;
3503   }
3504
3505   return false;
3506 }
3507
3508 // Return true if we can prove that, whenever Neg and Pos are both in the
3509 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3510 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3511 //
3512 //     (or (shift1 X, Neg), (shift2 X, Pos))
3513 //
3514 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3515 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3516 // to consider shift amounts with defined behavior.
3517 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3518   // If OpSize is a power of 2 then:
3519   //
3520   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3521   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3522   //
3523   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3524   // for the stronger condition:
3525   //
3526   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3527   //
3528   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3529   // we can just replace Neg with Neg' for the rest of the function.
3530   //
3531   // In other cases we check for the even stronger condition:
3532   //
3533   //     Neg == OpSize - Pos                                    [B]
3534   //
3535   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3536   // behavior if Pos == 0 (and consequently Neg == OpSize).
3537   //
3538   // We could actually use [A] whenever OpSize is a power of 2, but the
3539   // only extra cases that it would match are those uninteresting ones
3540   // where Neg and Pos are never in range at the same time.  E.g. for
3541   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3542   // as well as (sub 32, Pos), but:
3543   //
3544   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3545   //
3546   // always invokes undefined behavior for 32-bit X.
3547   //
3548   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3549   unsigned MaskLoBits = 0;
3550   if (Neg.getOpcode() == ISD::AND &&
3551       isPowerOf2_64(OpSize) &&
3552       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3553       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3554     Neg = Neg.getOperand(0);
3555     MaskLoBits = Log2_64(OpSize);
3556   }
3557
3558   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3559   if (Neg.getOpcode() != ISD::SUB)
3560     return 0;
3561   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3562   if (!NegC)
3563     return 0;
3564   SDValue NegOp1 = Neg.getOperand(1);
3565
3566   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3567   // Pos'.  The truncation is redundant for the purpose of the equality.
3568   if (MaskLoBits &&
3569       Pos.getOpcode() == ISD::AND &&
3570       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3571       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3572     Pos = Pos.getOperand(0);
3573
3574   // The condition we need is now:
3575   //
3576   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3577   //
3578   // If NegOp1 == Pos then we need:
3579   //
3580   //              OpSize & Mask == NegC & Mask
3581   //
3582   // (because "x & Mask" is a truncation and distributes through subtraction).
3583   APInt Width;
3584   if (Pos == NegOp1)
3585     Width = NegC->getAPIntValue();
3586   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3587   // Then the condition we want to prove becomes:
3588   //
3589   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3590   //
3591   // which, again because "x & Mask" is a truncation, becomes:
3592   //
3593   //                NegC & Mask == (OpSize - PosC) & Mask
3594   //              OpSize & Mask == (NegC + PosC) & Mask
3595   else if (Pos.getOpcode() == ISD::ADD &&
3596            Pos.getOperand(0) == NegOp1 &&
3597            Pos.getOperand(1).getOpcode() == ISD::Constant)
3598     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3599              NegC->getAPIntValue());
3600   else
3601     return false;
3602
3603   // Now we just need to check that OpSize & Mask == Width & Mask.
3604   if (MaskLoBits)
3605     // Opsize & Mask is 0 since Mask is Opsize - 1.
3606     return Width.getLoBits(MaskLoBits) == 0;
3607   return Width == OpSize;
3608 }
3609
3610 // A subroutine of MatchRotate used once we have found an OR of two opposite
3611 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3612 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3613 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3614 // Neg with outer conversions stripped away.
3615 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3616                                        SDValue Neg, SDValue InnerPos,
3617                                        SDValue InnerNeg, unsigned PosOpcode,
3618                                        unsigned NegOpcode, SDLoc DL) {
3619   // fold (or (shl x, (*ext y)),
3620   //          (srl x, (*ext (sub 32, y)))) ->
3621   //   (rotl x, y) or (rotr x, (sub 32, y))
3622   //
3623   // fold (or (shl x, (*ext (sub 32, y))),
3624   //          (srl x, (*ext y))) ->
3625   //   (rotr x, y) or (rotl x, (sub 32, y))
3626   EVT VT = Shifted.getValueType();
3627   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3628     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3629     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3630                        HasPos ? Pos : Neg).getNode();
3631   }
3632
3633   return nullptr;
3634 }
3635
3636 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3637 // idioms for rotate, and if the target supports rotation instructions, generate
3638 // a rot[lr].
3639 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3640   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3641   EVT VT = LHS.getValueType();
3642   if (!TLI.isTypeLegal(VT)) return nullptr;
3643
3644   // The target must have at least one rotate flavor.
3645   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3646   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3647   if (!HasROTL && !HasROTR) return nullptr;
3648
3649   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3650   SDValue LHSShift;   // The shift.
3651   SDValue LHSMask;    // AND value if any.
3652   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3653     return nullptr; // Not part of a rotate.
3654
3655   SDValue RHSShift;   // The shift.
3656   SDValue RHSMask;    // AND value if any.
3657   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3658     return nullptr; // Not part of a rotate.
3659
3660   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3661     return nullptr;   // Not shifting the same value.
3662
3663   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3664     return nullptr;   // Shifts must disagree.
3665
3666   // Canonicalize shl to left side in a shl/srl pair.
3667   if (RHSShift.getOpcode() == ISD::SHL) {
3668     std::swap(LHS, RHS);
3669     std::swap(LHSShift, RHSShift);
3670     std::swap(LHSMask , RHSMask );
3671   }
3672
3673   unsigned OpSizeInBits = VT.getSizeInBits();
3674   SDValue LHSShiftArg = LHSShift.getOperand(0);
3675   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3676   SDValue RHSShiftArg = RHSShift.getOperand(0);
3677   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3678
3679   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3680   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3681   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3682       RHSShiftAmt.getOpcode() == ISD::Constant) {
3683     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3684     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3685     if ((LShVal + RShVal) != OpSizeInBits)
3686       return nullptr;
3687
3688     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3689                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3690
3691     // If there is an AND of either shifted operand, apply it to the result.
3692     if (LHSMask.getNode() || RHSMask.getNode()) {
3693       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3694
3695       if (LHSMask.getNode()) {
3696         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3697         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3698       }
3699       if (RHSMask.getNode()) {
3700         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3701         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3702       }
3703
3704       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3705     }
3706
3707     return Rot.getNode();
3708   }
3709
3710   // If there is a mask here, and we have a variable shift, we can't be sure
3711   // that we're masking out the right stuff.
3712   if (LHSMask.getNode() || RHSMask.getNode())
3713     return nullptr;
3714
3715   // If the shift amount is sign/zext/any-extended just peel it off.
3716   SDValue LExtOp0 = LHSShiftAmt;
3717   SDValue RExtOp0 = RHSShiftAmt;
3718   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3719        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3720        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3721        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3722       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3723        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3724        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3725        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3726     LExtOp0 = LHSShiftAmt.getOperand(0);
3727     RExtOp0 = RHSShiftAmt.getOperand(0);
3728   }
3729
3730   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3731                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3732   if (TryL)
3733     return TryL;
3734
3735   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3736                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3737   if (TryR)
3738     return TryR;
3739
3740   return nullptr;
3741 }
3742
3743 SDValue DAGCombiner::visitXOR(SDNode *N) {
3744   SDValue N0 = N->getOperand(0);
3745   SDValue N1 = N->getOperand(1);
3746   SDValue LHS, RHS, CC;
3747   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3748   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3749   EVT VT = N0.getValueType();
3750
3751   // fold vector ops
3752   if (VT.isVector()) {
3753     SDValue FoldedVOp = SimplifyVBinOp(N);
3754     if (FoldedVOp.getNode()) return FoldedVOp;
3755
3756     // fold (xor x, 0) -> x, vector edition
3757     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3758       return N1;
3759     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3760       return N0;
3761   }
3762
3763   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3764   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3765     return DAG.getConstant(0, VT);
3766   // fold (xor x, undef) -> undef
3767   if (N0.getOpcode() == ISD::UNDEF)
3768     return N0;
3769   if (N1.getOpcode() == ISD::UNDEF)
3770     return N1;
3771   // fold (xor c1, c2) -> c1^c2
3772   if (N0C && N1C)
3773     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3774   // canonicalize constant to RHS
3775   if (N0C && !N1C)
3776     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3777   // fold (xor x, 0) -> x
3778   if (N1C && N1C->isNullValue())
3779     return N0;
3780   // reassociate xor
3781   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3782   if (RXOR.getNode())
3783     return RXOR;
3784
3785   // fold !(x cc y) -> (x !cc y)
3786   if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3787     bool isInt = LHS.getValueType().isInteger();
3788     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3789                                                isInt);
3790
3791     if (!LegalOperations ||
3792         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3793       switch (N0.getOpcode()) {
3794       default:
3795         llvm_unreachable("Unhandled SetCC Equivalent!");
3796       case ISD::SETCC:
3797         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3798       case ISD::SELECT_CC:
3799         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3800                                N0.getOperand(3), NotCC);
3801       }
3802     }
3803   }
3804
3805   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3806   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3807       N0.getNode()->hasOneUse() &&
3808       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3809     SDValue V = N0.getOperand(0);
3810     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3811                     DAG.getConstant(1, V.getValueType()));
3812     AddToWorklist(V.getNode());
3813     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3814   }
3815
3816   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3817   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3818       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3819     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3820     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3821       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3822       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3823       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3824       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3825       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3826     }
3827   }
3828   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3829   if (N1C && N1C->isAllOnesValue() &&
3830       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3831     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3832     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3833       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3834       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3835       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3836       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3837       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3838     }
3839   }
3840   // fold (xor (and x, y), y) -> (and (not x), y)
3841   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3842       N0->getOperand(1) == N1) {
3843     SDValue X = N0->getOperand(0);
3844     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3845     AddToWorklist(NotX.getNode());
3846     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3847   }
3848   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3849   if (N1C && N0.getOpcode() == ISD::XOR) {
3850     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3851     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3852     if (N00C)
3853       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3854                          DAG.getConstant(N1C->getAPIntValue() ^
3855                                          N00C->getAPIntValue(), VT));
3856     if (N01C)
3857       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3858                          DAG.getConstant(N1C->getAPIntValue() ^
3859                                          N01C->getAPIntValue(), VT));
3860   }
3861   // fold (xor x, x) -> 0
3862   if (N0 == N1)
3863     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3864
3865   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3866   if (N0.getOpcode() == N1.getOpcode()) {
3867     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3868     if (Tmp.getNode()) return Tmp;
3869   }
3870
3871   // Simplify the expression using non-local knowledge.
3872   if (!VT.isVector() &&
3873       SimplifyDemandedBits(SDValue(N, 0)))
3874     return SDValue(N, 0);
3875
3876   return SDValue();
3877 }
3878
3879 /// visitShiftByConstant - Handle transforms common to the three shifts, when
3880 /// the shift amount is a constant.
3881 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3882   // We can't and shouldn't fold opaque constants.
3883   if (Amt->isOpaque())
3884     return SDValue();
3885
3886   SDNode *LHS = N->getOperand(0).getNode();
3887   if (!LHS->hasOneUse()) return SDValue();
3888
3889   // We want to pull some binops through shifts, so that we have (and (shift))
3890   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3891   // thing happens with address calculations, so it's important to canonicalize
3892   // it.
3893   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3894
3895   switch (LHS->getOpcode()) {
3896   default: return SDValue();
3897   case ISD::OR:
3898   case ISD::XOR:
3899     HighBitSet = false; // We can only transform sra if the high bit is clear.
3900     break;
3901   case ISD::AND:
3902     HighBitSet = true;  // We can only transform sra if the high bit is set.
3903     break;
3904   case ISD::ADD:
3905     if (N->getOpcode() != ISD::SHL)
3906       return SDValue(); // only shl(add) not sr[al](add).
3907     HighBitSet = false; // We can only transform sra if the high bit is clear.
3908     break;
3909   }
3910
3911   // We require the RHS of the binop to be a constant and not opaque as well.
3912   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3913   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3914
3915   // FIXME: disable this unless the input to the binop is a shift by a constant.
3916   // If it is not a shift, it pessimizes some common cases like:
3917   //
3918   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3919   //    int bar(int *X, int i) { return X[i & 255]; }
3920   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3921   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3922        BinOpLHSVal->getOpcode() != ISD::SRA &&
3923        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3924       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3925     return SDValue();
3926
3927   EVT VT = N->getValueType(0);
3928
3929   // If this is a signed shift right, and the high bit is modified by the
3930   // logical operation, do not perform the transformation. The highBitSet
3931   // boolean indicates the value of the high bit of the constant which would
3932   // cause it to be modified for this operation.
3933   if (N->getOpcode() == ISD::SRA) {
3934     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3935     if (BinOpRHSSignSet != HighBitSet)
3936       return SDValue();
3937   }
3938
3939   if (!TLI.isDesirableToCommuteWithShift(LHS))
3940     return SDValue();
3941
3942   // Fold the constants, shifting the binop RHS by the shift amount.
3943   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3944                                N->getValueType(0),
3945                                LHS->getOperand(1), N->getOperand(1));
3946   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3947
3948   // Create the new shift.
3949   SDValue NewShift = DAG.getNode(N->getOpcode(),
3950                                  SDLoc(LHS->getOperand(0)),
3951                                  VT, LHS->getOperand(0), N->getOperand(1));
3952
3953   // Create the new binop.
3954   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
3955 }
3956
3957 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
3958   assert(N->getOpcode() == ISD::TRUNCATE);
3959   assert(N->getOperand(0).getOpcode() == ISD::AND);
3960
3961   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
3962   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
3963     SDValue N01 = N->getOperand(0).getOperand(1);
3964
3965     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
3966       EVT TruncVT = N->getValueType(0);
3967       SDValue N00 = N->getOperand(0).getOperand(0);
3968       APInt TruncC = N01C->getAPIntValue();
3969       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
3970
3971       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
3972                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
3973                          DAG.getConstant(TruncC, TruncVT));
3974     }
3975   }
3976
3977   return SDValue();
3978 }
3979
3980 SDValue DAGCombiner::visitRotate(SDNode *N) {
3981   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
3982   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
3983       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
3984     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
3985     if (NewOp1.getNode())
3986       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
3987                          N->getOperand(0), NewOp1);
3988   }
3989   return SDValue();
3990 }
3991
3992 SDValue DAGCombiner::visitSHL(SDNode *N) {
3993   SDValue N0 = N->getOperand(0);
3994   SDValue N1 = N->getOperand(1);
3995   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3996   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3997   EVT VT = N0.getValueType();
3998   unsigned OpSizeInBits = VT.getScalarSizeInBits();
3999
4000   // fold vector ops
4001   if (VT.isVector()) {
4002     SDValue FoldedVOp = SimplifyVBinOp(N);
4003     if (FoldedVOp.getNode()) return FoldedVOp;
4004
4005     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4006     // If setcc produces all-one true value then:
4007     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4008     if (N1CV && N1CV->isConstant()) {
4009       if (N0.getOpcode() == ISD::AND) {
4010         SDValue N00 = N0->getOperand(0);
4011         SDValue N01 = N0->getOperand(1);
4012         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4013
4014         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4015             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4016                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4017           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4018           if (C.getNode())
4019             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4020         }
4021       } else {
4022         N1C = isConstOrConstSplat(N1);
4023       }
4024     }
4025   }
4026
4027   // fold (shl c1, c2) -> c1<<c2
4028   if (N0C && N1C)
4029     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4030   // fold (shl 0, x) -> 0
4031   if (N0C && N0C->isNullValue())
4032     return N0;
4033   // fold (shl x, c >= size(x)) -> undef
4034   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4035     return DAG.getUNDEF(VT);
4036   // fold (shl x, 0) -> x
4037   if (N1C && N1C->isNullValue())
4038     return N0;
4039   // fold (shl undef, x) -> 0
4040   if (N0.getOpcode() == ISD::UNDEF)
4041     return DAG.getConstant(0, VT);
4042   // if (shl x, c) is known to be zero, return 0
4043   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4044                             APInt::getAllOnesValue(OpSizeInBits)))
4045     return DAG.getConstant(0, VT);
4046   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4047   if (N1.getOpcode() == ISD::TRUNCATE &&
4048       N1.getOperand(0).getOpcode() == ISD::AND) {
4049     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4050     if (NewOp1.getNode())
4051       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4052   }
4053
4054   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4055     return SDValue(N, 0);
4056
4057   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4058   if (N1C && N0.getOpcode() == ISD::SHL) {
4059     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4060       uint64_t c1 = N0C1->getZExtValue();
4061       uint64_t c2 = N1C->getZExtValue();
4062       if (c1 + c2 >= OpSizeInBits)
4063         return DAG.getConstant(0, VT);
4064       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4065                          DAG.getConstant(c1 + c2, N1.getValueType()));
4066     }
4067   }
4068
4069   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4070   // For this to be valid, the second form must not preserve any of the bits
4071   // that are shifted out by the inner shift in the first form.  This means
4072   // the outer shift size must be >= the number of bits added by the ext.
4073   // As a corollary, we don't care what kind of ext it is.
4074   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4075               N0.getOpcode() == ISD::ANY_EXTEND ||
4076               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4077       N0.getOperand(0).getOpcode() == ISD::SHL) {
4078     SDValue N0Op0 = N0.getOperand(0);
4079     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4080       uint64_t c1 = N0Op0C1->getZExtValue();
4081       uint64_t c2 = N1C->getZExtValue();
4082       EVT InnerShiftVT = N0Op0.getValueType();
4083       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4084       if (c2 >= OpSizeInBits - InnerShiftSize) {
4085         if (c1 + c2 >= OpSizeInBits)
4086           return DAG.getConstant(0, VT);
4087         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4088                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4089                                        N0Op0->getOperand(0)),
4090                            DAG.getConstant(c1 + c2, N1.getValueType()));
4091       }
4092     }
4093   }
4094
4095   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4096   // Only fold this if the inner zext has no other uses to avoid increasing
4097   // the total number of instructions.
4098   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4099       N0.getOperand(0).getOpcode() == ISD::SRL) {
4100     SDValue N0Op0 = N0.getOperand(0);
4101     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4102       uint64_t c1 = N0Op0C1->getZExtValue();
4103       if (c1 < VT.getScalarSizeInBits()) {
4104         uint64_t c2 = N1C->getZExtValue();
4105         if (c1 == c2) {
4106           SDValue NewOp0 = N0.getOperand(0);
4107           EVT CountVT = NewOp0.getOperand(1).getValueType();
4108           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4109                                        NewOp0, DAG.getConstant(c2, CountVT));
4110           AddToWorklist(NewSHL.getNode());
4111           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4112         }
4113       }
4114     }
4115   }
4116
4117   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4118   //                               (and (srl x, (sub c1, c2), MASK)
4119   // Only fold this if the inner shift has no other uses -- if it does, folding
4120   // this will increase the total number of instructions.
4121   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4122     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4123       uint64_t c1 = N0C1->getZExtValue();
4124       if (c1 < OpSizeInBits) {
4125         uint64_t c2 = N1C->getZExtValue();
4126         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4127         SDValue Shift;
4128         if (c2 > c1) {
4129           Mask = Mask.shl(c2 - c1);
4130           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4131                               DAG.getConstant(c2 - c1, N1.getValueType()));
4132         } else {
4133           Mask = Mask.lshr(c1 - c2);
4134           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4135                               DAG.getConstant(c1 - c2, N1.getValueType()));
4136         }
4137         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4138                            DAG.getConstant(Mask, VT));
4139       }
4140     }
4141   }
4142   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4143   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4144     unsigned BitSize = VT.getScalarSizeInBits();
4145     SDValue HiBitsMask =
4146       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4147                                             BitSize - N1C->getZExtValue()), VT);
4148     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4149                        HiBitsMask);
4150   }
4151
4152   if (N1C) {
4153     SDValue NewSHL = visitShiftByConstant(N, N1C);
4154     if (NewSHL.getNode())
4155       return NewSHL;
4156   }
4157
4158   return SDValue();
4159 }
4160
4161 SDValue DAGCombiner::visitSRA(SDNode *N) {
4162   SDValue N0 = N->getOperand(0);
4163   SDValue N1 = N->getOperand(1);
4164   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4165   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4166   EVT VT = N0.getValueType();
4167   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4168
4169   // fold vector ops
4170   if (VT.isVector()) {
4171     SDValue FoldedVOp = SimplifyVBinOp(N);
4172     if (FoldedVOp.getNode()) return FoldedVOp;
4173
4174     N1C = isConstOrConstSplat(N1);
4175   }
4176
4177   // fold (sra c1, c2) -> (sra c1, c2)
4178   if (N0C && N1C)
4179     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4180   // fold (sra 0, x) -> 0
4181   if (N0C && N0C->isNullValue())
4182     return N0;
4183   // fold (sra -1, x) -> -1
4184   if (N0C && N0C->isAllOnesValue())
4185     return N0;
4186   // fold (sra x, (setge c, size(x))) -> undef
4187   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4188     return DAG.getUNDEF(VT);
4189   // fold (sra x, 0) -> x
4190   if (N1C && N1C->isNullValue())
4191     return N0;
4192   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4193   // sext_inreg.
4194   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4195     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4196     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4197     if (VT.isVector())
4198       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4199                                ExtVT, VT.getVectorNumElements());
4200     if ((!LegalOperations ||
4201          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4202       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4203                          N0.getOperand(0), DAG.getValueType(ExtVT));
4204   }
4205
4206   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4207   if (N1C && N0.getOpcode() == ISD::SRA) {
4208     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4209       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4210       if (Sum >= OpSizeInBits)
4211         Sum = OpSizeInBits - 1;
4212       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4213                          DAG.getConstant(Sum, N1.getValueType()));
4214     }
4215   }
4216
4217   // fold (sra (shl X, m), (sub result_size, n))
4218   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4219   // result_size - n != m.
4220   // If truncate is free for the target sext(shl) is likely to result in better
4221   // code.
4222   if (N0.getOpcode() == ISD::SHL && N1C) {
4223     // Get the two constanst of the shifts, CN0 = m, CN = n.
4224     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4225     if (N01C) {
4226       LLVMContext &Ctx = *DAG.getContext();
4227       // Determine what the truncate's result bitsize and type would be.
4228       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4229
4230       if (VT.isVector())
4231         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4232
4233       // Determine the residual right-shift amount.
4234       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4235
4236       // If the shift is not a no-op (in which case this should be just a sign
4237       // extend already), the truncated to type is legal, sign_extend is legal
4238       // on that type, and the truncate to that type is both legal and free,
4239       // perform the transform.
4240       if ((ShiftAmt > 0) &&
4241           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4242           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4243           TLI.isTruncateFree(VT, TruncVT)) {
4244
4245           SDValue Amt = DAG.getConstant(ShiftAmt,
4246               getShiftAmountTy(N0.getOperand(0).getValueType()));
4247           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4248                                       N0.getOperand(0), Amt);
4249           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4250                                       Shift);
4251           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4252                              N->getValueType(0), Trunc);
4253       }
4254     }
4255   }
4256
4257   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4258   if (N1.getOpcode() == ISD::TRUNCATE &&
4259       N1.getOperand(0).getOpcode() == ISD::AND) {
4260     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4261     if (NewOp1.getNode())
4262       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4263   }
4264
4265   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4266   //      if c1 is equal to the number of bits the trunc removes
4267   if (N0.getOpcode() == ISD::TRUNCATE &&
4268       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4269        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4270       N0.getOperand(0).hasOneUse() &&
4271       N0.getOperand(0).getOperand(1).hasOneUse() &&
4272       N1C) {
4273     SDValue N0Op0 = N0.getOperand(0);
4274     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4275       unsigned LargeShiftVal = LargeShift->getZExtValue();
4276       EVT LargeVT = N0Op0.getValueType();
4277
4278       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4279         SDValue Amt =
4280           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4281                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4282         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4283                                   N0Op0.getOperand(0), Amt);
4284         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4285       }
4286     }
4287   }
4288
4289   // Simplify, based on bits shifted out of the LHS.
4290   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4291     return SDValue(N, 0);
4292
4293
4294   // If the sign bit is known to be zero, switch this to a SRL.
4295   if (DAG.SignBitIsZero(N0))
4296     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4297
4298   if (N1C) {
4299     SDValue NewSRA = visitShiftByConstant(N, N1C);
4300     if (NewSRA.getNode())
4301       return NewSRA;
4302   }
4303
4304   return SDValue();
4305 }
4306
4307 SDValue DAGCombiner::visitSRL(SDNode *N) {
4308   SDValue N0 = N->getOperand(0);
4309   SDValue N1 = N->getOperand(1);
4310   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4311   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4312   EVT VT = N0.getValueType();
4313   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4314
4315   // fold vector ops
4316   if (VT.isVector()) {
4317     SDValue FoldedVOp = SimplifyVBinOp(N);
4318     if (FoldedVOp.getNode()) return FoldedVOp;
4319
4320     N1C = isConstOrConstSplat(N1);
4321   }
4322
4323   // fold (srl c1, c2) -> c1 >>u c2
4324   if (N0C && N1C)
4325     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4326   // fold (srl 0, x) -> 0
4327   if (N0C && N0C->isNullValue())
4328     return N0;
4329   // fold (srl x, c >= size(x)) -> undef
4330   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4331     return DAG.getUNDEF(VT);
4332   // fold (srl x, 0) -> x
4333   if (N1C && N1C->isNullValue())
4334     return N0;
4335   // if (srl x, c) is known to be zero, return 0
4336   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4337                                    APInt::getAllOnesValue(OpSizeInBits)))
4338     return DAG.getConstant(0, VT);
4339
4340   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4341   if (N1C && N0.getOpcode() == ISD::SRL) {
4342     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4343       uint64_t c1 = N01C->getZExtValue();
4344       uint64_t c2 = N1C->getZExtValue();
4345       if (c1 + c2 >= OpSizeInBits)
4346         return DAG.getConstant(0, VT);
4347       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4348                          DAG.getConstant(c1 + c2, N1.getValueType()));
4349     }
4350   }
4351
4352   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4353   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4354       N0.getOperand(0).getOpcode() == ISD::SRL &&
4355       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4356     uint64_t c1 =
4357       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4358     uint64_t c2 = N1C->getZExtValue();
4359     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4360     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4361     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4362     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4363     if (c1 + OpSizeInBits == InnerShiftSize) {
4364       if (c1 + c2 >= InnerShiftSize)
4365         return DAG.getConstant(0, VT);
4366       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4367                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4368                                      N0.getOperand(0)->getOperand(0),
4369                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4370     }
4371   }
4372
4373   // fold (srl (shl x, c), c) -> (and x, cst2)
4374   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4375     unsigned BitSize = N0.getScalarValueSizeInBits();
4376     if (BitSize <= 64) {
4377       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4378       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4379                          DAG.getConstant(~0ULL >> ShAmt, VT));
4380     }
4381   }
4382
4383   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4384   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4385     // Shifting in all undef bits?
4386     EVT SmallVT = N0.getOperand(0).getValueType();
4387     unsigned BitSize = SmallVT.getScalarSizeInBits();
4388     if (N1C->getZExtValue() >= BitSize)
4389       return DAG.getUNDEF(VT);
4390
4391     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4392       uint64_t ShiftAmt = N1C->getZExtValue();
4393       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4394                                        N0.getOperand(0),
4395                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4396       AddToWorklist(SmallShift.getNode());
4397       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4398       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4399                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4400                          DAG.getConstant(Mask, VT));
4401     }
4402   }
4403
4404   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4405   // bit, which is unmodified by sra.
4406   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4407     if (N0.getOpcode() == ISD::SRA)
4408       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4409   }
4410
4411   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4412   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4413       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4414     APInt KnownZero, KnownOne;
4415     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4416
4417     // If any of the input bits are KnownOne, then the input couldn't be all
4418     // zeros, thus the result of the srl will always be zero.
4419     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4420
4421     // If all of the bits input the to ctlz node are known to be zero, then
4422     // the result of the ctlz is "32" and the result of the shift is one.
4423     APInt UnknownBits = ~KnownZero;
4424     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4425
4426     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4427     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4428       // Okay, we know that only that the single bit specified by UnknownBits
4429       // could be set on input to the CTLZ node. If this bit is set, the SRL
4430       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4431       // to an SRL/XOR pair, which is likely to simplify more.
4432       unsigned ShAmt = UnknownBits.countTrailingZeros();
4433       SDValue Op = N0.getOperand(0);
4434
4435       if (ShAmt) {
4436         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4437                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4438         AddToWorklist(Op.getNode());
4439       }
4440
4441       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4442                          Op, DAG.getConstant(1, VT));
4443     }
4444   }
4445
4446   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4447   if (N1.getOpcode() == ISD::TRUNCATE &&
4448       N1.getOperand(0).getOpcode() == ISD::AND) {
4449     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4450     if (NewOp1.getNode())
4451       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4452   }
4453
4454   // fold operands of srl based on knowledge that the low bits are not
4455   // demanded.
4456   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4457     return SDValue(N, 0);
4458
4459   if (N1C) {
4460     SDValue NewSRL = visitShiftByConstant(N, N1C);
4461     if (NewSRL.getNode())
4462       return NewSRL;
4463   }
4464
4465   // Attempt to convert a srl of a load into a narrower zero-extending load.
4466   SDValue NarrowLoad = ReduceLoadWidth(N);
4467   if (NarrowLoad.getNode())
4468     return NarrowLoad;
4469
4470   // Here is a common situation. We want to optimize:
4471   //
4472   //   %a = ...
4473   //   %b = and i32 %a, 2
4474   //   %c = srl i32 %b, 1
4475   //   brcond i32 %c ...
4476   //
4477   // into
4478   //
4479   //   %a = ...
4480   //   %b = and %a, 2
4481   //   %c = setcc eq %b, 0
4482   //   brcond %c ...
4483   //
4484   // However when after the source operand of SRL is optimized into AND, the SRL
4485   // itself may not be optimized further. Look for it and add the BRCOND into
4486   // the worklist.
4487   if (N->hasOneUse()) {
4488     SDNode *Use = *N->use_begin();
4489     if (Use->getOpcode() == ISD::BRCOND)
4490       AddToWorklist(Use);
4491     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4492       // Also look pass the truncate.
4493       Use = *Use->use_begin();
4494       if (Use->getOpcode() == ISD::BRCOND)
4495         AddToWorklist(Use);
4496     }
4497   }
4498
4499   return SDValue();
4500 }
4501
4502 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4503   SDValue N0 = N->getOperand(0);
4504   EVT VT = N->getValueType(0);
4505
4506   // fold (ctlz c1) -> c2
4507   if (isa<ConstantSDNode>(N0))
4508     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4509   return SDValue();
4510 }
4511
4512 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4513   SDValue N0 = N->getOperand(0);
4514   EVT VT = N->getValueType(0);
4515
4516   // fold (ctlz_zero_undef c1) -> c2
4517   if (isa<ConstantSDNode>(N0))
4518     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4519   return SDValue();
4520 }
4521
4522 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4523   SDValue N0 = N->getOperand(0);
4524   EVT VT = N->getValueType(0);
4525
4526   // fold (cttz c1) -> c2
4527   if (isa<ConstantSDNode>(N0))
4528     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4529   return SDValue();
4530 }
4531
4532 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4533   SDValue N0 = N->getOperand(0);
4534   EVT VT = N->getValueType(0);
4535
4536   // fold (cttz_zero_undef c1) -> c2
4537   if (isa<ConstantSDNode>(N0))
4538     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4539   return SDValue();
4540 }
4541
4542 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4543   SDValue N0 = N->getOperand(0);
4544   EVT VT = N->getValueType(0);
4545
4546   // fold (ctpop c1) -> c2
4547   if (isa<ConstantSDNode>(N0))
4548     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4549   return SDValue();
4550 }
4551
4552 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4553   SDValue N0 = N->getOperand(0);
4554   SDValue N1 = N->getOperand(1);
4555   SDValue N2 = N->getOperand(2);
4556   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4557   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4558   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4559   EVT VT = N->getValueType(0);
4560   EVT VT0 = N0.getValueType();
4561
4562   // fold (select C, X, X) -> X
4563   if (N1 == N2)
4564     return N1;
4565   // fold (select true, X, Y) -> X
4566   if (N0C && !N0C->isNullValue())
4567     return N1;
4568   // fold (select false, X, Y) -> Y
4569   if (N0C && N0C->isNullValue())
4570     return N2;
4571   // fold (select C, 1, X) -> (or C, X)
4572   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4573     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4574   // fold (select C, 0, 1) -> (xor C, 1)
4575   // We can't do this reliably if integer based booleans have different contents
4576   // to floating point based booleans. This is because we can't tell whether we
4577   // have an integer-based boolean or a floating-point-based boolean unless we
4578   // can find the SETCC that produced it and inspect its operands. This is
4579   // fairly easy if C is the SETCC node, but it can potentially be
4580   // undiscoverable (or not reasonably discoverable). For example, it could be
4581   // in another basic block or it could require searching a complicated
4582   // expression.
4583   if (VT.isInteger() &&
4584       (VT0 == MVT::i1 || (VT0.isInteger() &&
4585                           TLI.getBooleanContents(false, false) ==
4586                               TLI.getBooleanContents(false, true) &&
4587                           TLI.getBooleanContents(false, false) ==
4588                               TargetLowering::ZeroOrOneBooleanContent)) &&
4589       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4590     SDValue XORNode;
4591     if (VT == VT0)
4592       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4593                          N0, DAG.getConstant(1, VT0));
4594     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4595                           N0, DAG.getConstant(1, VT0));
4596     AddToWorklist(XORNode.getNode());
4597     if (VT.bitsGT(VT0))
4598       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4599     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4600   }
4601   // fold (select C, 0, X) -> (and (not C), X)
4602   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4603     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4604     AddToWorklist(NOTNode.getNode());
4605     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4606   }
4607   // fold (select C, X, 1) -> (or (not C), X)
4608   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4609     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4610     AddToWorklist(NOTNode.getNode());
4611     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4612   }
4613   // fold (select C, X, 0) -> (and C, X)
4614   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4615     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4616   // fold (select X, X, Y) -> (or X, Y)
4617   // fold (select X, 1, Y) -> (or X, Y)
4618   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4619     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4620   // fold (select X, Y, X) -> (and X, Y)
4621   // fold (select X, Y, 0) -> (and X, Y)
4622   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4623     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4624
4625   // If we can fold this based on the true/false value, do so.
4626   if (SimplifySelectOps(N, N1, N2))
4627     return SDValue(N, 0);  // Don't revisit N.
4628
4629   // fold selects based on a setcc into other things, such as min/max/abs
4630   if (N0.getOpcode() == ISD::SETCC) {
4631     if ((!LegalOperations &&
4632          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4633         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4634       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4635                          N0.getOperand(0), N0.getOperand(1),
4636                          N1, N2, N0.getOperand(2));
4637     return SimplifySelect(SDLoc(N), N0, N1, N2);
4638   }
4639
4640   return SDValue();
4641 }
4642
4643 static
4644 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4645   SDLoc DL(N);
4646   EVT LoVT, HiVT;
4647   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4648
4649   // Split the inputs.
4650   SDValue Lo, Hi, LL, LH, RL, RH;
4651   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4652   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4653
4654   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4655   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4656
4657   return std::make_pair(Lo, Hi);
4658 }
4659
4660 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4661 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4662 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4663   SDLoc dl(N);
4664   SDValue Cond = N->getOperand(0);
4665   SDValue LHS = N->getOperand(1);
4666   SDValue RHS = N->getOperand(2);
4667   MVT VT = N->getSimpleValueType(0);
4668   int NumElems = VT.getVectorNumElements();
4669   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4670          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4671          Cond.getOpcode() == ISD::BUILD_VECTOR);
4672
4673   // We're sure we have an even number of elements due to the
4674   // concat_vectors we have as arguments to vselect.
4675   // Skip BV elements until we find one that's not an UNDEF
4676   // After we find an UNDEF element, keep looping until we get to half the
4677   // length of the BV and see if all the non-undef nodes are the same.
4678   ConstantSDNode *BottomHalf = nullptr;
4679   for (int i = 0; i < NumElems / 2; ++i) {
4680     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4681       continue;
4682
4683     if (BottomHalf == nullptr)
4684       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4685     else if (Cond->getOperand(i).getNode() != BottomHalf)
4686       return SDValue();
4687   }
4688
4689   // Do the same for the second half of the BuildVector
4690   ConstantSDNode *TopHalf = nullptr;
4691   for (int i = NumElems / 2; i < NumElems; ++i) {
4692     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4693       continue;
4694
4695     if (TopHalf == nullptr)
4696       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4697     else if (Cond->getOperand(i).getNode() != TopHalf)
4698       return SDValue();
4699   }
4700
4701   assert(TopHalf && BottomHalf &&
4702          "One half of the selector was all UNDEFs and the other was all the "
4703          "same value. This should have been addressed before this function.");
4704   return DAG.getNode(
4705       ISD::CONCAT_VECTORS, dl, VT,
4706       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4707       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4708 }
4709
4710 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4711   SDValue N0 = N->getOperand(0);
4712   SDValue N1 = N->getOperand(1);
4713   SDValue N2 = N->getOperand(2);
4714   SDLoc DL(N);
4715
4716   // Canonicalize integer abs.
4717   // vselect (setg[te] X,  0),  X, -X ->
4718   // vselect (setgt    X, -1),  X, -X ->
4719   // vselect (setl[te] X,  0), -X,  X ->
4720   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4721   if (N0.getOpcode() == ISD::SETCC) {
4722     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4723     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4724     bool isAbs = false;
4725     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4726
4727     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4728          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4729         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4730       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4731     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4732              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4733       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4734
4735     if (isAbs) {
4736       EVT VT = LHS.getValueType();
4737       SDValue Shift = DAG.getNode(
4738           ISD::SRA, DL, VT, LHS,
4739           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4740       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4741       AddToWorklist(Shift.getNode());
4742       AddToWorklist(Add.getNode());
4743       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4744     }
4745   }
4746
4747   // If the VSELECT result requires splitting and the mask is provided by a
4748   // SETCC, then split both nodes and its operands before legalization. This
4749   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4750   // and enables future optimizations (e.g. min/max pattern matching on X86).
4751   if (N0.getOpcode() == ISD::SETCC) {
4752     EVT VT = N->getValueType(0);
4753
4754     // Check if any splitting is required.
4755     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4756         TargetLowering::TypeSplitVector)
4757       return SDValue();
4758
4759     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4760     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4761     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4762     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4763
4764     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4765     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4766
4767     // Add the new VSELECT nodes to the work list in case they need to be split
4768     // again.
4769     AddToWorklist(Lo.getNode());
4770     AddToWorklist(Hi.getNode());
4771
4772     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4773   }
4774
4775   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4776   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4777     return N1;
4778   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4779   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4780     return N2;
4781
4782   // The ConvertSelectToConcatVector function is assuming both the above
4783   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4784   // and addressed.
4785   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4786       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4787       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4788     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4789     if (CV.getNode())
4790       return CV;
4791   }
4792
4793   return SDValue();
4794 }
4795
4796 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4797   SDValue N0 = N->getOperand(0);
4798   SDValue N1 = N->getOperand(1);
4799   SDValue N2 = N->getOperand(2);
4800   SDValue N3 = N->getOperand(3);
4801   SDValue N4 = N->getOperand(4);
4802   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4803
4804   // fold select_cc lhs, rhs, x, x, cc -> x
4805   if (N2 == N3)
4806     return N2;
4807
4808   // Determine if the condition we're dealing with is constant
4809   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4810                               N0, N1, CC, SDLoc(N), false);
4811   if (SCC.getNode()) {
4812     AddToWorklist(SCC.getNode());
4813
4814     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4815       if (!SCCC->isNullValue())
4816         return N2;    // cond always true -> true val
4817       else
4818         return N3;    // cond always false -> false val
4819     }
4820
4821     // Fold to a simpler select_cc
4822     if (SCC.getOpcode() == ISD::SETCC)
4823       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4824                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4825                          SCC.getOperand(2));
4826   }
4827
4828   // If we can fold this based on the true/false value, do so.
4829   if (SimplifySelectOps(N, N2, N3))
4830     return SDValue(N, 0);  // Don't revisit N.
4831
4832   // fold select_cc into other things, such as min/max/abs
4833   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4834 }
4835
4836 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4837   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4838                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4839                        SDLoc(N));
4840 }
4841
4842 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4843 // dag node into a ConstantSDNode or a build_vector of constants.
4844 // This function is called by the DAGCombiner when visiting sext/zext/aext
4845 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4846 // Vector extends are not folded if operations are legal; this is to
4847 // avoid introducing illegal build_vector dag nodes.
4848 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4849                                          SelectionDAG &DAG, bool LegalTypes,
4850                                          bool LegalOperations) {
4851   unsigned Opcode = N->getOpcode();
4852   SDValue N0 = N->getOperand(0);
4853   EVT VT = N->getValueType(0);
4854
4855   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4856          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4857
4858   // fold (sext c1) -> c1
4859   // fold (zext c1) -> c1
4860   // fold (aext c1) -> c1
4861   if (isa<ConstantSDNode>(N0))
4862     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4863
4864   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4865   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4866   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4867   EVT SVT = VT.getScalarType();
4868   if (!(VT.isVector() &&
4869       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4870       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4871     return nullptr;
4872
4873   // We can fold this node into a build_vector.
4874   unsigned VTBits = SVT.getSizeInBits();
4875   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4876   unsigned ShAmt = VTBits - EVTBits;
4877   SmallVector<SDValue, 8> Elts;
4878   unsigned NumElts = N0->getNumOperands();
4879   SDLoc DL(N);
4880
4881   for (unsigned i=0; i != NumElts; ++i) {
4882     SDValue Op = N0->getOperand(i);
4883     if (Op->getOpcode() == ISD::UNDEF) {
4884       Elts.push_back(DAG.getUNDEF(SVT));
4885       continue;
4886     }
4887
4888     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4889     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4890     if (Opcode == ISD::SIGN_EXTEND)
4891       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4892                                      SVT));
4893     else
4894       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4895                                      SVT));
4896   }
4897
4898   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4899 }
4900
4901 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4902 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4903 // transformation. Returns true if extension are possible and the above
4904 // mentioned transformation is profitable.
4905 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4906                                     unsigned ExtOpc,
4907                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4908                                     const TargetLowering &TLI) {
4909   bool HasCopyToRegUses = false;
4910   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4911   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4912                             UE = N0.getNode()->use_end();
4913        UI != UE; ++UI) {
4914     SDNode *User = *UI;
4915     if (User == N)
4916       continue;
4917     if (UI.getUse().getResNo() != N0.getResNo())
4918       continue;
4919     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4920     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4921       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4922       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4923         // Sign bits will be lost after a zext.
4924         return false;
4925       bool Add = false;
4926       for (unsigned i = 0; i != 2; ++i) {
4927         SDValue UseOp = User->getOperand(i);
4928         if (UseOp == N0)
4929           continue;
4930         if (!isa<ConstantSDNode>(UseOp))
4931           return false;
4932         Add = true;
4933       }
4934       if (Add)
4935         ExtendNodes.push_back(User);
4936       continue;
4937     }
4938     // If truncates aren't free and there are users we can't
4939     // extend, it isn't worthwhile.
4940     if (!isTruncFree)
4941       return false;
4942     // Remember if this value is live-out.
4943     if (User->getOpcode() == ISD::CopyToReg)
4944       HasCopyToRegUses = true;
4945   }
4946
4947   if (HasCopyToRegUses) {
4948     bool BothLiveOut = false;
4949     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
4950          UI != UE; ++UI) {
4951       SDUse &Use = UI.getUse();
4952       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
4953         BothLiveOut = true;
4954         break;
4955       }
4956     }
4957     if (BothLiveOut)
4958       // Both unextended and extended values are live out. There had better be
4959       // a good reason for the transformation.
4960       return ExtendNodes.size();
4961   }
4962   return true;
4963 }
4964
4965 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
4966                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
4967                                   ISD::NodeType ExtType) {
4968   // Extend SetCC uses if necessary.
4969   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
4970     SDNode *SetCC = SetCCs[i];
4971     SmallVector<SDValue, 4> Ops;
4972
4973     for (unsigned j = 0; j != 2; ++j) {
4974       SDValue SOp = SetCC->getOperand(j);
4975       if (SOp == Trunc)
4976         Ops.push_back(ExtLoad);
4977       else
4978         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
4979     }
4980
4981     Ops.push_back(SetCC->getOperand(2));
4982     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
4983   }
4984 }
4985
4986 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
4987   SDValue N0 = N->getOperand(0);
4988   EVT VT = N->getValueType(0);
4989
4990   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
4991                                               LegalOperations))
4992     return SDValue(Res, 0);
4993
4994   // fold (sext (sext x)) -> (sext x)
4995   // fold (sext (aext x)) -> (sext x)
4996   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
4997     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
4998                        N0.getOperand(0));
4999
5000   if (N0.getOpcode() == ISD::TRUNCATE) {
5001     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5002     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5003     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5004     if (NarrowLoad.getNode()) {
5005       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5006       if (NarrowLoad.getNode() != N0.getNode()) {
5007         CombineTo(N0.getNode(), NarrowLoad);
5008         // CombineTo deleted the truncate, if needed, but not what's under it.
5009         AddToWorklist(oye);
5010       }
5011       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5012     }
5013
5014     // See if the value being truncated is already sign extended.  If so, just
5015     // eliminate the trunc/sext pair.
5016     SDValue Op = N0.getOperand(0);
5017     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5018     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5019     unsigned DestBits = VT.getScalarType().getSizeInBits();
5020     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5021
5022     if (OpBits == DestBits) {
5023       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5024       // bits, it is already ready.
5025       if (NumSignBits > DestBits-MidBits)
5026         return Op;
5027     } else if (OpBits < DestBits) {
5028       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5029       // bits, just sext from i32.
5030       if (NumSignBits > OpBits-MidBits)
5031         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5032     } else {
5033       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5034       // bits, just truncate to i32.
5035       if (NumSignBits > OpBits-MidBits)
5036         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5037     }
5038
5039     // fold (sext (truncate x)) -> (sextinreg x).
5040     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5041                                                  N0.getValueType())) {
5042       if (OpBits < DestBits)
5043         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5044       else if (OpBits > DestBits)
5045         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5046       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5047                          DAG.getValueType(N0.getValueType()));
5048     }
5049   }
5050
5051   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5052   // None of the supported targets knows how to perform load and sign extend
5053   // on vectors in one instruction.  We only perform this transformation on
5054   // scalars.
5055   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5056       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5057       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5058        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5059     bool DoXform = true;
5060     SmallVector<SDNode*, 4> SetCCs;
5061     if (!N0.hasOneUse())
5062       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5063     if (DoXform) {
5064       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5065       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5066                                        LN0->getChain(),
5067                                        LN0->getBasePtr(), N0.getValueType(),
5068                                        LN0->getMemOperand());
5069       CombineTo(N, ExtLoad);
5070       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5071                                   N0.getValueType(), ExtLoad);
5072       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5073       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5074                       ISD::SIGN_EXTEND);
5075       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5076     }
5077   }
5078
5079   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5080   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5081   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5082       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5083     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5084     EVT MemVT = LN0->getMemoryVT();
5085     if ((!LegalOperations && !LN0->isVolatile()) ||
5086         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5087       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5088                                        LN0->getChain(),
5089                                        LN0->getBasePtr(), MemVT,
5090                                        LN0->getMemOperand());
5091       CombineTo(N, ExtLoad);
5092       CombineTo(N0.getNode(),
5093                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5094                             N0.getValueType(), ExtLoad),
5095                 ExtLoad.getValue(1));
5096       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5097     }
5098   }
5099
5100   // fold (sext (and/or/xor (load x), cst)) ->
5101   //      (and/or/xor (sextload x), (sext cst))
5102   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5103        N0.getOpcode() == ISD::XOR) &&
5104       isa<LoadSDNode>(N0.getOperand(0)) &&
5105       N0.getOperand(1).getOpcode() == ISD::Constant &&
5106       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5107       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5108     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5109     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5110       bool DoXform = true;
5111       SmallVector<SDNode*, 4> SetCCs;
5112       if (!N0.hasOneUse())
5113         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5114                                           SetCCs, TLI);
5115       if (DoXform) {
5116         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5117                                          LN0->getChain(), LN0->getBasePtr(),
5118                                          LN0->getMemoryVT(),
5119                                          LN0->getMemOperand());
5120         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5121         Mask = Mask.sext(VT.getSizeInBits());
5122         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5123                                   ExtLoad, DAG.getConstant(Mask, VT));
5124         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5125                                     SDLoc(N0.getOperand(0)),
5126                                     N0.getOperand(0).getValueType(), ExtLoad);
5127         CombineTo(N, And);
5128         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5129         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5130                         ISD::SIGN_EXTEND);
5131         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5132       }
5133     }
5134   }
5135
5136   if (N0.getOpcode() == ISD::SETCC) {
5137     EVT N0VT = N0.getOperand(0).getValueType();
5138     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5139     // Only do this before legalize for now.
5140     if (VT.isVector() && !LegalOperations &&
5141         TLI.getBooleanContents(N0VT) ==
5142             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5143       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5144       // of the same size as the compared operands. Only optimize sext(setcc())
5145       // if this is the case.
5146       EVT SVT = getSetCCResultType(N0VT);
5147
5148       // We know that the # elements of the results is the same as the
5149       // # elements of the compare (and the # elements of the compare result
5150       // for that matter).  Check to see that they are the same size.  If so,
5151       // we know that the element size of the sext'd result matches the
5152       // element size of the compare operands.
5153       if (VT.getSizeInBits() == SVT.getSizeInBits())
5154         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5155                              N0.getOperand(1),
5156                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5157
5158       // If the desired elements are smaller or larger than the source
5159       // elements we can use a matching integer vector type and then
5160       // truncate/sign extend
5161       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5162       if (SVT == MatchingVectorType) {
5163         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5164                                N0.getOperand(0), N0.getOperand(1),
5165                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5166         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5167       }
5168     }
5169
5170     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5171     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5172     SDValue NegOne =
5173       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5174     SDValue SCC =
5175       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5176                        NegOne, DAG.getConstant(0, VT),
5177                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5178     if (SCC.getNode()) return SCC;
5179
5180     if (!VT.isVector()) {
5181       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5182       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5183         SDLoc DL(N);
5184         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5185         SDValue SetCC = DAG.getSetCC(DL,
5186                                      SetCCVT,
5187                                      N0.getOperand(0), N0.getOperand(1), CC);
5188         EVT SelectVT = getSetCCResultType(VT);
5189         return DAG.getSelect(DL, VT,
5190                              DAG.getSExtOrTrunc(SetCC, DL, SelectVT),
5191                              NegOne, DAG.getConstant(0, VT));
5192
5193       }
5194     }
5195   }
5196
5197   // fold (sext x) -> (zext x) if the sign bit is known zero.
5198   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5199       DAG.SignBitIsZero(N0))
5200     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5201
5202   return SDValue();
5203 }
5204
5205 // isTruncateOf - If N is a truncate of some other value, return true, record
5206 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5207 // This function computes KnownZero to avoid a duplicated call to
5208 // computeKnownBits in the caller.
5209 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5210                          APInt &KnownZero) {
5211   APInt KnownOne;
5212   if (N->getOpcode() == ISD::TRUNCATE) {
5213     Op = N->getOperand(0);
5214     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5215     return true;
5216   }
5217
5218   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5219       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5220     return false;
5221
5222   SDValue Op0 = N->getOperand(0);
5223   SDValue Op1 = N->getOperand(1);
5224   assert(Op0.getValueType() == Op1.getValueType());
5225
5226   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5227   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5228   if (COp0 && COp0->isNullValue())
5229     Op = Op1;
5230   else if (COp1 && COp1->isNullValue())
5231     Op = Op0;
5232   else
5233     return false;
5234
5235   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5236
5237   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5238     return false;
5239
5240   return true;
5241 }
5242
5243 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5244   SDValue N0 = N->getOperand(0);
5245   EVT VT = N->getValueType(0);
5246
5247   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5248                                               LegalOperations))
5249     return SDValue(Res, 0);
5250
5251   // fold (zext (zext x)) -> (zext x)
5252   // fold (zext (aext x)) -> (zext x)
5253   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5254     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5255                        N0.getOperand(0));
5256
5257   // fold (zext (truncate x)) -> (zext x) or
5258   //      (zext (truncate x)) -> (truncate x)
5259   // This is valid when the truncated bits of x are already zero.
5260   // FIXME: We should extend this to work for vectors too.
5261   SDValue Op;
5262   APInt KnownZero;
5263   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5264     APInt TruncatedBits =
5265       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5266       APInt(Op.getValueSizeInBits(), 0) :
5267       APInt::getBitsSet(Op.getValueSizeInBits(),
5268                         N0.getValueSizeInBits(),
5269                         std::min(Op.getValueSizeInBits(),
5270                                  VT.getSizeInBits()));
5271     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5272       if (VT.bitsGT(Op.getValueType()))
5273         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5274       if (VT.bitsLT(Op.getValueType()))
5275         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5276
5277       return Op;
5278     }
5279   }
5280
5281   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5282   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5283   if (N0.getOpcode() == ISD::TRUNCATE) {
5284     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5285     if (NarrowLoad.getNode()) {
5286       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5287       if (NarrowLoad.getNode() != N0.getNode()) {
5288         CombineTo(N0.getNode(), NarrowLoad);
5289         // CombineTo deleted the truncate, if needed, but not what's under it.
5290         AddToWorklist(oye);
5291       }
5292       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5293     }
5294   }
5295
5296   // fold (zext (truncate x)) -> (and x, mask)
5297   if (N0.getOpcode() == ISD::TRUNCATE &&
5298       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5299
5300     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5301     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5302     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5303     if (NarrowLoad.getNode()) {
5304       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5305       if (NarrowLoad.getNode() != N0.getNode()) {
5306         CombineTo(N0.getNode(), NarrowLoad);
5307         // CombineTo deleted the truncate, if needed, but not what's under it.
5308         AddToWorklist(oye);
5309       }
5310       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5311     }
5312
5313     SDValue Op = N0.getOperand(0);
5314     if (Op.getValueType().bitsLT(VT)) {
5315       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5316       AddToWorklist(Op.getNode());
5317     } else if (Op.getValueType().bitsGT(VT)) {
5318       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5319       AddToWorklist(Op.getNode());
5320     }
5321     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5322                                   N0.getValueType().getScalarType());
5323   }
5324
5325   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5326   // if either of the casts is not free.
5327   if (N0.getOpcode() == ISD::AND &&
5328       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5329       N0.getOperand(1).getOpcode() == ISD::Constant &&
5330       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5331                            N0.getValueType()) ||
5332        !TLI.isZExtFree(N0.getValueType(), VT))) {
5333     SDValue X = N0.getOperand(0).getOperand(0);
5334     if (X.getValueType().bitsLT(VT)) {
5335       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5336     } else if (X.getValueType().bitsGT(VT)) {
5337       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5338     }
5339     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5340     Mask = Mask.zext(VT.getSizeInBits());
5341     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5342                        X, DAG.getConstant(Mask, VT));
5343   }
5344
5345   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5346   // None of the supported targets knows how to perform load and vector_zext
5347   // on vectors in one instruction.  We only perform this transformation on
5348   // scalars.
5349   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5350       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5351       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5352        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5353     bool DoXform = true;
5354     SmallVector<SDNode*, 4> SetCCs;
5355     if (!N0.hasOneUse())
5356       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5357     if (DoXform) {
5358       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5359       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5360                                        LN0->getChain(),
5361                                        LN0->getBasePtr(), N0.getValueType(),
5362                                        LN0->getMemOperand());
5363       CombineTo(N, ExtLoad);
5364       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5365                                   N0.getValueType(), ExtLoad);
5366       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5367
5368       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5369                       ISD::ZERO_EXTEND);
5370       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5371     }
5372   }
5373
5374   // fold (zext (and/or/xor (load x), cst)) ->
5375   //      (and/or/xor (zextload x), (zext cst))
5376   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5377        N0.getOpcode() == ISD::XOR) &&
5378       isa<LoadSDNode>(N0.getOperand(0)) &&
5379       N0.getOperand(1).getOpcode() == ISD::Constant &&
5380       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5381       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5382     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5383     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5384       bool DoXform = true;
5385       SmallVector<SDNode*, 4> SetCCs;
5386       if (!N0.hasOneUse())
5387         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5388                                           SetCCs, TLI);
5389       if (DoXform) {
5390         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5391                                          LN0->getChain(), LN0->getBasePtr(),
5392                                          LN0->getMemoryVT(),
5393                                          LN0->getMemOperand());
5394         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5395         Mask = Mask.zext(VT.getSizeInBits());
5396         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5397                                   ExtLoad, DAG.getConstant(Mask, VT));
5398         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5399                                     SDLoc(N0.getOperand(0)),
5400                                     N0.getOperand(0).getValueType(), ExtLoad);
5401         CombineTo(N, And);
5402         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5403         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5404                         ISD::ZERO_EXTEND);
5405         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5406       }
5407     }
5408   }
5409
5410   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5411   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5412   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5413       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5414     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5415     EVT MemVT = LN0->getMemoryVT();
5416     if ((!LegalOperations && !LN0->isVolatile()) ||
5417         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5418       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5419                                        LN0->getChain(),
5420                                        LN0->getBasePtr(), MemVT,
5421                                        LN0->getMemOperand());
5422       CombineTo(N, ExtLoad);
5423       CombineTo(N0.getNode(),
5424                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5425                             ExtLoad),
5426                 ExtLoad.getValue(1));
5427       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5428     }
5429   }
5430
5431   if (N0.getOpcode() == ISD::SETCC) {
5432     if (!LegalOperations && VT.isVector() &&
5433         N0.getValueType().getVectorElementType() == MVT::i1) {
5434       EVT N0VT = N0.getOperand(0).getValueType();
5435       if (getSetCCResultType(N0VT) == N0.getValueType())
5436         return SDValue();
5437
5438       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5439       // Only do this before legalize for now.
5440       EVT EltVT = VT.getVectorElementType();
5441       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5442                                     DAG.getConstant(1, EltVT));
5443       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5444         // We know that the # elements of the results is the same as the
5445         // # elements of the compare (and the # elements of the compare result
5446         // for that matter).  Check to see that they are the same size.  If so,
5447         // we know that the element size of the sext'd result matches the
5448         // element size of the compare operands.
5449         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5450                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5451                                          N0.getOperand(1),
5452                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5453                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5454                                        OneOps));
5455
5456       // If the desired elements are smaller or larger than the source
5457       // elements we can use a matching integer vector type and then
5458       // truncate/sign extend
5459       EVT MatchingElementType =
5460         EVT::getIntegerVT(*DAG.getContext(),
5461                           N0VT.getScalarType().getSizeInBits());
5462       EVT MatchingVectorType =
5463         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5464                          N0VT.getVectorNumElements());
5465       SDValue VsetCC =
5466         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5467                       N0.getOperand(1),
5468                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5469       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5470                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5471                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5472     }
5473
5474     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5475     SDValue SCC =
5476       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5477                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5478                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5479     if (SCC.getNode()) return SCC;
5480   }
5481
5482   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5483   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5484       isa<ConstantSDNode>(N0.getOperand(1)) &&
5485       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5486       N0.hasOneUse()) {
5487     SDValue ShAmt = N0.getOperand(1);
5488     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5489     if (N0.getOpcode() == ISD::SHL) {
5490       SDValue InnerZExt = N0.getOperand(0);
5491       // If the original shl may be shifting out bits, do not perform this
5492       // transformation.
5493       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5494         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5495       if (ShAmtVal > KnownZeroBits)
5496         return SDValue();
5497     }
5498
5499     SDLoc DL(N);
5500
5501     // Ensure that the shift amount is wide enough for the shifted value.
5502     if (VT.getSizeInBits() >= 256)
5503       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5504
5505     return DAG.getNode(N0.getOpcode(), DL, VT,
5506                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5507                        ShAmt);
5508   }
5509
5510   return SDValue();
5511 }
5512
5513 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5514   SDValue N0 = N->getOperand(0);
5515   EVT VT = N->getValueType(0);
5516
5517   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5518                                               LegalOperations))
5519     return SDValue(Res, 0);
5520
5521   // fold (aext (aext x)) -> (aext x)
5522   // fold (aext (zext x)) -> (zext x)
5523   // fold (aext (sext x)) -> (sext x)
5524   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5525       N0.getOpcode() == ISD::ZERO_EXTEND ||
5526       N0.getOpcode() == ISD::SIGN_EXTEND)
5527     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5528
5529   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5530   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5531   if (N0.getOpcode() == ISD::TRUNCATE) {
5532     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5533     if (NarrowLoad.getNode()) {
5534       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5535       if (NarrowLoad.getNode() != N0.getNode()) {
5536         CombineTo(N0.getNode(), NarrowLoad);
5537         // CombineTo deleted the truncate, if needed, but not what's under it.
5538         AddToWorklist(oye);
5539       }
5540       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5541     }
5542   }
5543
5544   // fold (aext (truncate x))
5545   if (N0.getOpcode() == ISD::TRUNCATE) {
5546     SDValue TruncOp = N0.getOperand(0);
5547     if (TruncOp.getValueType() == VT)
5548       return TruncOp; // x iff x size == zext size.
5549     if (TruncOp.getValueType().bitsGT(VT))
5550       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5551     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5552   }
5553
5554   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5555   // if the trunc is not free.
5556   if (N0.getOpcode() == ISD::AND &&
5557       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5558       N0.getOperand(1).getOpcode() == ISD::Constant &&
5559       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5560                           N0.getValueType())) {
5561     SDValue X = N0.getOperand(0).getOperand(0);
5562     if (X.getValueType().bitsLT(VT)) {
5563       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5564     } else if (X.getValueType().bitsGT(VT)) {
5565       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5566     }
5567     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5568     Mask = Mask.zext(VT.getSizeInBits());
5569     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5570                        X, DAG.getConstant(Mask, VT));
5571   }
5572
5573   // fold (aext (load x)) -> (aext (truncate (extload x)))
5574   // None of the supported targets knows how to perform load and any_ext
5575   // on vectors in one instruction.  We only perform this transformation on
5576   // scalars.
5577   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5578       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5579       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5580     bool DoXform = true;
5581     SmallVector<SDNode*, 4> SetCCs;
5582     if (!N0.hasOneUse())
5583       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5584     if (DoXform) {
5585       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5586       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5587                                        LN0->getChain(),
5588                                        LN0->getBasePtr(), N0.getValueType(),
5589                                        LN0->getMemOperand());
5590       CombineTo(N, ExtLoad);
5591       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5592                                   N0.getValueType(), ExtLoad);
5593       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5594       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5595                       ISD::ANY_EXTEND);
5596       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5597     }
5598   }
5599
5600   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5601   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5602   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5603   if (N0.getOpcode() == ISD::LOAD &&
5604       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5605       N0.hasOneUse()) {
5606     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5607     ISD::LoadExtType ExtType = LN0->getExtensionType();
5608     EVT MemVT = LN0->getMemoryVT();
5609     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5610       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5611                                        VT, LN0->getChain(), LN0->getBasePtr(),
5612                                        MemVT, LN0->getMemOperand());
5613       CombineTo(N, ExtLoad);
5614       CombineTo(N0.getNode(),
5615                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5616                             N0.getValueType(), ExtLoad),
5617                 ExtLoad.getValue(1));
5618       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5619     }
5620   }
5621
5622   if (N0.getOpcode() == ISD::SETCC) {
5623     // For vectors:
5624     // aext(setcc) -> vsetcc
5625     // aext(setcc) -> truncate(vsetcc)
5626     // aext(setcc) -> aext(vsetcc)
5627     // Only do this before legalize for now.
5628     if (VT.isVector() && !LegalOperations) {
5629       EVT N0VT = N0.getOperand(0).getValueType();
5630         // We know that the # elements of the results is the same as the
5631         // # elements of the compare (and the # elements of the compare result
5632         // for that matter).  Check to see that they are the same size.  If so,
5633         // we know that the element size of the sext'd result matches the
5634         // element size of the compare operands.
5635       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5636         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5637                              N0.getOperand(1),
5638                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5639       // If the desired elements are smaller or larger than the source
5640       // elements we can use a matching integer vector type and then
5641       // truncate/any extend
5642       else {
5643         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5644         SDValue VsetCC =
5645           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5646                         N0.getOperand(1),
5647                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5648         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5649       }
5650     }
5651
5652     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5653     SDValue SCC =
5654       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5655                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5656                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5657     if (SCC.getNode())
5658       return SCC;
5659   }
5660
5661   return SDValue();
5662 }
5663
5664 /// GetDemandedBits - See if the specified operand can be simplified with the
5665 /// knowledge that only the bits specified by Mask are used.  If so, return the
5666 /// simpler operand, otherwise return a null SDValue.
5667 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5668   switch (V.getOpcode()) {
5669   default: break;
5670   case ISD::Constant: {
5671     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5672     assert(CV && "Const value should be ConstSDNode.");
5673     const APInt &CVal = CV->getAPIntValue();
5674     APInt NewVal = CVal & Mask;
5675     if (NewVal != CVal)
5676       return DAG.getConstant(NewVal, V.getValueType());
5677     break;
5678   }
5679   case ISD::OR:
5680   case ISD::XOR:
5681     // If the LHS or RHS don't contribute bits to the or, drop them.
5682     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5683       return V.getOperand(1);
5684     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5685       return V.getOperand(0);
5686     break;
5687   case ISD::SRL:
5688     // Only look at single-use SRLs.
5689     if (!V.getNode()->hasOneUse())
5690       break;
5691     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5692       // See if we can recursively simplify the LHS.
5693       unsigned Amt = RHSC->getZExtValue();
5694
5695       // Watch out for shift count overflow though.
5696       if (Amt >= Mask.getBitWidth()) break;
5697       APInt NewMask = Mask << Amt;
5698       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5699       if (SimplifyLHS.getNode())
5700         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5701                            SimplifyLHS, V.getOperand(1));
5702     }
5703   }
5704   return SDValue();
5705 }
5706
5707 /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
5708 /// bits and then truncated to a narrower type and where N is a multiple
5709 /// of number of bits of the narrower type, transform it to a narrower load
5710 /// from address + N / num of bits of new type. If the result is to be
5711 /// extended, also fold the extension to form a extending load.
5712 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5713   unsigned Opc = N->getOpcode();
5714
5715   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5716   SDValue N0 = N->getOperand(0);
5717   EVT VT = N->getValueType(0);
5718   EVT ExtVT = VT;
5719
5720   // This transformation isn't valid for vector loads.
5721   if (VT.isVector())
5722     return SDValue();
5723
5724   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5725   // extended to VT.
5726   if (Opc == ISD::SIGN_EXTEND_INREG) {
5727     ExtType = ISD::SEXTLOAD;
5728     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5729   } else if (Opc == ISD::SRL) {
5730     // Another special-case: SRL is basically zero-extending a narrower value.
5731     ExtType = ISD::ZEXTLOAD;
5732     N0 = SDValue(N, 0);
5733     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5734     if (!N01) return SDValue();
5735     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5736                               VT.getSizeInBits() - N01->getZExtValue());
5737   }
5738   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5739     return SDValue();
5740
5741   unsigned EVTBits = ExtVT.getSizeInBits();
5742
5743   // Do not generate loads of non-round integer types since these can
5744   // be expensive (and would be wrong if the type is not byte sized).
5745   if (!ExtVT.isRound())
5746     return SDValue();
5747
5748   unsigned ShAmt = 0;
5749   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5750     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5751       ShAmt = N01->getZExtValue();
5752       // Is the shift amount a multiple of size of VT?
5753       if ((ShAmt & (EVTBits-1)) == 0) {
5754         N0 = N0.getOperand(0);
5755         // Is the load width a multiple of size of VT?
5756         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5757           return SDValue();
5758       }
5759
5760       // At this point, we must have a load or else we can't do the transform.
5761       if (!isa<LoadSDNode>(N0)) return SDValue();
5762
5763       // Because a SRL must be assumed to *need* to zero-extend the high bits
5764       // (as opposed to anyext the high bits), we can't combine the zextload
5765       // lowering of SRL and an sextload.
5766       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5767         return SDValue();
5768
5769       // If the shift amount is larger than the input type then we're not
5770       // accessing any of the loaded bytes.  If the load was a zextload/extload
5771       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5772       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5773         return SDValue();
5774     }
5775   }
5776
5777   // If the load is shifted left (and the result isn't shifted back right),
5778   // we can fold the truncate through the shift.
5779   unsigned ShLeftAmt = 0;
5780   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5781       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5782     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5783       ShLeftAmt = N01->getZExtValue();
5784       N0 = N0.getOperand(0);
5785     }
5786   }
5787
5788   // If we haven't found a load, we can't narrow it.  Don't transform one with
5789   // multiple uses, this would require adding a new load.
5790   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5791     return SDValue();
5792
5793   // Don't change the width of a volatile load.
5794   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5795   if (LN0->isVolatile())
5796     return SDValue();
5797
5798   // Verify that we are actually reducing a load width here.
5799   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5800     return SDValue();
5801
5802   // For the transform to be legal, the load must produce only two values
5803   // (the value loaded and the chain).  Don't transform a pre-increment
5804   // load, for example, which produces an extra value.  Otherwise the
5805   // transformation is not equivalent, and the downstream logic to replace
5806   // uses gets things wrong.
5807   if (LN0->getNumValues() > 2)
5808     return SDValue();
5809
5810   // If the load that we're shrinking is an extload and we're not just
5811   // discarding the extension we can't simply shrink the load. Bail.
5812   // TODO: It would be possible to merge the extensions in some cases.
5813   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5814       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5815     return SDValue();
5816
5817   EVT PtrType = N0.getOperand(1).getValueType();
5818
5819   if (PtrType == MVT::Untyped || PtrType.isExtended())
5820     // It's not possible to generate a constant of extended or untyped type.
5821     return SDValue();
5822
5823   // For big endian targets, we need to adjust the offset to the pointer to
5824   // load the correct bytes.
5825   if (TLI.isBigEndian()) {
5826     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5827     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5828     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5829   }
5830
5831   uint64_t PtrOff = ShAmt / 8;
5832   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5833   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5834                                PtrType, LN0->getBasePtr(),
5835                                DAG.getConstant(PtrOff, PtrType));
5836   AddToWorklist(NewPtr.getNode());
5837
5838   SDValue Load;
5839   if (ExtType == ISD::NON_EXTLOAD)
5840     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5841                         LN0->getPointerInfo().getWithOffset(PtrOff),
5842                         LN0->isVolatile(), LN0->isNonTemporal(),
5843                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5844   else
5845     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5846                           LN0->getPointerInfo().getWithOffset(PtrOff),
5847                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5848                           NewAlign, LN0->getAAInfo());
5849
5850   // Replace the old load's chain with the new load's chain.
5851   WorklistRemover DeadNodes(*this);
5852   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5853
5854   // Shift the result left, if we've swallowed a left shift.
5855   SDValue Result = Load;
5856   if (ShLeftAmt != 0) {
5857     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5858     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5859       ShImmTy = VT;
5860     // If the shift amount is as large as the result size (but, presumably,
5861     // no larger than the source) then the useful bits of the result are
5862     // zero; we can't simply return the shortened shift, because the result
5863     // of that operation is undefined.
5864     if (ShLeftAmt >= VT.getSizeInBits())
5865       Result = DAG.getConstant(0, VT);
5866     else
5867       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5868                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5869   }
5870
5871   // Return the new loaded value.
5872   return Result;
5873 }
5874
5875 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5876   SDValue N0 = N->getOperand(0);
5877   SDValue N1 = N->getOperand(1);
5878   EVT VT = N->getValueType(0);
5879   EVT EVT = cast<VTSDNode>(N1)->getVT();
5880   unsigned VTBits = VT.getScalarType().getSizeInBits();
5881   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5882
5883   // fold (sext_in_reg c1) -> c1
5884   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5885     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5886
5887   // If the input is already sign extended, just drop the extension.
5888   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5889     return N0;
5890
5891   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5892   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5893       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5894     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5895                        N0.getOperand(0), N1);
5896
5897   // fold (sext_in_reg (sext x)) -> (sext x)
5898   // fold (sext_in_reg (aext x)) -> (sext x)
5899   // if x is small enough.
5900   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5901     SDValue N00 = N0.getOperand(0);
5902     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5903         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5904       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5905   }
5906
5907   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5908   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5909     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5910
5911   // fold operands of sext_in_reg based on knowledge that the top bits are not
5912   // demanded.
5913   if (SimplifyDemandedBits(SDValue(N, 0)))
5914     return SDValue(N, 0);
5915
5916   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5917   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5918   SDValue NarrowLoad = ReduceLoadWidth(N);
5919   if (NarrowLoad.getNode())
5920     return NarrowLoad;
5921
5922   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5923   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5924   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5925   if (N0.getOpcode() == ISD::SRL) {
5926     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5927       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5928         // We can turn this into an SRA iff the input to the SRL is already sign
5929         // extended enough.
5930         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5931         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5932           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5933                              N0.getOperand(0), N0.getOperand(1));
5934       }
5935   }
5936
5937   // fold (sext_inreg (extload x)) -> (sextload x)
5938   if (ISD::isEXTLoad(N0.getNode()) &&
5939       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5940       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5941       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5942        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5943     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5944     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5945                                      LN0->getChain(),
5946                                      LN0->getBasePtr(), EVT,
5947                                      LN0->getMemOperand());
5948     CombineTo(N, ExtLoad);
5949     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5950     AddToWorklist(ExtLoad.getNode());
5951     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5952   }
5953   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
5954   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5955       N0.hasOneUse() &&
5956       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
5957       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5958        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
5959     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5960     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5961                                      LN0->getChain(),
5962                                      LN0->getBasePtr(), EVT,
5963                                      LN0->getMemOperand());
5964     CombineTo(N, ExtLoad);
5965     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
5966     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5967   }
5968
5969   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
5970   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
5971     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
5972                                        N0.getOperand(1), false);
5973     if (BSwap.getNode())
5974       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5975                          BSwap, N1);
5976   }
5977
5978   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
5979   // into a build_vector.
5980   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5981     SmallVector<SDValue, 8> Elts;
5982     unsigned NumElts = N0->getNumOperands();
5983     unsigned ShAmt = VTBits - EVTBits;
5984
5985     for (unsigned i = 0; i != NumElts; ++i) {
5986       SDValue Op = N0->getOperand(i);
5987       if (Op->getOpcode() == ISD::UNDEF) {
5988         Elts.push_back(Op);
5989         continue;
5990       }
5991
5992       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5993       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5994       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5995                                      Op.getValueType()));
5996     }
5997
5998     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
5999   }
6000
6001   return SDValue();
6002 }
6003
6004 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6005   SDValue N0 = N->getOperand(0);
6006   EVT VT = N->getValueType(0);
6007   bool isLE = TLI.isLittleEndian();
6008
6009   // noop truncate
6010   if (N0.getValueType() == N->getValueType(0))
6011     return N0;
6012   // fold (truncate c1) -> c1
6013   if (isa<ConstantSDNode>(N0))
6014     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6015   // fold (truncate (truncate x)) -> (truncate x)
6016   if (N0.getOpcode() == ISD::TRUNCATE)
6017     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6018   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6019   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6020       N0.getOpcode() == ISD::SIGN_EXTEND ||
6021       N0.getOpcode() == ISD::ANY_EXTEND) {
6022     if (N0.getOperand(0).getValueType().bitsLT(VT))
6023       // if the source is smaller than the dest, we still need an extend
6024       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6025                          N0.getOperand(0));
6026     if (N0.getOperand(0).getValueType().bitsGT(VT))
6027       // if the source is larger than the dest, than we just need the truncate
6028       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6029     // if the source and dest are the same type, we can drop both the extend
6030     // and the truncate.
6031     return N0.getOperand(0);
6032   }
6033
6034   // Fold extract-and-trunc into a narrow extract. For example:
6035   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6036   //   i32 y = TRUNCATE(i64 x)
6037   //        -- becomes --
6038   //   v16i8 b = BITCAST (v2i64 val)
6039   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6040   //
6041   // Note: We only run this optimization after type legalization (which often
6042   // creates this pattern) and before operation legalization after which
6043   // we need to be more careful about the vector instructions that we generate.
6044   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6045       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6046
6047     EVT VecTy = N0.getOperand(0).getValueType();
6048     EVT ExTy = N0.getValueType();
6049     EVT TrTy = N->getValueType(0);
6050
6051     unsigned NumElem = VecTy.getVectorNumElements();
6052     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6053
6054     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6055     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6056
6057     SDValue EltNo = N0->getOperand(1);
6058     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6059       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6060       EVT IndexTy = TLI.getVectorIdxTy();
6061       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6062
6063       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6064                               NVT, N0.getOperand(0));
6065
6066       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6067                          SDLoc(N), TrTy, V,
6068                          DAG.getConstant(Index, IndexTy));
6069     }
6070   }
6071
6072   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6073   if (N0.getOpcode() == ISD::SELECT) {
6074     EVT SrcVT = N0.getValueType();
6075     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6076         TLI.isTruncateFree(SrcVT, VT)) {
6077       SDLoc SL(N0);
6078       SDValue Cond = N0.getOperand(0);
6079       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6080       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6081       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6082     }
6083   }
6084
6085   // Fold a series of buildvector, bitcast, and truncate if possible.
6086   // For example fold
6087   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6088   //   (2xi32 (buildvector x, y)).
6089   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6090       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6091       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6092       N0.getOperand(0).hasOneUse()) {
6093
6094     SDValue BuildVect = N0.getOperand(0);
6095     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6096     EVT TruncVecEltTy = VT.getVectorElementType();
6097
6098     // Check that the element types match.
6099     if (BuildVectEltTy == TruncVecEltTy) {
6100       // Now we only need to compute the offset of the truncated elements.
6101       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6102       unsigned TruncVecNumElts = VT.getVectorNumElements();
6103       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6104
6105       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6106              "Invalid number of elements");
6107
6108       SmallVector<SDValue, 8> Opnds;
6109       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6110         Opnds.push_back(BuildVect.getOperand(i));
6111
6112       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6113     }
6114   }
6115
6116   // See if we can simplify the input to this truncate through knowledge that
6117   // only the low bits are being used.
6118   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6119   // Currently we only perform this optimization on scalars because vectors
6120   // may have different active low bits.
6121   if (!VT.isVector()) {
6122     SDValue Shorter =
6123       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6124                                                VT.getSizeInBits()));
6125     if (Shorter.getNode())
6126       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6127   }
6128   // fold (truncate (load x)) -> (smaller load x)
6129   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6130   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6131     SDValue Reduced = ReduceLoadWidth(N);
6132     if (Reduced.getNode())
6133       return Reduced;
6134     // Handle the case where the load remains an extending load even
6135     // after truncation.
6136     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6137       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6138       if (!LN0->isVolatile() &&
6139           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6140         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6141                                          VT, LN0->getChain(), LN0->getBasePtr(),
6142                                          LN0->getMemoryVT(),
6143                                          LN0->getMemOperand());
6144         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6145         return NewLoad;
6146       }
6147     }
6148   }
6149   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6150   // where ... are all 'undef'.
6151   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6152     SmallVector<EVT, 8> VTs;
6153     SDValue V;
6154     unsigned Idx = 0;
6155     unsigned NumDefs = 0;
6156
6157     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6158       SDValue X = N0.getOperand(i);
6159       if (X.getOpcode() != ISD::UNDEF) {
6160         V = X;
6161         Idx = i;
6162         NumDefs++;
6163       }
6164       // Stop if more than one members are non-undef.
6165       if (NumDefs > 1)
6166         break;
6167       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6168                                      VT.getVectorElementType(),
6169                                      X.getValueType().getVectorNumElements()));
6170     }
6171
6172     if (NumDefs == 0)
6173       return DAG.getUNDEF(VT);
6174
6175     if (NumDefs == 1) {
6176       assert(V.getNode() && "The single defined operand is empty!");
6177       SmallVector<SDValue, 8> Opnds;
6178       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6179         if (i != Idx) {
6180           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6181           continue;
6182         }
6183         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6184         AddToWorklist(NV.getNode());
6185         Opnds.push_back(NV);
6186       }
6187       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6188     }
6189   }
6190
6191   // Simplify the operands using demanded-bits information.
6192   if (!VT.isVector() &&
6193       SimplifyDemandedBits(SDValue(N, 0)))
6194     return SDValue(N, 0);
6195
6196   return SDValue();
6197 }
6198
6199 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6200   SDValue Elt = N->getOperand(i);
6201   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6202     return Elt.getNode();
6203   return Elt.getOperand(Elt.getResNo()).getNode();
6204 }
6205
6206 /// CombineConsecutiveLoads - build_pair (load, load) -> load
6207 /// if load locations are consecutive.
6208 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6209   assert(N->getOpcode() == ISD::BUILD_PAIR);
6210
6211   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6212   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6213   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6214       LD1->getAddressSpace() != LD2->getAddressSpace())
6215     return SDValue();
6216   EVT LD1VT = LD1->getValueType(0);
6217
6218   if (ISD::isNON_EXTLoad(LD2) &&
6219       LD2->hasOneUse() &&
6220       // If both are volatile this would reduce the number of volatile loads.
6221       // If one is volatile it might be ok, but play conservative and bail out.
6222       !LD1->isVolatile() &&
6223       !LD2->isVolatile() &&
6224       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6225     unsigned Align = LD1->getAlignment();
6226     unsigned NewAlign = TLI.getDataLayout()->
6227       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6228
6229     if (NewAlign <= Align &&
6230         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6231       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6232                          LD1->getBasePtr(), LD1->getPointerInfo(),
6233                          false, false, false, Align);
6234   }
6235
6236   return SDValue();
6237 }
6238
6239 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6240   SDValue N0 = N->getOperand(0);
6241   EVT VT = N->getValueType(0);
6242
6243   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6244   // Only do this before legalize, since afterward the target may be depending
6245   // on the bitconvert.
6246   // First check to see if this is all constant.
6247   if (!LegalTypes &&
6248       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6249       VT.isVector()) {
6250     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6251
6252     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6253     assert(!DestEltVT.isVector() &&
6254            "Element type of vector ValueType must not be vector!");
6255     if (isSimple)
6256       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6257   }
6258
6259   // If the input is a constant, let getNode fold it.
6260   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6261     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6262     if (Res.getNode() != N) {
6263       if (!LegalOperations ||
6264           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6265         return Res;
6266
6267       // Folding it resulted in an illegal node, and it's too late to
6268       // do that. Clean up the old node and forego the transformation.
6269       // Ideally this won't happen very often, because instcombine
6270       // and the earlier dagcombine runs (where illegal nodes are
6271       // permitted) should have folded most of them already.
6272       DAG.DeleteNode(Res.getNode());
6273     }
6274   }
6275
6276   // (conv (conv x, t1), t2) -> (conv x, t2)
6277   if (N0.getOpcode() == ISD::BITCAST)
6278     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6279                        N0.getOperand(0));
6280
6281   // fold (conv (load x)) -> (load (conv*)x)
6282   // If the resultant load doesn't need a higher alignment than the original!
6283   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6284       // Do not change the width of a volatile load.
6285       !cast<LoadSDNode>(N0)->isVolatile() &&
6286       // Do not remove the cast if the types differ in endian layout.
6287       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6288       TLI.hasBigEndianPartOrdering(VT) &&
6289       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6290       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6291     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6292     unsigned Align = TLI.getDataLayout()->
6293       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6294     unsigned OrigAlign = LN0->getAlignment();
6295
6296     if (Align <= OrigAlign) {
6297       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6298                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6299                                  LN0->isVolatile(), LN0->isNonTemporal(),
6300                                  LN0->isInvariant(), OrigAlign,
6301                                  LN0->getAAInfo());
6302       AddToWorklist(N);
6303       CombineTo(N0.getNode(),
6304                 DAG.getNode(ISD::BITCAST, SDLoc(N0),
6305                             N0.getValueType(), Load),
6306                 Load.getValue(1));
6307       return Load;
6308     }
6309   }
6310
6311   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6312   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6313   // This often reduces constant pool loads.
6314   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6315        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6316       N0.getNode()->hasOneUse() && VT.isInteger() &&
6317       !VT.isVector() && !N0.getValueType().isVector()) {
6318     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6319                                   N0.getOperand(0));
6320     AddToWorklist(NewConv.getNode());
6321
6322     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6323     if (N0.getOpcode() == ISD::FNEG)
6324       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6325                          NewConv, DAG.getConstant(SignBit, VT));
6326     assert(N0.getOpcode() == ISD::FABS);
6327     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6328                        NewConv, DAG.getConstant(~SignBit, VT));
6329   }
6330
6331   // fold (bitconvert (fcopysign cst, x)) ->
6332   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6333   // Note that we don't handle (copysign x, cst) because this can always be
6334   // folded to an fneg or fabs.
6335   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6336       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6337       VT.isInteger() && !VT.isVector()) {
6338     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6339     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6340     if (isTypeLegal(IntXVT)) {
6341       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6342                               IntXVT, N0.getOperand(1));
6343       AddToWorklist(X.getNode());
6344
6345       // If X has a different width than the result/lhs, sext it or truncate it.
6346       unsigned VTWidth = VT.getSizeInBits();
6347       if (OrigXWidth < VTWidth) {
6348         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6349         AddToWorklist(X.getNode());
6350       } else if (OrigXWidth > VTWidth) {
6351         // To get the sign bit in the right place, we have to shift it right
6352         // before truncating.
6353         X = DAG.getNode(ISD::SRL, SDLoc(X),
6354                         X.getValueType(), X,
6355                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6356         AddToWorklist(X.getNode());
6357         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6358         AddToWorklist(X.getNode());
6359       }
6360
6361       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6362       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6363                       X, DAG.getConstant(SignBit, VT));
6364       AddToWorklist(X.getNode());
6365
6366       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6367                                 VT, N0.getOperand(0));
6368       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6369                         Cst, DAG.getConstant(~SignBit, VT));
6370       AddToWorklist(Cst.getNode());
6371
6372       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6373     }
6374   }
6375
6376   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6377   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6378     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6379     if (CombineLD.getNode())
6380       return CombineLD;
6381   }
6382
6383   return SDValue();
6384 }
6385
6386 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6387   EVT VT = N->getValueType(0);
6388   return CombineConsecutiveLoads(N, VT);
6389 }
6390
6391 /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
6392 /// node with Constant, ConstantFP or Undef operands.  DstEltVT indicates the
6393 /// destination element value type.
6394 SDValue DAGCombiner::
6395 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6396   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6397
6398   // If this is already the right type, we're done.
6399   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6400
6401   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6402   unsigned DstBitSize = DstEltVT.getSizeInBits();
6403
6404   // If this is a conversion of N elements of one type to N elements of another
6405   // type, convert each element.  This handles FP<->INT cases.
6406   if (SrcBitSize == DstBitSize) {
6407     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6408                               BV->getValueType(0).getVectorNumElements());
6409
6410     // Due to the FP element handling below calling this routine recursively,
6411     // we can end up with a scalar-to-vector node here.
6412     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6413       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6414                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6415                                      DstEltVT, BV->getOperand(0)));
6416
6417     SmallVector<SDValue, 8> Ops;
6418     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6419       SDValue Op = BV->getOperand(i);
6420       // If the vector element type is not legal, the BUILD_VECTOR operands
6421       // are promoted and implicitly truncated.  Make that explicit here.
6422       if (Op.getValueType() != SrcEltVT)
6423         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6424       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6425                                 DstEltVT, Op));
6426       AddToWorklist(Ops.back().getNode());
6427     }
6428     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6429   }
6430
6431   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6432   // handle annoying details of growing/shrinking FP values, we convert them to
6433   // int first.
6434   if (SrcEltVT.isFloatingPoint()) {
6435     // Convert the input float vector to a int vector where the elements are the
6436     // same sizes.
6437     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6438     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6439     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6440     SrcEltVT = IntVT;
6441   }
6442
6443   // Now we know the input is an integer vector.  If the output is a FP type,
6444   // convert to integer first, then to FP of the right size.
6445   if (DstEltVT.isFloatingPoint()) {
6446     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6447     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6448     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6449
6450     // Next, convert to FP elements of the same size.
6451     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6452   }
6453
6454   // Okay, we know the src/dst types are both integers of differing types.
6455   // Handling growing first.
6456   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6457   if (SrcBitSize < DstBitSize) {
6458     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6459
6460     SmallVector<SDValue, 8> Ops;
6461     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6462          i += NumInputsPerOutput) {
6463       bool isLE = TLI.isLittleEndian();
6464       APInt NewBits = APInt(DstBitSize, 0);
6465       bool EltIsUndef = true;
6466       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6467         // Shift the previously computed bits over.
6468         NewBits <<= SrcBitSize;
6469         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6470         if (Op.getOpcode() == ISD::UNDEF) continue;
6471         EltIsUndef = false;
6472
6473         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6474                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6475       }
6476
6477       if (EltIsUndef)
6478         Ops.push_back(DAG.getUNDEF(DstEltVT));
6479       else
6480         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6481     }
6482
6483     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6484     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6485   }
6486
6487   // Finally, this must be the case where we are shrinking elements: each input
6488   // turns into multiple outputs.
6489   bool isS2V = ISD::isScalarToVector(BV);
6490   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6491   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6492                             NumOutputsPerInput*BV->getNumOperands());
6493   SmallVector<SDValue, 8> Ops;
6494
6495   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6496     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6497       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6498         Ops.push_back(DAG.getUNDEF(DstEltVT));
6499       continue;
6500     }
6501
6502     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6503                   getAPIntValue().zextOrTrunc(SrcBitSize);
6504
6505     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6506       APInt ThisVal = OpVal.trunc(DstBitSize);
6507       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6508       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6509         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6510         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6511                            Ops[0]);
6512       OpVal = OpVal.lshr(DstBitSize);
6513     }
6514
6515     // For big endian targets, swap the order of the pieces of each element.
6516     if (TLI.isBigEndian())
6517       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6518   }
6519
6520   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6521 }
6522
6523 SDValue DAGCombiner::visitFADD(SDNode *N) {
6524   SDValue N0 = N->getOperand(0);
6525   SDValue N1 = N->getOperand(1);
6526   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6527   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6528   EVT VT = N->getValueType(0);
6529
6530   // fold vector ops
6531   if (VT.isVector()) {
6532     SDValue FoldedVOp = SimplifyVBinOp(N);
6533     if (FoldedVOp.getNode()) return FoldedVOp;
6534   }
6535
6536   // fold (fadd c1, c2) -> c1 + c2
6537   if (N0CFP && N1CFP)
6538     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6539   // canonicalize constant to RHS
6540   if (N0CFP && !N1CFP)
6541     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6542   // fold (fadd A, 0) -> A
6543   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6544       N1CFP->getValueAPF().isZero())
6545     return N0;
6546   // fold (fadd A, (fneg B)) -> (fsub A, B)
6547   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6548     isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6549     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6550                        GetNegatedExpression(N1, DAG, LegalOperations));
6551   // fold (fadd (fneg A), B) -> (fsub B, A)
6552   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6553     isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
6554     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6555                        GetNegatedExpression(N0, DAG, LegalOperations));
6556
6557   // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6558   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6559       N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6560       isa<ConstantFPSDNode>(N0.getOperand(1)))
6561     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6562                        DAG.getNode(ISD::FADD, SDLoc(N), VT,
6563                                    N0.getOperand(1), N1));
6564
6565   // No FP constant should be created after legalization as Instruction
6566   // Selection pass has hard time in dealing with FP constant.
6567   //
6568   // We don't need test this condition for transformation like following, as
6569   // the DAG being transformed implies it is legal to take FP constant as
6570   // operand.
6571   //
6572   //  (fadd (fmul c, x), x) -> (fmul c+1, x)
6573   //
6574   bool AllowNewFpConst = (Level < AfterLegalizeDAG);
6575
6576   // If allow, fold (fadd (fneg x), x) -> 0.0
6577   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6578       N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6579     return DAG.getConstantFP(0.0, VT);
6580
6581     // If allow, fold (fadd x, (fneg x)) -> 0.0
6582   if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
6583       N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6584     return DAG.getConstantFP(0.0, VT);
6585
6586   // In unsafe math mode, we can fold chains of FADD's of the same value
6587   // into multiplications.  This transform is not safe in general because
6588   // we are reducing the number of rounding steps.
6589   if (DAG.getTarget().Options.UnsafeFPMath &&
6590       TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
6591       !N0CFP && !N1CFP) {
6592     if (N0.getOpcode() == ISD::FMUL) {
6593       ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6594       ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6595
6596       // (fadd (fmul c, x), x) -> (fmul x, c+1)
6597       if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
6598         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6599                                      SDValue(CFP00, 0),
6600                                      DAG.getConstantFP(1.0, VT));
6601         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6602                            N1, NewCFP);
6603       }
6604
6605       // (fadd (fmul x, c), x) -> (fmul x, c+1)
6606       if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6607         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6608                                      SDValue(CFP01, 0),
6609                                      DAG.getConstantFP(1.0, VT));
6610         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6611                            N1, NewCFP);
6612       }
6613
6614       // (fadd (fmul c, x), (fadd x, x)) -> (fmul x, c+2)
6615       if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
6616           N1.getOperand(0) == N1.getOperand(1) &&
6617           N0.getOperand(1) == N1.getOperand(0)) {
6618         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6619                                      SDValue(CFP00, 0),
6620                                      DAG.getConstantFP(2.0, VT));
6621         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6622                            N0.getOperand(1), NewCFP);
6623       }
6624
6625       // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6626       if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6627           N1.getOperand(0) == N1.getOperand(1) &&
6628           N0.getOperand(0) == N1.getOperand(0)) {
6629         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6630                                      SDValue(CFP01, 0),
6631                                      DAG.getConstantFP(2.0, VT));
6632         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6633                            N0.getOperand(0), NewCFP);
6634       }
6635     }
6636
6637     if (N1.getOpcode() == ISD::FMUL) {
6638       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6639       ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6640
6641       // (fadd x, (fmul c, x)) -> (fmul x, c+1)
6642       if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
6643         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6644                                      SDValue(CFP10, 0),
6645                                      DAG.getConstantFP(1.0, VT));
6646         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6647                            N0, NewCFP);
6648       }
6649
6650       // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6651       if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6652         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6653                                      SDValue(CFP11, 0),
6654                                      DAG.getConstantFP(1.0, VT));
6655         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6656                            N0, NewCFP);
6657       }
6658
6659
6660       // (fadd (fadd x, x), (fmul c, x)) -> (fmul x, c+2)
6661       if (CFP10 && !CFP11 && N0.getOpcode() == ISD::FADD &&
6662           N0.getOperand(0) == N0.getOperand(1) &&
6663           N1.getOperand(1) == N0.getOperand(0)) {
6664         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6665                                      SDValue(CFP10, 0),
6666                                      DAG.getConstantFP(2.0, VT));
6667         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6668                            N1.getOperand(1), NewCFP);
6669       }
6670
6671       // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6672       if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6673           N0.getOperand(0) == N0.getOperand(1) &&
6674           N1.getOperand(0) == N0.getOperand(0)) {
6675         SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6676                                      SDValue(CFP11, 0),
6677                                      DAG.getConstantFP(2.0, VT));
6678         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6679                            N1.getOperand(0), NewCFP);
6680       }
6681     }
6682
6683     if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
6684       ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6685       // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6686       if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6687           (N0.getOperand(0) == N1))
6688         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6689                            N1, DAG.getConstantFP(3.0, VT));
6690     }
6691
6692     if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
6693       ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6694       // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6695       if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6696           N1.getOperand(0) == N0)
6697         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6698                            N0, DAG.getConstantFP(3.0, VT));
6699     }
6700
6701     // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6702     if (AllowNewFpConst &&
6703         N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6704         N0.getOperand(0) == N0.getOperand(1) &&
6705         N1.getOperand(0) == N1.getOperand(1) &&
6706         N0.getOperand(0) == N1.getOperand(0))
6707       return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6708                          N0.getOperand(0),
6709                          DAG.getConstantFP(4.0, VT));
6710   }
6711
6712   // FADD -> FMA combines:
6713   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6714        DAG.getTarget().Options.UnsafeFPMath) &&
6715       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6716       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6717
6718     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6719     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6720       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6721                          N0.getOperand(0), N0.getOperand(1), N1);
6722
6723     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6724     // Note: Commutes FADD operands.
6725     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6726       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6727                          N1.getOperand(0), N1.getOperand(1), N0);
6728   }
6729
6730   return SDValue();
6731 }
6732
6733 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6734   SDValue N0 = N->getOperand(0);
6735   SDValue N1 = N->getOperand(1);
6736   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6737   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6738   EVT VT = N->getValueType(0);
6739   SDLoc dl(N);
6740
6741   // fold vector ops
6742   if (VT.isVector()) {
6743     SDValue FoldedVOp = SimplifyVBinOp(N);
6744     if (FoldedVOp.getNode()) return FoldedVOp;
6745   }
6746
6747   // fold (fsub c1, c2) -> c1-c2
6748   if (N0CFP && N1CFP)
6749     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6750   // fold (fsub A, 0) -> A
6751   if (DAG.getTarget().Options.UnsafeFPMath &&
6752       N1CFP && N1CFP->getValueAPF().isZero())
6753     return N0;
6754   // fold (fsub 0, B) -> -B
6755   if (DAG.getTarget().Options.UnsafeFPMath &&
6756       N0CFP && N0CFP->getValueAPF().isZero()) {
6757     if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6758       return GetNegatedExpression(N1, DAG, LegalOperations);
6759     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6760       return DAG.getNode(ISD::FNEG, dl, VT, N1);
6761   }
6762   // fold (fsub A, (fneg B)) -> (fadd A, B)
6763   if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
6764     return DAG.getNode(ISD::FADD, dl, VT, N0,
6765                        GetNegatedExpression(N1, DAG, LegalOperations));
6766
6767   // If 'unsafe math' is enabled, fold
6768   //    (fsub x, x) -> 0.0 &
6769   //    (fsub x, (fadd x, y)) -> (fneg y) &
6770   //    (fsub x, (fadd y, x)) -> (fneg y)
6771   if (DAG.getTarget().Options.UnsafeFPMath) {
6772     if (N0 == N1)
6773       return DAG.getConstantFP(0.0f, VT);
6774
6775     if (N1.getOpcode() == ISD::FADD) {
6776       SDValue N10 = N1->getOperand(0);
6777       SDValue N11 = N1->getOperand(1);
6778
6779       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
6780                                           &DAG.getTarget().Options))
6781         return GetNegatedExpression(N11, DAG, LegalOperations);
6782
6783       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
6784                                           &DAG.getTarget().Options))
6785         return GetNegatedExpression(N10, DAG, LegalOperations);
6786     }
6787   }
6788
6789   // FSUB -> FMA combines:
6790   if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
6791        DAG.getTarget().Options.UnsafeFPMath) &&
6792       DAG.getTarget().getTargetLowering()->isFMAFasterThanFMulAndFAdd(VT) &&
6793       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6794
6795     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6796     if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse())
6797       return DAG.getNode(ISD::FMA, dl, VT,
6798                          N0.getOperand(0), N0.getOperand(1),
6799                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6800
6801     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6802     // Note: Commutes FSUB operands.
6803     if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse())
6804       return DAG.getNode(ISD::FMA, dl, VT,
6805                          DAG.getNode(ISD::FNEG, dl, VT,
6806                          N1.getOperand(0)),
6807                          N1.getOperand(1), N0);
6808
6809     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6810     if (N0.getOpcode() == ISD::FNEG &&
6811         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6812         N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
6813       SDValue N00 = N0.getOperand(0).getOperand(0);
6814       SDValue N01 = N0.getOperand(0).getOperand(1);
6815       return DAG.getNode(ISD::FMA, dl, VT,
6816                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6817                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6818     }
6819   }
6820
6821   return SDValue();
6822 }
6823
6824 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6825   SDValue N0 = N->getOperand(0);
6826   SDValue N1 = N->getOperand(1);
6827   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6828   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6829   EVT VT = N->getValueType(0);
6830   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6831
6832   // fold vector ops
6833   if (VT.isVector()) {
6834     SDValue FoldedVOp = SimplifyVBinOp(N);
6835     if (FoldedVOp.getNode()) return FoldedVOp;
6836   }
6837
6838   // fold (fmul c1, c2) -> c1*c2
6839   if (N0CFP && N1CFP)
6840     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6841   // canonicalize constant to RHS
6842   if (N0CFP && !N1CFP)
6843     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6844   // fold (fmul A, 0) -> 0
6845   if (DAG.getTarget().Options.UnsafeFPMath &&
6846       N1CFP && N1CFP->getValueAPF().isZero())
6847     return N1;
6848   // fold (fmul A, 0) -> 0, vector edition.
6849   if (DAG.getTarget().Options.UnsafeFPMath &&
6850       ISD::isBuildVectorAllZeros(N1.getNode()))
6851     return N1;
6852   // fold (fmul A, 1.0) -> A
6853   if (N1CFP && N1CFP->isExactlyValue(1.0))
6854     return N0;
6855   // fold (fmul X, 2.0) -> (fadd X, X)
6856   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6857     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6858   // fold (fmul X, -1.0) -> (fneg X)
6859   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6860     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6861       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6862
6863   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6864   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
6865                                        &DAG.getTarget().Options)) {
6866     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
6867                                          &DAG.getTarget().Options)) {
6868       // Both can be negated for free, check to see if at least one is cheaper
6869       // negated.
6870       if (LHSNeg == 2 || RHSNeg == 2)
6871         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6872                            GetNegatedExpression(N0, DAG, LegalOperations),
6873                            GetNegatedExpression(N1, DAG, LegalOperations));
6874     }
6875   }
6876
6877   // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6878   if (DAG.getTarget().Options.UnsafeFPMath &&
6879       N1CFP && N0.getOpcode() == ISD::FMUL &&
6880       N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
6881     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
6882                        DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6883                                    N0.getOperand(1), N1));
6884
6885   return SDValue();
6886 }
6887
6888 SDValue DAGCombiner::visitFMA(SDNode *N) {
6889   SDValue N0 = N->getOperand(0);
6890   SDValue N1 = N->getOperand(1);
6891   SDValue N2 = N->getOperand(2);
6892   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6893   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6894   EVT VT = N->getValueType(0);
6895   SDLoc dl(N);
6896
6897   if (DAG.getTarget().Options.UnsafeFPMath) {
6898     if (N0CFP && N0CFP->isZero())
6899       return N2;
6900     if (N1CFP && N1CFP->isZero())
6901       return N2;
6902   }
6903   if (N0CFP && N0CFP->isExactlyValue(1.0))
6904     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6905   if (N1CFP && N1CFP->isExactlyValue(1.0))
6906     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6907
6908   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6909   if (N0CFP && !N1CFP)
6910     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6911
6912   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6913   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6914       N2.getOpcode() == ISD::FMUL &&
6915       N0 == N2.getOperand(0) &&
6916       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6917     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6918                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6919   }
6920
6921
6922   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6923   if (DAG.getTarget().Options.UnsafeFPMath &&
6924       N0.getOpcode() == ISD::FMUL && N1CFP &&
6925       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6926     return DAG.getNode(ISD::FMA, dl, VT,
6927                        N0.getOperand(0),
6928                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6929                        N2);
6930   }
6931
6932   // (fma x, 1, y) -> (fadd x, y)
6933   // (fma x, -1, y) -> (fadd (fneg x), y)
6934   if (N1CFP) {
6935     if (N1CFP->isExactlyValue(1.0))
6936       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6937
6938     if (N1CFP->isExactlyValue(-1.0) &&
6939         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6940       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6941       AddToWorklist(RHSNeg.getNode());
6942       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6943     }
6944   }
6945
6946   // (fma x, c, x) -> (fmul x, (c+1))
6947   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2)
6948     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6949                        DAG.getNode(ISD::FADD, dl, VT,
6950                                    N1, DAG.getConstantFP(1.0, VT)));
6951
6952   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6953   if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
6954       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6955     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6956                        DAG.getNode(ISD::FADD, dl, VT,
6957                                    N1, DAG.getConstantFP(-1.0, VT)));
6958
6959
6960   return SDValue();
6961 }
6962
6963 SDValue DAGCombiner::visitFDIV(SDNode *N) {
6964   SDValue N0 = N->getOperand(0);
6965   SDValue N1 = N->getOperand(1);
6966   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6967   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6968   EVT VT = N->getValueType(0);
6969   const TargetLowering &TLI = DAG.getTargetLoweringInfo();
6970
6971   // fold vector ops
6972   if (VT.isVector()) {
6973     SDValue FoldedVOp = SimplifyVBinOp(N);
6974     if (FoldedVOp.getNode()) return FoldedVOp;
6975   }
6976
6977   // fold (fdiv c1, c2) -> c1/c2
6978   if (N0CFP && N1CFP)
6979     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
6980
6981   // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
6982   if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
6983     // Compute the reciprocal 1.0 / c2.
6984     APFloat N1APF = N1CFP->getValueAPF();
6985     APFloat Recip(N1APF.getSemantics(), 1); // 1.0
6986     APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
6987     // Only do the transform if the reciprocal is a legal fp immediate that
6988     // isn't too nasty (eg NaN, denormal, ...).
6989     if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
6990         (!LegalOperations ||
6991          // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
6992          // backend)... we should handle this gracefully after Legalize.
6993          // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
6994          TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
6995          TLI.isFPImmLegal(Recip, VT)))
6996       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
6997                          DAG.getConstantFP(Recip, VT));
6998   }
6999
7000   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7001   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
7002                                        &DAG.getTarget().Options)) {
7003     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
7004                                          &DAG.getTarget().Options)) {
7005       // Both can be negated for free, check to see if at least one is cheaper
7006       // negated.
7007       if (LHSNeg == 2 || RHSNeg == 2)
7008         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7009                            GetNegatedExpression(N0, DAG, LegalOperations),
7010                            GetNegatedExpression(N1, DAG, LegalOperations));
7011     }
7012   }
7013
7014   return SDValue();
7015 }
7016
7017 SDValue DAGCombiner::visitFREM(SDNode *N) {
7018   SDValue N0 = N->getOperand(0);
7019   SDValue N1 = N->getOperand(1);
7020   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7021   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7022   EVT VT = N->getValueType(0);
7023
7024   // fold (frem c1, c2) -> fmod(c1,c2)
7025   if (N0CFP && N1CFP)
7026     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7027
7028   return SDValue();
7029 }
7030
7031 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7032   SDValue N0 = N->getOperand(0);
7033   SDValue N1 = N->getOperand(1);
7034   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7035   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7036   EVT VT = N->getValueType(0);
7037
7038   if (N0CFP && N1CFP)  // Constant fold
7039     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7040
7041   if (N1CFP) {
7042     const APFloat& V = N1CFP->getValueAPF();
7043     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7044     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7045     if (!V.isNegative()) {
7046       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7047         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7048     } else {
7049       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7050         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7051                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7052     }
7053   }
7054
7055   // copysign(fabs(x), y) -> copysign(x, y)
7056   // copysign(fneg(x), y) -> copysign(x, y)
7057   // copysign(copysign(x,z), y) -> copysign(x, y)
7058   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7059       N0.getOpcode() == ISD::FCOPYSIGN)
7060     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7061                        N0.getOperand(0), N1);
7062
7063   // copysign(x, abs(y)) -> abs(x)
7064   if (N1.getOpcode() == ISD::FABS)
7065     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7066
7067   // copysign(x, copysign(y,z)) -> copysign(x, z)
7068   if (N1.getOpcode() == ISD::FCOPYSIGN)
7069     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7070                        N0, N1.getOperand(1));
7071
7072   // copysign(x, fp_extend(y)) -> copysign(x, y)
7073   // copysign(x, fp_round(y)) -> copysign(x, y)
7074   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7075     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7076                        N0, N1.getOperand(0));
7077
7078   return SDValue();
7079 }
7080
7081 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7082   SDValue N0 = N->getOperand(0);
7083   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7084   EVT VT = N->getValueType(0);
7085   EVT OpVT = N0.getValueType();
7086
7087   // fold (sint_to_fp c1) -> c1fp
7088   if (N0C &&
7089       // ...but only if the target supports immediate floating-point values
7090       (!LegalOperations ||
7091        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7092     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7093
7094   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7095   // but UINT_TO_FP is legal on this target, try to convert.
7096   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7097       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7098     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7099     if (DAG.SignBitIsZero(N0))
7100       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7101   }
7102
7103   // The next optimizations are desirable only if SELECT_CC can be lowered.
7104   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7105     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7106     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7107         !VT.isVector() &&
7108         (!LegalOperations ||
7109          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7110       SDValue Ops[] =
7111         { N0.getOperand(0), N0.getOperand(1),
7112           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7113           N0.getOperand(2) };
7114       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7115     }
7116
7117     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7118     //      (select_cc x, y, 1.0, 0.0,, cc)
7119     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7120         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7121         (!LegalOperations ||
7122          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7123       SDValue Ops[] =
7124         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7125           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7126           N0.getOperand(0).getOperand(2) };
7127       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7128     }
7129   }
7130
7131   return SDValue();
7132 }
7133
7134 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7135   SDValue N0 = N->getOperand(0);
7136   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7137   EVT VT = N->getValueType(0);
7138   EVT OpVT = N0.getValueType();
7139
7140   // fold (uint_to_fp c1) -> c1fp
7141   if (N0C &&
7142       // ...but only if the target supports immediate floating-point values
7143       (!LegalOperations ||
7144        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7145     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7146
7147   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7148   // but SINT_TO_FP is legal on this target, try to convert.
7149   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7150       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7151     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7152     if (DAG.SignBitIsZero(N0))
7153       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7154   }
7155
7156   // The next optimizations are desirable only if SELECT_CC can be lowered.
7157   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7158     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7159
7160     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7161         (!LegalOperations ||
7162          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7163       SDValue Ops[] =
7164         { N0.getOperand(0), N0.getOperand(1),
7165           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7166           N0.getOperand(2) };
7167       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7168     }
7169   }
7170
7171   return SDValue();
7172 }
7173
7174 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7175   SDValue N0 = N->getOperand(0);
7176   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7177   EVT VT = N->getValueType(0);
7178
7179   // fold (fp_to_sint c1fp) -> c1
7180   if (N0CFP)
7181     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7182
7183   return SDValue();
7184 }
7185
7186 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7187   SDValue N0 = N->getOperand(0);
7188   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7189   EVT VT = N->getValueType(0);
7190
7191   // fold (fp_to_uint c1fp) -> c1
7192   if (N0CFP)
7193     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7194
7195   return SDValue();
7196 }
7197
7198 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7199   SDValue N0 = N->getOperand(0);
7200   SDValue N1 = N->getOperand(1);
7201   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7202   EVT VT = N->getValueType(0);
7203
7204   // fold (fp_round c1fp) -> c1fp
7205   if (N0CFP)
7206     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7207
7208   // fold (fp_round (fp_extend x)) -> x
7209   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7210     return N0.getOperand(0);
7211
7212   // fold (fp_round (fp_round x)) -> (fp_round x)
7213   if (N0.getOpcode() == ISD::FP_ROUND) {
7214     // This is a value preserving truncation if both round's are.
7215     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7216                    N0.getNode()->getConstantOperandVal(1) == 1;
7217     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7218                        DAG.getIntPtrConstant(IsTrunc));
7219   }
7220
7221   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7222   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7223     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7224                               N0.getOperand(0), N1);
7225     AddToWorklist(Tmp.getNode());
7226     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7227                        Tmp, N0.getOperand(1));
7228   }
7229
7230   return SDValue();
7231 }
7232
7233 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7234   SDValue N0 = N->getOperand(0);
7235   EVT VT = N->getValueType(0);
7236   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7237   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7238
7239   // fold (fp_round_inreg c1fp) -> c1fp
7240   if (N0CFP && isTypeLegal(EVT)) {
7241     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7242     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7243   }
7244
7245   return SDValue();
7246 }
7247
7248 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7249   SDValue N0 = N->getOperand(0);
7250   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7251   EVT VT = N->getValueType(0);
7252
7253   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7254   if (N->hasOneUse() &&
7255       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7256     return SDValue();
7257
7258   // fold (fp_extend c1fp) -> c1fp
7259   if (N0CFP)
7260     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7261
7262   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7263   // value of X.
7264   if (N0.getOpcode() == ISD::FP_ROUND
7265       && N0.getNode()->getConstantOperandVal(1) == 1) {
7266     SDValue In = N0.getOperand(0);
7267     if (In.getValueType() == VT) return In;
7268     if (VT.bitsLT(In.getValueType()))
7269       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7270                          In, N0.getOperand(1));
7271     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7272   }
7273
7274   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7275   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7276        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7277     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7278     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7279                                      LN0->getChain(),
7280                                      LN0->getBasePtr(), N0.getValueType(),
7281                                      LN0->getMemOperand());
7282     CombineTo(N, ExtLoad);
7283     CombineTo(N0.getNode(),
7284               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7285                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7286               ExtLoad.getValue(1));
7287     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7288   }
7289
7290   return SDValue();
7291 }
7292
7293 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7294   SDValue N0 = N->getOperand(0);
7295   EVT VT = N->getValueType(0);
7296
7297   if (VT.isVector()) {
7298     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7299     if (FoldedVOp.getNode()) return FoldedVOp;
7300   }
7301
7302   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7303                          &DAG.getTarget().Options))
7304     return GetNegatedExpression(N0, DAG, LegalOperations);
7305
7306   // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
7307   // constant pool values.
7308   if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
7309       !VT.isVector() &&
7310       N0.getNode()->hasOneUse() &&
7311       N0.getOperand(0).getValueType().isInteger()) {
7312     SDValue Int = N0.getOperand(0);
7313     EVT IntVT = Int.getValueType();
7314     if (IntVT.isInteger() && !IntVT.isVector()) {
7315       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7316               DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7317       AddToWorklist(Int.getNode());
7318       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7319                          VT, Int);
7320     }
7321   }
7322
7323   // (fneg (fmul c, x)) -> (fmul -c, x)
7324   if (N0.getOpcode() == ISD::FMUL) {
7325     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7326     if (CFP1) {
7327       APFloat CVal = CFP1->getValueAPF();
7328       CVal.changeSign();
7329       if (Level >= AfterLegalizeDAG &&
7330           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7331            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7332         return DAG.getNode(
7333             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7334             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7335     }
7336   }
7337
7338   return SDValue();
7339 }
7340
7341 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7342   SDValue N0 = N->getOperand(0);
7343   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7344   EVT VT = N->getValueType(0);
7345
7346   // fold (fceil c1) -> fceil(c1)
7347   if (N0CFP)
7348     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7349
7350   return SDValue();
7351 }
7352
7353 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7354   SDValue N0 = N->getOperand(0);
7355   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7356   EVT VT = N->getValueType(0);
7357
7358   // fold (ftrunc c1) -> ftrunc(c1)
7359   if (N0CFP)
7360     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7361
7362   return SDValue();
7363 }
7364
7365 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7366   SDValue N0 = N->getOperand(0);
7367   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7368   EVT VT = N->getValueType(0);
7369
7370   // fold (ffloor c1) -> ffloor(c1)
7371   if (N0CFP)
7372     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7373
7374   return SDValue();
7375 }
7376
7377 SDValue DAGCombiner::visitFABS(SDNode *N) {
7378   SDValue N0 = N->getOperand(0);
7379   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7380   EVT VT = N->getValueType(0);
7381
7382   if (VT.isVector()) {
7383     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7384     if (FoldedVOp.getNode()) return FoldedVOp;
7385   }
7386
7387   // fold (fabs c1) -> fabs(c1)
7388   if (N0CFP)
7389     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7390   // fold (fabs (fabs x)) -> (fabs x)
7391   if (N0.getOpcode() == ISD::FABS)
7392     return N->getOperand(0);
7393   // fold (fabs (fneg x)) -> (fabs x)
7394   // fold (fabs (fcopysign x, y)) -> (fabs x)
7395   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7396     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7397
7398   // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
7399   // constant pool values.
7400   if (!TLI.isFAbsFree(VT) &&
7401       N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
7402       N0.getOperand(0).getValueType().isInteger() &&
7403       !N0.getOperand(0).getValueType().isVector()) {
7404     SDValue Int = N0.getOperand(0);
7405     EVT IntVT = Int.getValueType();
7406     if (IntVT.isInteger() && !IntVT.isVector()) {
7407       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7408              DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
7409       AddToWorklist(Int.getNode());
7410       return DAG.getNode(ISD::BITCAST, SDLoc(N),
7411                          N->getValueType(0), Int);
7412     }
7413   }
7414
7415   return SDValue();
7416 }
7417
7418 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7419   SDValue Chain = N->getOperand(0);
7420   SDValue N1 = N->getOperand(1);
7421   SDValue N2 = N->getOperand(2);
7422
7423   // If N is a constant we could fold this into a fallthrough or unconditional
7424   // branch. However that doesn't happen very often in normal code, because
7425   // Instcombine/SimplifyCFG should have handled the available opportunities.
7426   // If we did this folding here, it would be necessary to update the
7427   // MachineBasicBlock CFG, which is awkward.
7428
7429   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7430   // on the target.
7431   if (N1.getOpcode() == ISD::SETCC &&
7432       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7433                                    N1.getOperand(0).getValueType())) {
7434     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7435                        Chain, N1.getOperand(2),
7436                        N1.getOperand(0), N1.getOperand(1), N2);
7437   }
7438
7439   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7440       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7441        (N1.getOperand(0).hasOneUse() &&
7442         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7443     SDNode *Trunc = nullptr;
7444     if (N1.getOpcode() == ISD::TRUNCATE) {
7445       // Look pass the truncate.
7446       Trunc = N1.getNode();
7447       N1 = N1.getOperand(0);
7448     }
7449
7450     // Match this pattern so that we can generate simpler code:
7451     //
7452     //   %a = ...
7453     //   %b = and i32 %a, 2
7454     //   %c = srl i32 %b, 1
7455     //   brcond i32 %c ...
7456     //
7457     // into
7458     //
7459     //   %a = ...
7460     //   %b = and i32 %a, 2
7461     //   %c = setcc eq %b, 0
7462     //   brcond %c ...
7463     //
7464     // This applies only when the AND constant value has one bit set and the
7465     // SRL constant is equal to the log2 of the AND constant. The back-end is
7466     // smart enough to convert the result into a TEST/JMP sequence.
7467     SDValue Op0 = N1.getOperand(0);
7468     SDValue Op1 = N1.getOperand(1);
7469
7470     if (Op0.getOpcode() == ISD::AND &&
7471         Op1.getOpcode() == ISD::Constant) {
7472       SDValue AndOp1 = Op0.getOperand(1);
7473
7474       if (AndOp1.getOpcode() == ISD::Constant) {
7475         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7476
7477         if (AndConst.isPowerOf2() &&
7478             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7479           SDValue SetCC =
7480             DAG.getSetCC(SDLoc(N),
7481                          getSetCCResultType(Op0.getValueType()),
7482                          Op0, DAG.getConstant(0, Op0.getValueType()),
7483                          ISD::SETNE);
7484
7485           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7486                                           MVT::Other, Chain, SetCC, N2);
7487           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7488           // will convert it back to (X & C1) >> C2.
7489           CombineTo(N, NewBRCond, false);
7490           // Truncate is dead.
7491           if (Trunc) {
7492             removeFromWorklist(Trunc);
7493             DAG.DeleteNode(Trunc);
7494           }
7495           // Replace the uses of SRL with SETCC
7496           WorklistRemover DeadNodes(*this);
7497           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7498           removeFromWorklist(N1.getNode());
7499           DAG.DeleteNode(N1.getNode());
7500           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7501         }
7502       }
7503     }
7504
7505     if (Trunc)
7506       // Restore N1 if the above transformation doesn't match.
7507       N1 = N->getOperand(1);
7508   }
7509
7510   // Transform br(xor(x, y)) -> br(x != y)
7511   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7512   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7513     SDNode *TheXor = N1.getNode();
7514     SDValue Op0 = TheXor->getOperand(0);
7515     SDValue Op1 = TheXor->getOperand(1);
7516     if (Op0.getOpcode() == Op1.getOpcode()) {
7517       // Avoid missing important xor optimizations.
7518       SDValue Tmp = visitXOR(TheXor);
7519       if (Tmp.getNode()) {
7520         if (Tmp.getNode() != TheXor) {
7521           DEBUG(dbgs() << "\nReplacing.8 ";
7522                 TheXor->dump(&DAG);
7523                 dbgs() << "\nWith: ";
7524                 Tmp.getNode()->dump(&DAG);
7525                 dbgs() << '\n');
7526           WorklistRemover DeadNodes(*this);
7527           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7528           removeFromWorklist(TheXor);
7529           DAG.DeleteNode(TheXor);
7530           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7531                              MVT::Other, Chain, Tmp, N2);
7532         }
7533
7534         // visitXOR has changed XOR's operands or replaced the XOR completely,
7535         // bail out.
7536         return SDValue(N, 0);
7537       }
7538     }
7539
7540     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7541       bool Equal = false;
7542       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7543         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7544             Op0.getOpcode() == ISD::XOR) {
7545           TheXor = Op0.getNode();
7546           Equal = true;
7547         }
7548
7549       EVT SetCCVT = N1.getValueType();
7550       if (LegalTypes)
7551         SetCCVT = getSetCCResultType(SetCCVT);
7552       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7553                                    SetCCVT,
7554                                    Op0, Op1,
7555                                    Equal ? ISD::SETEQ : ISD::SETNE);
7556       // Replace the uses of XOR with SETCC
7557       WorklistRemover DeadNodes(*this);
7558       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7559       removeFromWorklist(N1.getNode());
7560       DAG.DeleteNode(N1.getNode());
7561       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7562                          MVT::Other, Chain, SetCC, N2);
7563     }
7564   }
7565
7566   return SDValue();
7567 }
7568
7569 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7570 //
7571 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7572   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7573   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7574
7575   // If N is a constant we could fold this into a fallthrough or unconditional
7576   // branch. However that doesn't happen very often in normal code, because
7577   // Instcombine/SimplifyCFG should have handled the available opportunities.
7578   // If we did this folding here, it would be necessary to update the
7579   // MachineBasicBlock CFG, which is awkward.
7580
7581   // Use SimplifySetCC to simplify SETCC's.
7582   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7583                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7584                                false);
7585   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7586
7587   // fold to a simpler setcc
7588   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7589     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7590                        N->getOperand(0), Simp.getOperand(2),
7591                        Simp.getOperand(0), Simp.getOperand(1),
7592                        N->getOperand(4));
7593
7594   return SDValue();
7595 }
7596
7597 /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
7598 /// uses N as its base pointer and that N may be folded in the load / store
7599 /// addressing mode.
7600 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7601                                     SelectionDAG &DAG,
7602                                     const TargetLowering &TLI) {
7603   EVT VT;
7604   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7605     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7606       return false;
7607     VT = Use->getValueType(0);
7608   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7609     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7610       return false;
7611     VT = ST->getValue().getValueType();
7612   } else
7613     return false;
7614
7615   TargetLowering::AddrMode AM;
7616   if (N->getOpcode() == ISD::ADD) {
7617     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7618     if (Offset)
7619       // [reg +/- imm]
7620       AM.BaseOffs = Offset->getSExtValue();
7621     else
7622       // [reg +/- reg]
7623       AM.Scale = 1;
7624   } else if (N->getOpcode() == ISD::SUB) {
7625     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7626     if (Offset)
7627       // [reg +/- imm]
7628       AM.BaseOffs = -Offset->getSExtValue();
7629     else
7630       // [reg +/- reg]
7631       AM.Scale = 1;
7632   } else
7633     return false;
7634
7635   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7636 }
7637
7638 /// CombineToPreIndexedLoadStore - Try turning a load / store into a
7639 /// pre-indexed load / store when the base pointer is an add or subtract
7640 /// and it has other uses besides the load / store. After the
7641 /// transformation, the new indexed load / store has effectively folded
7642 /// the add / subtract in and all of its other uses are redirected to the
7643 /// new load / store.
7644 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7645   if (Level < AfterLegalizeDAG)
7646     return false;
7647
7648   bool isLoad = true;
7649   SDValue Ptr;
7650   EVT VT;
7651   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7652     if (LD->isIndexed())
7653       return false;
7654     VT = LD->getMemoryVT();
7655     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7656         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7657       return false;
7658     Ptr = LD->getBasePtr();
7659   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7660     if (ST->isIndexed())
7661       return false;
7662     VT = ST->getMemoryVT();
7663     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7664         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7665       return false;
7666     Ptr = ST->getBasePtr();
7667     isLoad = false;
7668   } else {
7669     return false;
7670   }
7671
7672   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7673   // out.  There is no reason to make this a preinc/predec.
7674   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7675       Ptr.getNode()->hasOneUse())
7676     return false;
7677
7678   // Ask the target to do addressing mode selection.
7679   SDValue BasePtr;
7680   SDValue Offset;
7681   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7682   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7683     return false;
7684
7685   // Backends without true r+i pre-indexed forms may need to pass a
7686   // constant base with a variable offset so that constant coercion
7687   // will work with the patterns in canonical form.
7688   bool Swapped = false;
7689   if (isa<ConstantSDNode>(BasePtr)) {
7690     std::swap(BasePtr, Offset);
7691     Swapped = true;
7692   }
7693
7694   // Don't create a indexed load / store with zero offset.
7695   if (isa<ConstantSDNode>(Offset) &&
7696       cast<ConstantSDNode>(Offset)->isNullValue())
7697     return false;
7698
7699   // Try turning it into a pre-indexed load / store except when:
7700   // 1) The new base ptr is a frame index.
7701   // 2) If N is a store and the new base ptr is either the same as or is a
7702   //    predecessor of the value being stored.
7703   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7704   //    that would create a cycle.
7705   // 4) All uses are load / store ops that use it as old base ptr.
7706
7707   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7708   // (plus the implicit offset) to a register to preinc anyway.
7709   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7710     return false;
7711
7712   // Check #2.
7713   if (!isLoad) {
7714     SDValue Val = cast<StoreSDNode>(N)->getValue();
7715     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7716       return false;
7717   }
7718
7719   // If the offset is a constant, there may be other adds of constants that
7720   // can be folded with this one. We should do this to avoid having to keep
7721   // a copy of the original base pointer.
7722   SmallVector<SDNode *, 16> OtherUses;
7723   if (isa<ConstantSDNode>(Offset))
7724     for (SDNode *Use : BasePtr.getNode()->uses()) {
7725       if (Use == Ptr.getNode())
7726         continue;
7727
7728       if (Use->isPredecessorOf(N))
7729         continue;
7730
7731       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7732         OtherUses.clear();
7733         break;
7734       }
7735
7736       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7737       if (Op1.getNode() == BasePtr.getNode())
7738         std::swap(Op0, Op1);
7739       assert(Op0.getNode() == BasePtr.getNode() &&
7740              "Use of ADD/SUB but not an operand");
7741
7742       if (!isa<ConstantSDNode>(Op1)) {
7743         OtherUses.clear();
7744         break;
7745       }
7746
7747       // FIXME: In some cases, we can be smarter about this.
7748       if (Op1.getValueType() != Offset.getValueType()) {
7749         OtherUses.clear();
7750         break;
7751       }
7752
7753       OtherUses.push_back(Use);
7754     }
7755
7756   if (Swapped)
7757     std::swap(BasePtr, Offset);
7758
7759   // Now check for #3 and #4.
7760   bool RealUse = false;
7761
7762   // Caches for hasPredecessorHelper
7763   SmallPtrSet<const SDNode *, 32> Visited;
7764   SmallVector<const SDNode *, 16> Worklist;
7765
7766   for (SDNode *Use : Ptr.getNode()->uses()) {
7767     if (Use == N)
7768       continue;
7769     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7770       return false;
7771
7772     // If Ptr may be folded in addressing mode of other use, then it's
7773     // not profitable to do this transformation.
7774     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7775       RealUse = true;
7776   }
7777
7778   if (!RealUse)
7779     return false;
7780
7781   SDValue Result;
7782   if (isLoad)
7783     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7784                                 BasePtr, Offset, AM);
7785   else
7786     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7787                                  BasePtr, Offset, AM);
7788   ++PreIndexedNodes;
7789   ++NodesCombined;
7790   DEBUG(dbgs() << "\nReplacing.4 ";
7791         N->dump(&DAG);
7792         dbgs() << "\nWith: ";
7793         Result.getNode()->dump(&DAG);
7794         dbgs() << '\n');
7795   WorklistRemover DeadNodes(*this);
7796   if (isLoad) {
7797     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7798     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7799   } else {
7800     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7801   }
7802
7803   // Finally, since the node is now dead, remove it from the graph.
7804   DAG.DeleteNode(N);
7805
7806   if (Swapped)
7807     std::swap(BasePtr, Offset);
7808
7809   // Replace other uses of BasePtr that can be updated to use Ptr
7810   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
7811     unsigned OffsetIdx = 1;
7812     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
7813       OffsetIdx = 0;
7814     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
7815            BasePtr.getNode() && "Expected BasePtr operand");
7816
7817     // We need to replace ptr0 in the following expression:
7818     //   x0 * offset0 + y0 * ptr0 = t0
7819     // knowing that
7820     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
7821     //
7822     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
7823     // indexed load/store and the expresion that needs to be re-written.
7824     //
7825     // Therefore, we have:
7826     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
7827
7828     ConstantSDNode *CN =
7829       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
7830     int X0, X1, Y0, Y1;
7831     APInt Offset0 = CN->getAPIntValue();
7832     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
7833
7834     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
7835     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
7836     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
7837     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
7838
7839     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
7840
7841     APInt CNV = Offset0;
7842     if (X0 < 0) CNV = -CNV;
7843     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
7844     else CNV = CNV - Offset1;
7845
7846     // We can now generate the new expression.
7847     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
7848     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
7849
7850     SDValue NewUse = DAG.getNode(Opcode,
7851                                  SDLoc(OtherUses[i]),
7852                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
7853     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
7854     removeFromWorklist(OtherUses[i]);
7855     DAG.DeleteNode(OtherUses[i]);
7856   }
7857
7858   // Replace the uses of Ptr with uses of the updated base value.
7859   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
7860   removeFromWorklist(Ptr.getNode());
7861   DAG.DeleteNode(Ptr.getNode());
7862
7863   return true;
7864 }
7865
7866 /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
7867 /// add / sub of the base pointer node into a post-indexed load / store.
7868 /// The transformation folded the add / subtract into the new indexed
7869 /// load / store effectively and all of its uses are redirected to the
7870 /// new load / store.
7871 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
7872   if (Level < AfterLegalizeDAG)
7873     return false;
7874
7875   bool isLoad = true;
7876   SDValue Ptr;
7877   EVT VT;
7878   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7879     if (LD->isIndexed())
7880       return false;
7881     VT = LD->getMemoryVT();
7882     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
7883         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
7884       return false;
7885     Ptr = LD->getBasePtr();
7886   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7887     if (ST->isIndexed())
7888       return false;
7889     VT = ST->getMemoryVT();
7890     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
7891         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
7892       return false;
7893     Ptr = ST->getBasePtr();
7894     isLoad = false;
7895   } else {
7896     return false;
7897   }
7898
7899   if (Ptr.getNode()->hasOneUse())
7900     return false;
7901
7902   for (SDNode *Op : Ptr.getNode()->uses()) {
7903     if (Op == N ||
7904         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
7905       continue;
7906
7907     SDValue BasePtr;
7908     SDValue Offset;
7909     ISD::MemIndexedMode AM = ISD::UNINDEXED;
7910     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
7911       // Don't create a indexed load / store with zero offset.
7912       if (isa<ConstantSDNode>(Offset) &&
7913           cast<ConstantSDNode>(Offset)->isNullValue())
7914         continue;
7915
7916       // Try turning it into a post-indexed load / store except when
7917       // 1) All uses are load / store ops that use it as base ptr (and
7918       //    it may be folded as addressing mmode).
7919       // 2) Op must be independent of N, i.e. Op is neither a predecessor
7920       //    nor a successor of N. Otherwise, if Op is folded that would
7921       //    create a cycle.
7922
7923       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7924         continue;
7925
7926       // Check for #1.
7927       bool TryNext = false;
7928       for (SDNode *Use : BasePtr.getNode()->uses()) {
7929         if (Use == Ptr.getNode())
7930           continue;
7931
7932         // If all the uses are load / store addresses, then don't do the
7933         // transformation.
7934         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
7935           bool RealUse = false;
7936           for (SDNode *UseUse : Use->uses()) {
7937             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
7938               RealUse = true;
7939           }
7940
7941           if (!RealUse) {
7942             TryNext = true;
7943             break;
7944           }
7945         }
7946       }
7947
7948       if (TryNext)
7949         continue;
7950
7951       // Check for #2
7952       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
7953         SDValue Result = isLoad
7954           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7955                                BasePtr, Offset, AM)
7956           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
7957                                 BasePtr, Offset, AM);
7958         ++PostIndexedNodes;
7959         ++NodesCombined;
7960         DEBUG(dbgs() << "\nReplacing.5 ";
7961               N->dump(&DAG);
7962               dbgs() << "\nWith: ";
7963               Result.getNode()->dump(&DAG);
7964               dbgs() << '\n');
7965         WorklistRemover DeadNodes(*this);
7966         if (isLoad) {
7967           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
7968           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
7969         } else {
7970           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
7971         }
7972
7973         // Finally, since the node is now dead, remove it from the graph.
7974         DAG.DeleteNode(N);
7975
7976         // Replace the uses of Use with uses of the updated base value.
7977         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
7978                                       Result.getValue(isLoad ? 1 : 0));
7979         removeFromWorklist(Op);
7980         DAG.DeleteNode(Op);
7981         return true;
7982       }
7983     }
7984   }
7985
7986   return false;
7987 }
7988
7989 SDValue DAGCombiner::visitLOAD(SDNode *N) {
7990   LoadSDNode *LD  = cast<LoadSDNode>(N);
7991   SDValue Chain = LD->getChain();
7992   SDValue Ptr   = LD->getBasePtr();
7993
7994   // If load is not volatile and there are no uses of the loaded value (and
7995   // the updated indexed value in case of indexed loads), change uses of the
7996   // chain value into uses of the chain input (i.e. delete the dead load).
7997   if (!LD->isVolatile()) {
7998     if (N->getValueType(1) == MVT::Other) {
7999       // Unindexed loads.
8000       if (!N->hasAnyUseOfValue(0)) {
8001         // It's not safe to use the two value CombineTo variant here. e.g.
8002         // v1, chain2 = load chain1, loc
8003         // v2, chain3 = load chain2, loc
8004         // v3         = add v2, c
8005         // Now we replace use of chain2 with chain1.  This makes the second load
8006         // isomorphic to the one we are deleting, and thus makes this load live.
8007         DEBUG(dbgs() << "\nReplacing.6 ";
8008               N->dump(&DAG);
8009               dbgs() << "\nWith chain: ";
8010               Chain.getNode()->dump(&DAG);
8011               dbgs() << "\n");
8012         WorklistRemover DeadNodes(*this);
8013         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8014
8015         if (N->use_empty()) {
8016           removeFromWorklist(N);
8017           DAG.DeleteNode(N);
8018         }
8019
8020         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8021       }
8022     } else {
8023       // Indexed loads.
8024       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8025       if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
8026         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8027         DEBUG(dbgs() << "\nReplacing.7 ";
8028               N->dump(&DAG);
8029               dbgs() << "\nWith: ";
8030               Undef.getNode()->dump(&DAG);
8031               dbgs() << " and 2 other values\n");
8032         WorklistRemover DeadNodes(*this);
8033         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8034         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
8035                                       DAG.getUNDEF(N->getValueType(1)));
8036         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8037         removeFromWorklist(N);
8038         DAG.DeleteNode(N);
8039         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8040       }
8041     }
8042   }
8043
8044   // If this load is directly stored, replace the load value with the stored
8045   // value.
8046   // TODO: Handle store large -> read small portion.
8047   // TODO: Handle TRUNCSTORE/LOADEXT
8048   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8049     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8050       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8051       if (PrevST->getBasePtr() == Ptr &&
8052           PrevST->getValue().getValueType() == N->getValueType(0))
8053       return CombineTo(N, Chain.getOperand(1), Chain);
8054     }
8055   }
8056
8057   // Try to infer better alignment information than the load already has.
8058   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8059     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8060       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8061         SDValue NewLoad =
8062                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8063                               LD->getValueType(0),
8064                               Chain, Ptr, LD->getPointerInfo(),
8065                               LD->getMemoryVT(),
8066                               LD->isVolatile(), LD->isNonTemporal(), Align,
8067                               LD->getAAInfo());
8068         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8069       }
8070     }
8071   }
8072
8073   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
8074     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
8075 #ifndef NDEBUG
8076   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8077       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8078     UseAA = false;
8079 #endif
8080   if (UseAA && LD->isUnindexed()) {
8081     // Walk up chain skipping non-aliasing memory nodes.
8082     SDValue BetterChain = FindBetterChain(N, Chain);
8083
8084     // If there is a better chain.
8085     if (Chain != BetterChain) {
8086       SDValue ReplLoad;
8087
8088       // Replace the chain to void dependency.
8089       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8090         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8091                                BetterChain, Ptr, LD->getMemOperand());
8092       } else {
8093         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8094                                   LD->getValueType(0),
8095                                   BetterChain, Ptr, LD->getMemoryVT(),
8096                                   LD->getMemOperand());
8097       }
8098
8099       // Create token factor to keep old chain connected.
8100       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8101                                   MVT::Other, Chain, ReplLoad.getValue(1));
8102
8103       // Make sure the new and old chains are cleaned up.
8104       AddToWorklist(Token.getNode());
8105
8106       // Replace uses with load result and token factor. Don't add users
8107       // to work list.
8108       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8109     }
8110   }
8111
8112   // Try transforming N to an indexed load.
8113   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8114     return SDValue(N, 0);
8115
8116   // Try to slice up N to more direct loads if the slices are mapped to
8117   // different register banks or pairing can take place.
8118   if (SliceUpLoad(N))
8119     return SDValue(N, 0);
8120
8121   return SDValue();
8122 }
8123
8124 namespace {
8125 /// \brief Helper structure used to slice a load in smaller loads.
8126 /// Basically a slice is obtained from the following sequence:
8127 /// Origin = load Ty1, Base
8128 /// Shift = srl Ty1 Origin, CstTy Amount
8129 /// Inst = trunc Shift to Ty2
8130 ///
8131 /// Then, it will be rewriten into:
8132 /// Slice = load SliceTy, Base + SliceOffset
8133 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8134 ///
8135 /// SliceTy is deduced from the number of bits that are actually used to
8136 /// build Inst.
8137 struct LoadedSlice {
8138   /// \brief Helper structure used to compute the cost of a slice.
8139   struct Cost {
8140     /// Are we optimizing for code size.
8141     bool ForCodeSize;
8142     /// Various cost.
8143     unsigned Loads;
8144     unsigned Truncates;
8145     unsigned CrossRegisterBanksCopies;
8146     unsigned ZExts;
8147     unsigned Shift;
8148
8149     Cost(bool ForCodeSize = false)
8150         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8151           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8152
8153     /// \brief Get the cost of one isolated slice.
8154     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8155         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8156           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8157       EVT TruncType = LS.Inst->getValueType(0);
8158       EVT LoadedType = LS.getLoadedType();
8159       if (TruncType != LoadedType &&
8160           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8161         ZExts = 1;
8162     }
8163
8164     /// \brief Account for slicing gain in the current cost.
8165     /// Slicing provide a few gains like removing a shift or a
8166     /// truncate. This method allows to grow the cost of the original
8167     /// load with the gain from this slice.
8168     void addSliceGain(const LoadedSlice &LS) {
8169       // Each slice saves a truncate.
8170       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8171       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8172                               LS.Inst->getOperand(0).getValueType()))
8173         ++Truncates;
8174       // If there is a shift amount, this slice gets rid of it.
8175       if (LS.Shift)
8176         ++Shift;
8177       // If this slice can merge a cross register bank copy, account for it.
8178       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8179         ++CrossRegisterBanksCopies;
8180     }
8181
8182     Cost &operator+=(const Cost &RHS) {
8183       Loads += RHS.Loads;
8184       Truncates += RHS.Truncates;
8185       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8186       ZExts += RHS.ZExts;
8187       Shift += RHS.Shift;
8188       return *this;
8189     }
8190
8191     bool operator==(const Cost &RHS) const {
8192       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8193              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8194              ZExts == RHS.ZExts && Shift == RHS.Shift;
8195     }
8196
8197     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8198
8199     bool operator<(const Cost &RHS) const {
8200       // Assume cross register banks copies are as expensive as loads.
8201       // FIXME: Do we want some more target hooks?
8202       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8203       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8204       // Unless we are optimizing for code size, consider the
8205       // expensive operation first.
8206       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8207         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8208       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8209              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8210     }
8211
8212     bool operator>(const Cost &RHS) const { return RHS < *this; }
8213
8214     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8215
8216     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8217   };
8218   // The last instruction that represent the slice. This should be a
8219   // truncate instruction.
8220   SDNode *Inst;
8221   // The original load instruction.
8222   LoadSDNode *Origin;
8223   // The right shift amount in bits from the original load.
8224   unsigned Shift;
8225   // The DAG from which Origin came from.
8226   // This is used to get some contextual information about legal types, etc.
8227   SelectionDAG *DAG;
8228
8229   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8230               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8231       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8232
8233   LoadedSlice(const LoadedSlice &LS)
8234       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8235
8236   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8237   /// \return Result is \p BitWidth and has used bits set to 1 and
8238   ///         not used bits set to 0.
8239   APInt getUsedBits() const {
8240     // Reproduce the trunc(lshr) sequence:
8241     // - Start from the truncated value.
8242     // - Zero extend to the desired bit width.
8243     // - Shift left.
8244     assert(Origin && "No original load to compare against.");
8245     unsigned BitWidth = Origin->getValueSizeInBits(0);
8246     assert(Inst && "This slice is not bound to an instruction");
8247     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8248            "Extracted slice is bigger than the whole type!");
8249     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8250     UsedBits.setAllBits();
8251     UsedBits = UsedBits.zext(BitWidth);
8252     UsedBits <<= Shift;
8253     return UsedBits;
8254   }
8255
8256   /// \brief Get the size of the slice to be loaded in bytes.
8257   unsigned getLoadedSize() const {
8258     unsigned SliceSize = getUsedBits().countPopulation();
8259     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8260     return SliceSize / 8;
8261   }
8262
8263   /// \brief Get the type that will be loaded for this slice.
8264   /// Note: This may not be the final type for the slice.
8265   EVT getLoadedType() const {
8266     assert(DAG && "Missing context");
8267     LLVMContext &Ctxt = *DAG->getContext();
8268     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8269   }
8270
8271   /// \brief Get the alignment of the load used for this slice.
8272   unsigned getAlignment() const {
8273     unsigned Alignment = Origin->getAlignment();
8274     unsigned Offset = getOffsetFromBase();
8275     if (Offset != 0)
8276       Alignment = MinAlign(Alignment, Alignment + Offset);
8277     return Alignment;
8278   }
8279
8280   /// \brief Check if this slice can be rewritten with legal operations.
8281   bool isLegal() const {
8282     // An invalid slice is not legal.
8283     if (!Origin || !Inst || !DAG)
8284       return false;
8285
8286     // Offsets are for indexed load only, we do not handle that.
8287     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8288       return false;
8289
8290     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8291
8292     // Check that the type is legal.
8293     EVT SliceType = getLoadedType();
8294     if (!TLI.isTypeLegal(SliceType))
8295       return false;
8296
8297     // Check that the load is legal for this type.
8298     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8299       return false;
8300
8301     // Check that the offset can be computed.
8302     // 1. Check its type.
8303     EVT PtrType = Origin->getBasePtr().getValueType();
8304     if (PtrType == MVT::Untyped || PtrType.isExtended())
8305       return false;
8306
8307     // 2. Check that it fits in the immediate.
8308     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8309       return false;
8310
8311     // 3. Check that the computation is legal.
8312     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8313       return false;
8314
8315     // Check that the zext is legal if it needs one.
8316     EVT TruncateType = Inst->getValueType(0);
8317     if (TruncateType != SliceType &&
8318         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8319       return false;
8320
8321     return true;
8322   }
8323
8324   /// \brief Get the offset in bytes of this slice in the original chunk of
8325   /// bits.
8326   /// \pre DAG != nullptr.
8327   uint64_t getOffsetFromBase() const {
8328     assert(DAG && "Missing context.");
8329     bool IsBigEndian =
8330         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8331     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8332     uint64_t Offset = Shift / 8;
8333     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8334     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8335            "The size of the original loaded type is not a multiple of a"
8336            " byte.");
8337     // If Offset is bigger than TySizeInBytes, it means we are loading all
8338     // zeros. This should have been optimized before in the process.
8339     assert(TySizeInBytes > Offset &&
8340            "Invalid shift amount for given loaded size");
8341     if (IsBigEndian)
8342       Offset = TySizeInBytes - Offset - getLoadedSize();
8343     return Offset;
8344   }
8345
8346   /// \brief Generate the sequence of instructions to load the slice
8347   /// represented by this object and redirect the uses of this slice to
8348   /// this new sequence of instructions.
8349   /// \pre this->Inst && this->Origin are valid Instructions and this
8350   /// object passed the legal check: LoadedSlice::isLegal returned true.
8351   /// \return The last instruction of the sequence used to load the slice.
8352   SDValue loadSlice() const {
8353     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8354     const SDValue &OldBaseAddr = Origin->getBasePtr();
8355     SDValue BaseAddr = OldBaseAddr;
8356     // Get the offset in that chunk of bytes w.r.t. the endianess.
8357     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8358     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8359     if (Offset) {
8360       // BaseAddr = BaseAddr + Offset.
8361       EVT ArithType = BaseAddr.getValueType();
8362       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8363                               DAG->getConstant(Offset, ArithType));
8364     }
8365
8366     // Create the type of the loaded slice according to its size.
8367     EVT SliceType = getLoadedType();
8368
8369     // Create the load for the slice.
8370     SDValue LastInst = DAG->getLoad(
8371         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8372         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8373         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8374     // If the final type is not the same as the loaded type, this means that
8375     // we have to pad with zero. Create a zero extend for that.
8376     EVT FinalType = Inst->getValueType(0);
8377     if (SliceType != FinalType)
8378       LastInst =
8379           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8380     return LastInst;
8381   }
8382
8383   /// \brief Check if this slice can be merged with an expensive cross register
8384   /// bank copy. E.g.,
8385   /// i = load i32
8386   /// f = bitcast i32 i to float
8387   bool canMergeExpensiveCrossRegisterBankCopy() const {
8388     if (!Inst || !Inst->hasOneUse())
8389       return false;
8390     SDNode *Use = *Inst->use_begin();
8391     if (Use->getOpcode() != ISD::BITCAST)
8392       return false;
8393     assert(DAG && "Missing context");
8394     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8395     EVT ResVT = Use->getValueType(0);
8396     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8397     const TargetRegisterClass *ArgRC =
8398         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8399     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8400       return false;
8401
8402     // At this point, we know that we perform a cross-register-bank copy.
8403     // Check if it is expensive.
8404     const TargetRegisterInfo *TRI = TLI.getTargetMachine().getRegisterInfo();
8405     // Assume bitcasts are cheap, unless both register classes do not
8406     // explicitly share a common sub class.
8407     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8408       return false;
8409
8410     // Check if it will be merged with the load.
8411     // 1. Check the alignment constraint.
8412     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8413         ResVT.getTypeForEVT(*DAG->getContext()));
8414
8415     if (RequiredAlignment > getAlignment())
8416       return false;
8417
8418     // 2. Check that the load is a legal operation for that type.
8419     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8420       return false;
8421
8422     // 3. Check that we do not have a zext in the way.
8423     if (Inst->getValueType(0) != getLoadedType())
8424       return false;
8425
8426     return true;
8427   }
8428 };
8429 }
8430
8431 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8432 /// \p UsedBits looks like 0..0 1..1 0..0.
8433 static bool areUsedBitsDense(const APInt &UsedBits) {
8434   // If all the bits are one, this is dense!
8435   if (UsedBits.isAllOnesValue())
8436     return true;
8437
8438   // Get rid of the unused bits on the right.
8439   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8440   // Get rid of the unused bits on the left.
8441   if (NarrowedUsedBits.countLeadingZeros())
8442     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8443   // Check that the chunk of bits is completely used.
8444   return NarrowedUsedBits.isAllOnesValue();
8445 }
8446
8447 /// \brief Check whether or not \p First and \p Second are next to each other
8448 /// in memory. This means that there is no hole between the bits loaded
8449 /// by \p First and the bits loaded by \p Second.
8450 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8451                                      const LoadedSlice &Second) {
8452   assert(First.Origin == Second.Origin && First.Origin &&
8453          "Unable to match different memory origins.");
8454   APInt UsedBits = First.getUsedBits();
8455   assert((UsedBits & Second.getUsedBits()) == 0 &&
8456          "Slices are not supposed to overlap.");
8457   UsedBits |= Second.getUsedBits();
8458   return areUsedBitsDense(UsedBits);
8459 }
8460
8461 /// \brief Adjust the \p GlobalLSCost according to the target
8462 /// paring capabilities and the layout of the slices.
8463 /// \pre \p GlobalLSCost should account for at least as many loads as
8464 /// there is in the slices in \p LoadedSlices.
8465 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8466                                  LoadedSlice::Cost &GlobalLSCost) {
8467   unsigned NumberOfSlices = LoadedSlices.size();
8468   // If there is less than 2 elements, no pairing is possible.
8469   if (NumberOfSlices < 2)
8470     return;
8471
8472   // Sort the slices so that elements that are likely to be next to each
8473   // other in memory are next to each other in the list.
8474   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8475             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8476     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8477     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8478   });
8479   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8480   // First (resp. Second) is the first (resp. Second) potentially candidate
8481   // to be placed in a paired load.
8482   const LoadedSlice *First = nullptr;
8483   const LoadedSlice *Second = nullptr;
8484   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8485                 // Set the beginning of the pair.
8486                                                            First = Second) {
8487
8488     Second = &LoadedSlices[CurrSlice];
8489
8490     // If First is NULL, it means we start a new pair.
8491     // Get to the next slice.
8492     if (!First)
8493       continue;
8494
8495     EVT LoadedType = First->getLoadedType();
8496
8497     // If the types of the slices are different, we cannot pair them.
8498     if (LoadedType != Second->getLoadedType())
8499       continue;
8500
8501     // Check if the target supplies paired loads for this type.
8502     unsigned RequiredAlignment = 0;
8503     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8504       // move to the next pair, this type is hopeless.
8505       Second = nullptr;
8506       continue;
8507     }
8508     // Check if we meet the alignment requirement.
8509     if (RequiredAlignment > First->getAlignment())
8510       continue;
8511
8512     // Check that both loads are next to each other in memory.
8513     if (!areSlicesNextToEachOther(*First, *Second))
8514       continue;
8515
8516     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8517     --GlobalLSCost.Loads;
8518     // Move to the next pair.
8519     Second = nullptr;
8520   }
8521 }
8522
8523 /// \brief Check the profitability of all involved LoadedSlice.
8524 /// Currently, it is considered profitable if there is exactly two
8525 /// involved slices (1) which are (2) next to each other in memory, and
8526 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8527 ///
8528 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8529 /// the elements themselves.
8530 ///
8531 /// FIXME: When the cost model will be mature enough, we can relax
8532 /// constraints (1) and (2).
8533 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8534                                 const APInt &UsedBits, bool ForCodeSize) {
8535   unsigned NumberOfSlices = LoadedSlices.size();
8536   if (StressLoadSlicing)
8537     return NumberOfSlices > 1;
8538
8539   // Check (1).
8540   if (NumberOfSlices != 2)
8541     return false;
8542
8543   // Check (2).
8544   if (!areUsedBitsDense(UsedBits))
8545     return false;
8546
8547   // Check (3).
8548   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8549   // The original code has one big load.
8550   OrigCost.Loads = 1;
8551   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8552     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8553     // Accumulate the cost of all the slices.
8554     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8555     GlobalSlicingCost += SliceCost;
8556
8557     // Account as cost in the original configuration the gain obtained
8558     // with the current slices.
8559     OrigCost.addSliceGain(LS);
8560   }
8561
8562   // If the target supports paired load, adjust the cost accordingly.
8563   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8564   return OrigCost > GlobalSlicingCost;
8565 }
8566
8567 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8568 /// operations, split it in the various pieces being extracted.
8569 ///
8570 /// This sort of thing is introduced by SROA.
8571 /// This slicing takes care not to insert overlapping loads.
8572 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8573 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8574   if (Level < AfterLegalizeDAG)
8575     return false;
8576
8577   LoadSDNode *LD = cast<LoadSDNode>(N);
8578   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8579       !LD->getValueType(0).isInteger())
8580     return false;
8581
8582   // Keep track of already used bits to detect overlapping values.
8583   // In that case, we will just abort the transformation.
8584   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8585
8586   SmallVector<LoadedSlice, 4> LoadedSlices;
8587
8588   // Check if this load is used as several smaller chunks of bits.
8589   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8590   // of computation for each trunc.
8591   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8592        UI != UIEnd; ++UI) {
8593     // Skip the uses of the chain.
8594     if (UI.getUse().getResNo() != 0)
8595       continue;
8596
8597     SDNode *User = *UI;
8598     unsigned Shift = 0;
8599
8600     // Check if this is a trunc(lshr).
8601     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8602         isa<ConstantSDNode>(User->getOperand(1))) {
8603       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8604       User = *User->use_begin();
8605     }
8606
8607     // At this point, User is a Truncate, iff we encountered, trunc or
8608     // trunc(lshr).
8609     if (User->getOpcode() != ISD::TRUNCATE)
8610       return false;
8611
8612     // The width of the type must be a power of 2 and greater than 8-bits.
8613     // Otherwise the load cannot be represented in LLVM IR.
8614     // Moreover, if we shifted with a non-8-bits multiple, the slice
8615     // will be across several bytes. We do not support that.
8616     unsigned Width = User->getValueSizeInBits(0);
8617     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8618       return 0;
8619
8620     // Build the slice for this chain of computations.
8621     LoadedSlice LS(User, LD, Shift, &DAG);
8622     APInt CurrentUsedBits = LS.getUsedBits();
8623
8624     // Check if this slice overlaps with another.
8625     if ((CurrentUsedBits & UsedBits) != 0)
8626       return false;
8627     // Update the bits used globally.
8628     UsedBits |= CurrentUsedBits;
8629
8630     // Check if the new slice would be legal.
8631     if (!LS.isLegal())
8632       return false;
8633
8634     // Record the slice.
8635     LoadedSlices.push_back(LS);
8636   }
8637
8638   // Abort slicing if it does not seem to be profitable.
8639   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8640     return false;
8641
8642   ++SlicedLoads;
8643
8644   // Rewrite each chain to use an independent load.
8645   // By construction, each chain can be represented by a unique load.
8646
8647   // Prepare the argument for the new token factor for all the slices.
8648   SmallVector<SDValue, 8> ArgChains;
8649   for (SmallVectorImpl<LoadedSlice>::const_iterator
8650            LSIt = LoadedSlices.begin(),
8651            LSItEnd = LoadedSlices.end();
8652        LSIt != LSItEnd; ++LSIt) {
8653     SDValue SliceInst = LSIt->loadSlice();
8654     CombineTo(LSIt->Inst, SliceInst, true);
8655     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8656       SliceInst = SliceInst.getOperand(0);
8657     assert(SliceInst->getOpcode() == ISD::LOAD &&
8658            "It takes more than a zext to get to the loaded slice!!");
8659     ArgChains.push_back(SliceInst.getValue(1));
8660   }
8661
8662   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8663                               ArgChains);
8664   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8665   return true;
8666 }
8667
8668 /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
8669 /// load is having specific bytes cleared out.  If so, return the byte size
8670 /// being masked out and the shift amount.
8671 static std::pair<unsigned, unsigned>
8672 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8673   std::pair<unsigned, unsigned> Result(0, 0);
8674
8675   // Check for the structure we're looking for.
8676   if (V->getOpcode() != ISD::AND ||
8677       !isa<ConstantSDNode>(V->getOperand(1)) ||
8678       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8679     return Result;
8680
8681   // Check the chain and pointer.
8682   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8683   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8684
8685   // The store should be chained directly to the load or be an operand of a
8686   // tokenfactor.
8687   if (LD == Chain.getNode())
8688     ; // ok.
8689   else if (Chain->getOpcode() != ISD::TokenFactor)
8690     return Result; // Fail.
8691   else {
8692     bool isOk = false;
8693     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8694       if (Chain->getOperand(i).getNode() == LD) {
8695         isOk = true;
8696         break;
8697       }
8698     if (!isOk) return Result;
8699   }
8700
8701   // This only handles simple types.
8702   if (V.getValueType() != MVT::i16 &&
8703       V.getValueType() != MVT::i32 &&
8704       V.getValueType() != MVT::i64)
8705     return Result;
8706
8707   // Check the constant mask.  Invert it so that the bits being masked out are
8708   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8709   // follow the sign bit for uniformity.
8710   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8711   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8712   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8713   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8714   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8715   if (NotMaskLZ == 64) return Result;  // All zero mask.
8716
8717   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8718   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8719     return Result;
8720
8721   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8722   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8723     NotMaskLZ -= 64-V.getValueSizeInBits();
8724
8725   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8726   switch (MaskedBytes) {
8727   case 1:
8728   case 2:
8729   case 4: break;
8730   default: return Result; // All one mask, or 5-byte mask.
8731   }
8732
8733   // Verify that the first bit starts at a multiple of mask so that the access
8734   // is aligned the same as the access width.
8735   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8736
8737   Result.first = MaskedBytes;
8738   Result.second = NotMaskTZ/8;
8739   return Result;
8740 }
8741
8742
8743 /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
8744 /// provides a value as specified by MaskInfo.  If so, replace the specified
8745 /// store with a narrower store of truncated IVal.
8746 static SDNode *
8747 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8748                                 SDValue IVal, StoreSDNode *St,
8749                                 DAGCombiner *DC) {
8750   unsigned NumBytes = MaskInfo.first;
8751   unsigned ByteShift = MaskInfo.second;
8752   SelectionDAG &DAG = DC->getDAG();
8753
8754   // Check to see if IVal is all zeros in the part being masked in by the 'or'
8755   // that uses this.  If not, this is not a replacement.
8756   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
8757                                   ByteShift*8, (ByteShift+NumBytes)*8);
8758   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
8759
8760   // Check that it is legal on the target to do this.  It is legal if the new
8761   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
8762   // legalization.
8763   MVT VT = MVT::getIntegerVT(NumBytes*8);
8764   if (!DC->isTypeLegal(VT))
8765     return nullptr;
8766
8767   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
8768   // shifted by ByteShift and truncated down to NumBytes.
8769   if (ByteShift)
8770     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
8771                        DAG.getConstant(ByteShift*8,
8772                                     DC->getShiftAmountTy(IVal.getValueType())));
8773
8774   // Figure out the offset for the store and the alignment of the access.
8775   unsigned StOffset;
8776   unsigned NewAlign = St->getAlignment();
8777
8778   if (DAG.getTargetLoweringInfo().isLittleEndian())
8779     StOffset = ByteShift;
8780   else
8781     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
8782
8783   SDValue Ptr = St->getBasePtr();
8784   if (StOffset) {
8785     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
8786                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
8787     NewAlign = MinAlign(NewAlign, StOffset);
8788   }
8789
8790   // Truncate down to the new size.
8791   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
8792
8793   ++OpsNarrowed;
8794   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
8795                       St->getPointerInfo().getWithOffset(StOffset),
8796                       false, false, NewAlign).getNode();
8797 }
8798
8799
8800 /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
8801 /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
8802 /// of the loaded bits, try narrowing the load and store if it would end up
8803 /// being a win for performance or code size.
8804 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
8805   StoreSDNode *ST  = cast<StoreSDNode>(N);
8806   if (ST->isVolatile())
8807     return SDValue();
8808
8809   SDValue Chain = ST->getChain();
8810   SDValue Value = ST->getValue();
8811   SDValue Ptr   = ST->getBasePtr();
8812   EVT VT = Value.getValueType();
8813
8814   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
8815     return SDValue();
8816
8817   unsigned Opc = Value.getOpcode();
8818
8819   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
8820   // is a byte mask indicating a consecutive number of bytes, check to see if
8821   // Y is known to provide just those bytes.  If so, we try to replace the
8822   // load + replace + store sequence with a single (narrower) store, which makes
8823   // the load dead.
8824   if (Opc == ISD::OR) {
8825     std::pair<unsigned, unsigned> MaskedLoad;
8826     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
8827     if (MaskedLoad.first)
8828       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8829                                                   Value.getOperand(1), ST,this))
8830         return SDValue(NewST, 0);
8831
8832     // Or is commutative, so try swapping X and Y.
8833     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
8834     if (MaskedLoad.first)
8835       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
8836                                                   Value.getOperand(0), ST,this))
8837         return SDValue(NewST, 0);
8838   }
8839
8840   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
8841       Value.getOperand(1).getOpcode() != ISD::Constant)
8842     return SDValue();
8843
8844   SDValue N0 = Value.getOperand(0);
8845   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
8846       Chain == SDValue(N0.getNode(), 1)) {
8847     LoadSDNode *LD = cast<LoadSDNode>(N0);
8848     if (LD->getBasePtr() != Ptr ||
8849         LD->getPointerInfo().getAddrSpace() !=
8850         ST->getPointerInfo().getAddrSpace())
8851       return SDValue();
8852
8853     // Find the type to narrow it the load / op / store to.
8854     SDValue N1 = Value.getOperand(1);
8855     unsigned BitWidth = N1.getValueSizeInBits();
8856     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
8857     if (Opc == ISD::AND)
8858       Imm ^= APInt::getAllOnesValue(BitWidth);
8859     if (Imm == 0 || Imm.isAllOnesValue())
8860       return SDValue();
8861     unsigned ShAmt = Imm.countTrailingZeros();
8862     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
8863     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
8864     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8865     while (NewBW < BitWidth &&
8866            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
8867              TLI.isNarrowingProfitable(VT, NewVT))) {
8868       NewBW = NextPowerOf2(NewBW);
8869       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
8870     }
8871     if (NewBW >= BitWidth)
8872       return SDValue();
8873
8874     // If the lsb changed does not start at the type bitwidth boundary,
8875     // start at the previous one.
8876     if (ShAmt % NewBW)
8877       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
8878     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
8879                                    std::min(BitWidth, ShAmt + NewBW));
8880     if ((Imm & Mask) == Imm) {
8881       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
8882       if (Opc == ISD::AND)
8883         NewImm ^= APInt::getAllOnesValue(NewBW);
8884       uint64_t PtrOff = ShAmt / 8;
8885       // For big endian targets, we need to adjust the offset to the pointer to
8886       // load the correct bytes.
8887       if (TLI.isBigEndian())
8888         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
8889
8890       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
8891       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
8892       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
8893         return SDValue();
8894
8895       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
8896                                    Ptr.getValueType(), Ptr,
8897                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
8898       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
8899                                   LD->getChain(), NewPtr,
8900                                   LD->getPointerInfo().getWithOffset(PtrOff),
8901                                   LD->isVolatile(), LD->isNonTemporal(),
8902                                   LD->isInvariant(), NewAlign,
8903                                   LD->getAAInfo());
8904       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
8905                                    DAG.getConstant(NewImm, NewVT));
8906       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
8907                                    NewVal, NewPtr,
8908                                    ST->getPointerInfo().getWithOffset(PtrOff),
8909                                    false, false, NewAlign);
8910
8911       AddToWorklist(NewPtr.getNode());
8912       AddToWorklist(NewLD.getNode());
8913       AddToWorklist(NewVal.getNode());
8914       WorklistRemover DeadNodes(*this);
8915       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
8916       ++OpsNarrowed;
8917       return NewST;
8918     }
8919   }
8920
8921   return SDValue();
8922 }
8923
8924 /// TransformFPLoadStorePair - For a given floating point load / store pair,
8925 /// if the load value isn't used by any other operations, then consider
8926 /// transforming the pair to integer load / store operations if the target
8927 /// deems the transformation profitable.
8928 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
8929   StoreSDNode *ST  = cast<StoreSDNode>(N);
8930   SDValue Chain = ST->getChain();
8931   SDValue Value = ST->getValue();
8932   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
8933       Value.hasOneUse() &&
8934       Chain == SDValue(Value.getNode(), 1)) {
8935     LoadSDNode *LD = cast<LoadSDNode>(Value);
8936     EVT VT = LD->getMemoryVT();
8937     if (!VT.isFloatingPoint() ||
8938         VT != ST->getMemoryVT() ||
8939         LD->isNonTemporal() ||
8940         ST->isNonTemporal() ||
8941         LD->getPointerInfo().getAddrSpace() != 0 ||
8942         ST->getPointerInfo().getAddrSpace() != 0)
8943       return SDValue();
8944
8945     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
8946     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
8947         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
8948         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
8949         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
8950       return SDValue();
8951
8952     unsigned LDAlign = LD->getAlignment();
8953     unsigned STAlign = ST->getAlignment();
8954     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
8955     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
8956     if (LDAlign < ABIAlign || STAlign < ABIAlign)
8957       return SDValue();
8958
8959     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
8960                                 LD->getChain(), LD->getBasePtr(),
8961                                 LD->getPointerInfo(),
8962                                 false, false, false, LDAlign);
8963
8964     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
8965                                  NewLD, ST->getBasePtr(),
8966                                  ST->getPointerInfo(),
8967                                  false, false, STAlign);
8968
8969     AddToWorklist(NewLD.getNode());
8970     AddToWorklist(NewST.getNode());
8971     WorklistRemover DeadNodes(*this);
8972     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
8973     ++LdStFP2Int;
8974     return NewST;
8975   }
8976
8977   return SDValue();
8978 }
8979
8980 /// Helper struct to parse and store a memory address as base + index + offset.
8981 /// We ignore sign extensions when it is safe to do so.
8982 /// The following two expressions are not equivalent. To differentiate we need
8983 /// to store whether there was a sign extension involved in the index
8984 /// computation.
8985 ///  (load (i64 add (i64 copyfromreg %c)
8986 ///                 (i64 signextend (add (i8 load %index)
8987 ///                                      (i8 1))))
8988 /// vs
8989 ///
8990 /// (load (i64 add (i64 copyfromreg %c)
8991 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
8992 ///                                         (i32 1)))))
8993 struct BaseIndexOffset {
8994   SDValue Base;
8995   SDValue Index;
8996   int64_t Offset;
8997   bool IsIndexSignExt;
8998
8999   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9000
9001   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9002                   bool IsIndexSignExt) :
9003     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9004
9005   bool equalBaseIndex(const BaseIndexOffset &Other) {
9006     return Other.Base == Base && Other.Index == Index &&
9007       Other.IsIndexSignExt == IsIndexSignExt;
9008   }
9009
9010   /// Parses tree in Ptr for base, index, offset addresses.
9011   static BaseIndexOffset match(SDValue Ptr) {
9012     bool IsIndexSignExt = false;
9013
9014     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9015     // instruction, then it could be just the BASE or everything else we don't
9016     // know how to handle. Just use Ptr as BASE and give up.
9017     if (Ptr->getOpcode() != ISD::ADD)
9018       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9019
9020     // We know that we have at least an ADD instruction. Try to pattern match
9021     // the simple case of BASE + OFFSET.
9022     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9023       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9024       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9025                               IsIndexSignExt);
9026     }
9027
9028     // Inside a loop the current BASE pointer is calculated using an ADD and a
9029     // MUL instruction. In this case Ptr is the actual BASE pointer.
9030     // (i64 add (i64 %array_ptr)
9031     //          (i64 mul (i64 %induction_var)
9032     //                   (i64 %element_size)))
9033     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9034       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9035
9036     // Look at Base + Index + Offset cases.
9037     SDValue Base = Ptr->getOperand(0);
9038     SDValue IndexOffset = Ptr->getOperand(1);
9039
9040     // Skip signextends.
9041     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9042       IndexOffset = IndexOffset->getOperand(0);
9043       IsIndexSignExt = true;
9044     }
9045
9046     // Either the case of Base + Index (no offset) or something else.
9047     if (IndexOffset->getOpcode() != ISD::ADD)
9048       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9049
9050     // Now we have the case of Base + Index + offset.
9051     SDValue Index = IndexOffset->getOperand(0);
9052     SDValue Offset = IndexOffset->getOperand(1);
9053
9054     if (!isa<ConstantSDNode>(Offset))
9055       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9056
9057     // Ignore signextends.
9058     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9059       Index = Index->getOperand(0);
9060       IsIndexSignExt = true;
9061     } else IsIndexSignExt = false;
9062
9063     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9064     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9065   }
9066 };
9067
9068 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9069 /// is located in a sequence of memory operations connected by a chain.
9070 struct MemOpLink {
9071   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9072     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9073   // Ptr to the mem node.
9074   LSBaseSDNode *MemNode;
9075   // Offset from the base ptr.
9076   int64_t OffsetFromBase;
9077   // What is the sequence number of this mem node.
9078   // Lowest mem operand in the DAG starts at zero.
9079   unsigned SequenceNum;
9080 };
9081
9082 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9083   EVT MemVT = St->getMemoryVT();
9084   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9085   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9086     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9087
9088   // Don't merge vectors into wider inputs.
9089   if (MemVT.isVector() || !MemVT.isSimple())
9090     return false;
9091
9092   // Perform an early exit check. Do not bother looking at stored values that
9093   // are not constants or loads.
9094   SDValue StoredVal = St->getValue();
9095   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9096   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9097       !IsLoadSrc)
9098     return false;
9099
9100   // Only look at ends of store sequences.
9101   SDValue Chain = SDValue(St, 0);
9102   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9103     return false;
9104
9105   // This holds the base pointer, index, and the offset in bytes from the base
9106   // pointer.
9107   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9108
9109   // We must have a base and an offset.
9110   if (!BasePtr.Base.getNode())
9111     return false;
9112
9113   // Do not handle stores to undef base pointers.
9114   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9115     return false;
9116
9117   // Save the LoadSDNodes that we find in the chain.
9118   // We need to make sure that these nodes do not interfere with
9119   // any of the store nodes.
9120   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9121
9122   // Save the StoreSDNodes that we find in the chain.
9123   SmallVector<MemOpLink, 8> StoreNodes;
9124
9125   // Walk up the chain and look for nodes with offsets from the same
9126   // base pointer. Stop when reaching an instruction with a different kind
9127   // or instruction which has a different base pointer.
9128   unsigned Seq = 0;
9129   StoreSDNode *Index = St;
9130   while (Index) {
9131     // If the chain has more than one use, then we can't reorder the mem ops.
9132     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9133       break;
9134
9135     // Find the base pointer and offset for this memory node.
9136     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9137
9138     // Check that the base pointer is the same as the original one.
9139     if (!Ptr.equalBaseIndex(BasePtr))
9140       break;
9141
9142     // Check that the alignment is the same.
9143     if (Index->getAlignment() != St->getAlignment())
9144       break;
9145
9146     // The memory operands must not be volatile.
9147     if (Index->isVolatile() || Index->isIndexed())
9148       break;
9149
9150     // No truncation.
9151     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9152       if (St->isTruncatingStore())
9153         break;
9154
9155     // The stored memory type must be the same.
9156     if (Index->getMemoryVT() != MemVT)
9157       break;
9158
9159     // We do not allow unaligned stores because we want to prevent overriding
9160     // stores.
9161     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9162       break;
9163
9164     // We found a potential memory operand to merge.
9165     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9166
9167     // Find the next memory operand in the chain. If the next operand in the
9168     // chain is a store then move up and continue the scan with the next
9169     // memory operand. If the next operand is a load save it and use alias
9170     // information to check if it interferes with anything.
9171     SDNode *NextInChain = Index->getChain().getNode();
9172     while (1) {
9173       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9174         // We found a store node. Use it for the next iteration.
9175         Index = STn;
9176         break;
9177       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9178         if (Ldn->isVolatile()) {
9179           Index = nullptr;
9180           break;
9181         }
9182
9183         // Save the load node for later. Continue the scan.
9184         AliasLoadNodes.push_back(Ldn);
9185         NextInChain = Ldn->getChain().getNode();
9186         continue;
9187       } else {
9188         Index = nullptr;
9189         break;
9190       }
9191     }
9192   }
9193
9194   // Check if there is anything to merge.
9195   if (StoreNodes.size() < 2)
9196     return false;
9197
9198   // Sort the memory operands according to their distance from the base pointer.
9199   std::sort(StoreNodes.begin(), StoreNodes.end(),
9200             [](MemOpLink LHS, MemOpLink RHS) {
9201     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9202            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9203             LHS.SequenceNum > RHS.SequenceNum);
9204   });
9205
9206   // Scan the memory operations on the chain and find the first non-consecutive
9207   // store memory address.
9208   unsigned LastConsecutiveStore = 0;
9209   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9210   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9211
9212     // Check that the addresses are consecutive starting from the second
9213     // element in the list of stores.
9214     if (i > 0) {
9215       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9216       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9217         break;
9218     }
9219
9220     bool Alias = false;
9221     // Check if this store interferes with any of the loads that we found.
9222     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9223       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9224         Alias = true;
9225         break;
9226       }
9227     // We found a load that alias with this store. Stop the sequence.
9228     if (Alias)
9229       break;
9230
9231     // Mark this node as useful.
9232     LastConsecutiveStore = i;
9233   }
9234
9235   // The node with the lowest store address.
9236   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9237
9238   // Store the constants into memory as one consecutive store.
9239   if (!IsLoadSrc) {
9240     unsigned LastLegalType = 0;
9241     unsigned LastLegalVectorType = 0;
9242     bool NonZero = false;
9243     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9244       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9245       SDValue StoredVal = St->getValue();
9246
9247       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9248         NonZero |= !C->isNullValue();
9249       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9250         NonZero |= !C->getConstantFPValue()->isNullValue();
9251       } else {
9252         // Non-constant.
9253         break;
9254       }
9255
9256       // Find a legal type for the constant store.
9257       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9258       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9259       if (TLI.isTypeLegal(StoreTy))
9260         LastLegalType = i+1;
9261       // Or check whether a truncstore is legal.
9262       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9263                TargetLowering::TypePromoteInteger) {
9264         EVT LegalizedStoredValueTy =
9265           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9266         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9267           LastLegalType = i+1;
9268       }
9269
9270       // Find a legal type for the vector store.
9271       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9272       if (TLI.isTypeLegal(Ty))
9273         LastLegalVectorType = i + 1;
9274     }
9275
9276     // We only use vectors if the constant is known to be zero and the
9277     // function is not marked with the noimplicitfloat attribute.
9278     if (NonZero || NoVectors)
9279       LastLegalVectorType = 0;
9280
9281     // Check if we found a legal integer type to store.
9282     if (LastLegalType == 0 && LastLegalVectorType == 0)
9283       return false;
9284
9285     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9286     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9287
9288     // Make sure we have something to merge.
9289     if (NumElem < 2)
9290       return false;
9291
9292     unsigned EarliestNodeUsed = 0;
9293     for (unsigned i=0; i < NumElem; ++i) {
9294       // Find a chain for the new wide-store operand. Notice that some
9295       // of the store nodes that we found may not be selected for inclusion
9296       // in the wide store. The chain we use needs to be the chain of the
9297       // earliest store node which is *used* and replaced by the wide store.
9298       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9299         EarliestNodeUsed = i;
9300     }
9301
9302     // The earliest Node in the DAG.
9303     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9304     SDLoc DL(StoreNodes[0].MemNode);
9305
9306     SDValue StoredVal;
9307     if (UseVector) {
9308       // Find a legal type for the vector store.
9309       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9310       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9311       StoredVal = DAG.getConstant(0, Ty);
9312     } else {
9313       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9314       APInt StoreInt(StoreBW, 0);
9315
9316       // Construct a single integer constant which is made of the smaller
9317       // constant inputs.
9318       bool IsLE = TLI.isLittleEndian();
9319       for (unsigned i = 0; i < NumElem ; ++i) {
9320         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9321         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9322         SDValue Val = St->getValue();
9323         StoreInt<<=ElementSizeBytes*8;
9324         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9325           StoreInt|=C->getAPIntValue().zext(StoreBW);
9326         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9327           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9328         } else {
9329           assert(false && "Invalid constant element type");
9330         }
9331       }
9332
9333       // Create the new Load and Store operations.
9334       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9335       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9336     }
9337
9338     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9339                                     FirstInChain->getBasePtr(),
9340                                     FirstInChain->getPointerInfo(),
9341                                     false, false,
9342                                     FirstInChain->getAlignment());
9343
9344     // Replace the first store with the new store
9345     CombineTo(EarliestOp, NewStore);
9346     // Erase all other stores.
9347     for (unsigned i = 0; i < NumElem ; ++i) {
9348       if (StoreNodes[i].MemNode == EarliestOp)
9349         continue;
9350       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9351       // ReplaceAllUsesWith will replace all uses that existed when it was
9352       // called, but graph optimizations may cause new ones to appear. For
9353       // example, the case in pr14333 looks like
9354       //
9355       //  St's chain -> St -> another store -> X
9356       //
9357       // And the only difference from St to the other store is the chain.
9358       // When we change it's chain to be St's chain they become identical,
9359       // get CSEed and the net result is that X is now a use of St.
9360       // Since we know that St is redundant, just iterate.
9361       while (!St->use_empty())
9362         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9363       removeFromWorklist(St);
9364       DAG.DeleteNode(St);
9365     }
9366
9367     return true;
9368   }
9369
9370   // Below we handle the case of multiple consecutive stores that
9371   // come from multiple consecutive loads. We merge them into a single
9372   // wide load and a single wide store.
9373
9374   // Look for load nodes which are used by the stored values.
9375   SmallVector<MemOpLink, 8> LoadNodes;
9376
9377   // Find acceptable loads. Loads need to have the same chain (token factor),
9378   // must not be zext, volatile, indexed, and they must be consecutive.
9379   BaseIndexOffset LdBasePtr;
9380   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9381     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9382     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9383     if (!Ld) break;
9384
9385     // Loads must only have one use.
9386     if (!Ld->hasNUsesOfValue(1, 0))
9387       break;
9388
9389     // Check that the alignment is the same as the stores.
9390     if (Ld->getAlignment() != St->getAlignment())
9391       break;
9392
9393     // The memory operands must not be volatile.
9394     if (Ld->isVolatile() || Ld->isIndexed())
9395       break;
9396
9397     // We do not accept ext loads.
9398     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9399       break;
9400
9401     // The stored memory type must be the same.
9402     if (Ld->getMemoryVT() != MemVT)
9403       break;
9404
9405     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9406     // If this is not the first ptr that we check.
9407     if (LdBasePtr.Base.getNode()) {
9408       // The base ptr must be the same.
9409       if (!LdPtr.equalBaseIndex(LdBasePtr))
9410         break;
9411     } else {
9412       // Check that all other base pointers are the same as this one.
9413       LdBasePtr = LdPtr;
9414     }
9415
9416     // We found a potential memory operand to merge.
9417     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9418   }
9419
9420   if (LoadNodes.size() < 2)
9421     return false;
9422
9423   // Scan the memory operations on the chain and find the first non-consecutive
9424   // load memory address. These variables hold the index in the store node
9425   // array.
9426   unsigned LastConsecutiveLoad = 0;
9427   // This variable refers to the size and not index in the array.
9428   unsigned LastLegalVectorType = 0;
9429   unsigned LastLegalIntegerType = 0;
9430   StartAddress = LoadNodes[0].OffsetFromBase;
9431   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9432   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9433     // All loads much share the same chain.
9434     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9435       break;
9436
9437     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9438     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9439       break;
9440     LastConsecutiveLoad = i;
9441
9442     // Find a legal type for the vector store.
9443     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9444     if (TLI.isTypeLegal(StoreTy))
9445       LastLegalVectorType = i + 1;
9446
9447     // Find a legal type for the integer store.
9448     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9449     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9450     if (TLI.isTypeLegal(StoreTy))
9451       LastLegalIntegerType = i + 1;
9452     // Or check whether a truncstore and extload is legal.
9453     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9454              TargetLowering::TypePromoteInteger) {
9455       EVT LegalizedStoredValueTy =
9456         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9457       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9458           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9459           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9460           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9461         LastLegalIntegerType = i+1;
9462     }
9463   }
9464
9465   // Only use vector types if the vector type is larger than the integer type.
9466   // If they are the same, use integers.
9467   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9468   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9469
9470   // We add +1 here because the LastXXX variables refer to location while
9471   // the NumElem refers to array/index size.
9472   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9473   NumElem = std::min(LastLegalType, NumElem);
9474
9475   if (NumElem < 2)
9476     return false;
9477
9478   // The earliest Node in the DAG.
9479   unsigned EarliestNodeUsed = 0;
9480   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9481   for (unsigned i=1; i<NumElem; ++i) {
9482     // Find a chain for the new wide-store operand. Notice that some
9483     // of the store nodes that we found may not be selected for inclusion
9484     // in the wide store. The chain we use needs to be the chain of the
9485     // earliest store node which is *used* and replaced by the wide store.
9486     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9487       EarliestNodeUsed = i;
9488   }
9489
9490   // Find if it is better to use vectors or integers to load and store
9491   // to memory.
9492   EVT JointMemOpVT;
9493   if (UseVectorTy) {
9494     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9495   } else {
9496     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9497     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9498   }
9499
9500   SDLoc LoadDL(LoadNodes[0].MemNode);
9501   SDLoc StoreDL(StoreNodes[0].MemNode);
9502
9503   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9504   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9505                                 FirstLoad->getChain(),
9506                                 FirstLoad->getBasePtr(),
9507                                 FirstLoad->getPointerInfo(),
9508                                 false, false, false,
9509                                 FirstLoad->getAlignment());
9510
9511   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9512                                   FirstInChain->getBasePtr(),
9513                                   FirstInChain->getPointerInfo(), false, false,
9514                                   FirstInChain->getAlignment());
9515
9516   // Replace one of the loads with the new load.
9517   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9518   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9519                                 SDValue(NewLoad.getNode(), 1));
9520
9521   // Remove the rest of the load chains.
9522   for (unsigned i = 1; i < NumElem ; ++i) {
9523     // Replace all chain users of the old load nodes with the chain of the new
9524     // load node.
9525     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9526     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9527   }
9528
9529   // Replace the first store with the new store.
9530   CombineTo(EarliestOp, NewStore);
9531   // Erase all other stores.
9532   for (unsigned i = 0; i < NumElem ; ++i) {
9533     // Remove all Store nodes.
9534     if (StoreNodes[i].MemNode == EarliestOp)
9535       continue;
9536     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9537     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9538     removeFromWorklist(St);
9539     DAG.DeleteNode(St);
9540   }
9541
9542   return true;
9543 }
9544
9545 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9546   StoreSDNode *ST  = cast<StoreSDNode>(N);
9547   SDValue Chain = ST->getChain();
9548   SDValue Value = ST->getValue();
9549   SDValue Ptr   = ST->getBasePtr();
9550
9551   // If this is a store of a bit convert, store the input value if the
9552   // resultant store does not need a higher alignment than the original.
9553   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9554       ST->isUnindexed()) {
9555     unsigned OrigAlign = ST->getAlignment();
9556     EVT SVT = Value.getOperand(0).getValueType();
9557     unsigned Align = TLI.getDataLayout()->
9558       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9559     if (Align <= OrigAlign &&
9560         ((!LegalOperations && !ST->isVolatile()) ||
9561          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9562       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9563                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9564                           ST->isNonTemporal(), OrigAlign,
9565                           ST->getAAInfo());
9566   }
9567
9568   // Turn 'store undef, Ptr' -> nothing.
9569   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9570     return Chain;
9571
9572   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9573   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9574     // NOTE: If the original store is volatile, this transform must not increase
9575     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9576     // processor operation but an i64 (which is not legal) requires two.  So the
9577     // transform should not be done in this case.
9578     if (Value.getOpcode() != ISD::TargetConstantFP) {
9579       SDValue Tmp;
9580       switch (CFP->getSimpleValueType(0).SimpleTy) {
9581       default: llvm_unreachable("Unknown FP type");
9582       case MVT::f16:    // We don't do this for these yet.
9583       case MVT::f80:
9584       case MVT::f128:
9585       case MVT::ppcf128:
9586         break;
9587       case MVT::f32:
9588         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9589             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9590           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9591                               bitcastToAPInt().getZExtValue(), MVT::i32);
9592           return DAG.getStore(Chain, SDLoc(N), Tmp,
9593                               Ptr, ST->getMemOperand());
9594         }
9595         break;
9596       case MVT::f64:
9597         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9598              !ST->isVolatile()) ||
9599             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9600           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9601                                 getZExtValue(), MVT::i64);
9602           return DAG.getStore(Chain, SDLoc(N), Tmp,
9603                               Ptr, ST->getMemOperand());
9604         }
9605
9606         if (!ST->isVolatile() &&
9607             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9608           // Many FP stores are not made apparent until after legalize, e.g. for
9609           // argument passing.  Since this is so common, custom legalize the
9610           // 64-bit integer store into two 32-bit stores.
9611           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9612           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9613           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9614           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9615
9616           unsigned Alignment = ST->getAlignment();
9617           bool isVolatile = ST->isVolatile();
9618           bool isNonTemporal = ST->isNonTemporal();
9619           AAMDNodes AAInfo = ST->getAAInfo();
9620
9621           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9622                                      Ptr, ST->getPointerInfo(),
9623                                      isVolatile, isNonTemporal,
9624                                      ST->getAlignment(), AAInfo);
9625           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9626                             DAG.getConstant(4, Ptr.getValueType()));
9627           Alignment = MinAlign(Alignment, 4U);
9628           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9629                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9630                                      isVolatile, isNonTemporal,
9631                                      Alignment, AAInfo);
9632           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9633                              St0, St1);
9634         }
9635
9636         break;
9637       }
9638     }
9639   }
9640
9641   // Try to infer better alignment information than the store already has.
9642   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9643     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9644       if (Align > ST->getAlignment())
9645         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9646                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9647                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9648                                  ST->getAAInfo());
9649     }
9650   }
9651
9652   // Try transforming a pair floating point load / store ops to integer
9653   // load / store ops.
9654   SDValue NewST = TransformFPLoadStorePair(N);
9655   if (NewST.getNode())
9656     return NewST;
9657
9658   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA :
9659     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
9660 #ifndef NDEBUG
9661   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9662       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9663     UseAA = false;
9664 #endif
9665   if (UseAA && ST->isUnindexed()) {
9666     // Walk up chain skipping non-aliasing memory nodes.
9667     SDValue BetterChain = FindBetterChain(N, Chain);
9668
9669     // If there is a better chain.
9670     if (Chain != BetterChain) {
9671       SDValue ReplStore;
9672
9673       // Replace the chain to avoid dependency.
9674       if (ST->isTruncatingStore()) {
9675         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9676                                       ST->getMemoryVT(), ST->getMemOperand());
9677       } else {
9678         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9679                                  ST->getMemOperand());
9680       }
9681
9682       // Create token to keep both nodes around.
9683       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9684                                   MVT::Other, Chain, ReplStore);
9685
9686       // Make sure the new and old chains are cleaned up.
9687       AddToWorklist(Token.getNode());
9688
9689       // Don't add users to work list.
9690       return CombineTo(N, Token, false);
9691     }
9692   }
9693
9694   // Try transforming N to an indexed store.
9695   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9696     return SDValue(N, 0);
9697
9698   // FIXME: is there such a thing as a truncating indexed store?
9699   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9700       Value.getValueType().isInteger()) {
9701     // See if we can simplify the input to this truncstore with knowledge that
9702     // only the low bits are being used.  For example:
9703     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9704     SDValue Shorter =
9705       GetDemandedBits(Value,
9706                       APInt::getLowBitsSet(
9707                         Value.getValueType().getScalarType().getSizeInBits(),
9708                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9709     AddToWorklist(Value.getNode());
9710     if (Shorter.getNode())
9711       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9712                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9713
9714     // Otherwise, see if we can simplify the operation with
9715     // SimplifyDemandedBits, which only works if the value has a single use.
9716     if (SimplifyDemandedBits(Value,
9717                         APInt::getLowBitsSet(
9718                           Value.getValueType().getScalarType().getSizeInBits(),
9719                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9720       return SDValue(N, 0);
9721   }
9722
9723   // If this is a load followed by a store to the same location, then the store
9724   // is dead/noop.
9725   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9726     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9727         ST->isUnindexed() && !ST->isVolatile() &&
9728         // There can't be any side effects between the load and store, such as
9729         // a call or store.
9730         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9731       // The store is dead, remove it.
9732       return Chain;
9733     }
9734   }
9735
9736   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9737   // truncating store.  We can do this even if this is already a truncstore.
9738   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
9739       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
9740       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
9741                             ST->getMemoryVT())) {
9742     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
9743                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
9744   }
9745
9746   // Only perform this optimization before the types are legal, because we
9747   // don't want to perform this optimization on every DAGCombine invocation.
9748   if (!LegalTypes) {
9749     bool EverChanged = false;
9750
9751     do {
9752       // There can be multiple store sequences on the same chain.
9753       // Keep trying to merge store sequences until we are unable to do so
9754       // or until we merge the last store on the chain.
9755       bool Changed = MergeConsecutiveStores(ST);
9756       EverChanged |= Changed;
9757       if (!Changed) break;
9758     } while (ST->getOpcode() != ISD::DELETED_NODE);
9759
9760     if (EverChanged)
9761       return SDValue(N, 0);
9762   }
9763
9764   return ReduceLoadOpStoreWidth(N);
9765 }
9766
9767 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
9768   SDValue InVec = N->getOperand(0);
9769   SDValue InVal = N->getOperand(1);
9770   SDValue EltNo = N->getOperand(2);
9771   SDLoc dl(N);
9772
9773   // If the inserted element is an UNDEF, just use the input vector.
9774   if (InVal.getOpcode() == ISD::UNDEF)
9775     return InVec;
9776
9777   EVT VT = InVec.getValueType();
9778
9779   // If we can't generate a legal BUILD_VECTOR, exit
9780   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
9781     return SDValue();
9782
9783   // Check that we know which element is being inserted
9784   if (!isa<ConstantSDNode>(EltNo))
9785     return SDValue();
9786   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9787
9788   // Canonicalize insert_vector_elt dag nodes.
9789   // Example:
9790   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
9791   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
9792   //
9793   // Do this only if the child insert_vector node has one use; also
9794   // do this only if indices are both constants and Idx1 < Idx0.
9795   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
9796       && isa<ConstantSDNode>(InVec.getOperand(2))) {
9797     unsigned OtherElt =
9798       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
9799     if (Elt < OtherElt) {
9800       // Swap nodes.
9801       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
9802                                   InVec.getOperand(0), InVal, EltNo);
9803       AddToWorklist(NewOp.getNode());
9804       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
9805                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
9806     }
9807   }
9808
9809   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
9810   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
9811   // vector elements.
9812   SmallVector<SDValue, 8> Ops;
9813   // Do not combine these two vectors if the output vector will not replace
9814   // the input vector.
9815   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
9816     Ops.append(InVec.getNode()->op_begin(),
9817                InVec.getNode()->op_end());
9818   } else if (InVec.getOpcode() == ISD::UNDEF) {
9819     unsigned NElts = VT.getVectorNumElements();
9820     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
9821   } else {
9822     return SDValue();
9823   }
9824
9825   // Insert the element
9826   if (Elt < Ops.size()) {
9827     // All the operands of BUILD_VECTOR must have the same type;
9828     // we enforce that here.
9829     EVT OpVT = Ops[0].getValueType();
9830     if (InVal.getValueType() != OpVT)
9831       InVal = OpVT.bitsGT(InVal.getValueType()) ?
9832                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
9833                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
9834     Ops[Elt] = InVal;
9835   }
9836
9837   // Return the new vector
9838   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
9839 }
9840
9841 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
9842   // (vextract (scalar_to_vector val, 0) -> val
9843   SDValue InVec = N->getOperand(0);
9844   EVT VT = InVec.getValueType();
9845   EVT NVT = N->getValueType(0);
9846
9847   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
9848     // Check if the result type doesn't match the inserted element type. A
9849     // SCALAR_TO_VECTOR may truncate the inserted element and the
9850     // EXTRACT_VECTOR_ELT may widen the extracted vector.
9851     SDValue InOp = InVec.getOperand(0);
9852     if (InOp.getValueType() != NVT) {
9853       assert(InOp.getValueType().isInteger() && NVT.isInteger());
9854       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
9855     }
9856     return InOp;
9857   }
9858
9859   SDValue EltNo = N->getOperand(1);
9860   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
9861
9862   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
9863   // We only perform this optimization before the op legalization phase because
9864   // we may introduce new vector instructions which are not backed by TD
9865   // patterns. For example on AVX, extracting elements from a wide vector
9866   // without using extract_subvector. However, if we can find an underlying
9867   // scalar value, then we can always use that.
9868   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
9869       && ConstEltNo) {
9870     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9871     int NumElem = VT.getVectorNumElements();
9872     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
9873     // Find the new index to extract from.
9874     int OrigElt = SVOp->getMaskElt(Elt);
9875
9876     // Extracting an undef index is undef.
9877     if (OrigElt == -1)
9878       return DAG.getUNDEF(NVT);
9879
9880     // Select the right vector half to extract from.
9881     SDValue SVInVec;
9882     if (OrigElt < NumElem) {
9883       SVInVec = InVec->getOperand(0);
9884     } else {
9885       SVInVec = InVec->getOperand(1);
9886       OrigElt -= NumElem;
9887     }
9888
9889     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
9890       SDValue InOp = SVInVec.getOperand(OrigElt);
9891       if (InOp.getValueType() != NVT) {
9892         assert(InOp.getValueType().isInteger() && NVT.isInteger());
9893         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
9894       }
9895
9896       return InOp;
9897     }
9898
9899     // FIXME: We should handle recursing on other vector shuffles and
9900     // scalar_to_vector here as well.
9901
9902     if (!LegalOperations) {
9903       EVT IndexTy = TLI.getVectorIdxTy();
9904       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
9905                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
9906     }
9907   }
9908
9909   // Perform only after legalization to ensure build_vector / vector_shuffle
9910   // optimizations have already been done.
9911   if (!LegalOperations) return SDValue();
9912
9913   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
9914   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
9915   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
9916
9917   if (ConstEltNo) {
9918     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
9919     bool NewLoad = false;
9920     bool BCNumEltsChanged = false;
9921     EVT ExtVT = VT.getVectorElementType();
9922     EVT LVT = ExtVT;
9923
9924     // If the result of load has to be truncated, then it's not necessarily
9925     // profitable.
9926     if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
9927       return SDValue();
9928
9929     if (InVec.getOpcode() == ISD::BITCAST) {
9930       // Don't duplicate a load with other uses.
9931       if (!InVec.hasOneUse())
9932         return SDValue();
9933
9934       EVT BCVT = InVec.getOperand(0).getValueType();
9935       if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
9936         return SDValue();
9937       if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
9938         BCNumEltsChanged = true;
9939       InVec = InVec.getOperand(0);
9940       ExtVT = BCVT.getVectorElementType();
9941       NewLoad = true;
9942     }
9943
9944     LoadSDNode *LN0 = nullptr;
9945     const ShuffleVectorSDNode *SVN = nullptr;
9946     if (ISD::isNormalLoad(InVec.getNode())) {
9947       LN0 = cast<LoadSDNode>(InVec);
9948     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
9949                InVec.getOperand(0).getValueType() == ExtVT &&
9950                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
9951       // Don't duplicate a load with other uses.
9952       if (!InVec.hasOneUse())
9953         return SDValue();
9954
9955       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
9956     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
9957       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
9958       // =>
9959       // (load $addr+1*size)
9960
9961       // Don't duplicate a load with other uses.
9962       if (!InVec.hasOneUse())
9963         return SDValue();
9964
9965       // If the bit convert changed the number of elements, it is unsafe
9966       // to examine the mask.
9967       if (BCNumEltsChanged)
9968         return SDValue();
9969
9970       // Select the input vector, guarding against out of range extract vector.
9971       unsigned NumElems = VT.getVectorNumElements();
9972       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
9973       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
9974
9975       if (InVec.getOpcode() == ISD::BITCAST) {
9976         // Don't duplicate a load with other uses.
9977         if (!InVec.hasOneUse())
9978           return SDValue();
9979
9980         InVec = InVec.getOperand(0);
9981       }
9982       if (ISD::isNormalLoad(InVec.getNode())) {
9983         LN0 = cast<LoadSDNode>(InVec);
9984         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
9985       }
9986     }
9987
9988     // Make sure we found a non-volatile load and the extractelement is
9989     // the only use.
9990     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
9991       return SDValue();
9992
9993     // If Idx was -1 above, Elt is going to be -1, so just return undef.
9994     if (Elt == -1)
9995       return DAG.getUNDEF(LVT);
9996
9997     unsigned Align = LN0->getAlignment();
9998     if (NewLoad) {
9999       // Check the resultant load doesn't need a higher alignment than the
10000       // original load.
10001       unsigned NewAlign =
10002         TLI.getDataLayout()
10003             ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
10004
10005       if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
10006         return SDValue();
10007
10008       Align = NewAlign;
10009     }
10010
10011     SDValue NewPtr = LN0->getBasePtr();
10012     unsigned PtrOff = 0;
10013
10014     if (Elt) {
10015       PtrOff = LVT.getSizeInBits() * Elt / 8;
10016       EVT PtrType = NewPtr.getValueType();
10017       if (TLI.isBigEndian())
10018         PtrOff = VT.getSizeInBits() / 8 - PtrOff;
10019       NewPtr = DAG.getNode(ISD::ADD, SDLoc(N), PtrType, NewPtr,
10020                            DAG.getConstant(PtrOff, PtrType));
10021     }
10022
10023     // The replacement we need to do here is a little tricky: we need to
10024     // replace an extractelement of a load with a load.
10025     // Use ReplaceAllUsesOfValuesWith to do the replacement.
10026     // Note that this replacement assumes that the extractvalue is the only
10027     // use of the load; that's okay because we don't want to perform this
10028     // transformation in other cases anyway.
10029     SDValue Load;
10030     SDValue Chain;
10031     if (NVT.bitsGT(LVT)) {
10032       // If the result type of vextract is wider than the load, then issue an
10033       // extending load instead.
10034       ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
10035         ? ISD::ZEXTLOAD : ISD::EXTLOAD;
10036       Load = DAG.getExtLoad(ExtType, SDLoc(N), NVT, LN0->getChain(),
10037                             NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
10038                             LVT, LN0->isVolatile(), LN0->isNonTemporal(),
10039                             Align, LN0->getAAInfo());
10040       Chain = Load.getValue(1);
10041     } else {
10042       Load = DAG.getLoad(LVT, SDLoc(N), LN0->getChain(), NewPtr,
10043                          LN0->getPointerInfo().getWithOffset(PtrOff),
10044                          LN0->isVolatile(), LN0->isNonTemporal(),
10045                          LN0->isInvariant(), Align, LN0->getAAInfo());
10046       Chain = Load.getValue(1);
10047       if (NVT.bitsLT(LVT))
10048         Load = DAG.getNode(ISD::TRUNCATE, SDLoc(N), NVT, Load);
10049       else
10050         Load = DAG.getNode(ISD::BITCAST, SDLoc(N), NVT, Load);
10051     }
10052     WorklistRemover DeadNodes(*this);
10053     SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
10054     SDValue To[] = { Load, Chain };
10055     DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10056     // Since we're explcitly calling ReplaceAllUses, add the new node to the
10057     // worklist explicitly as well.
10058     AddToWorklist(Load.getNode());
10059     AddUsersToWorklist(Load.getNode()); // Add users too
10060     // Make sure to revisit this node to clean it up; it will usually be dead.
10061     AddToWorklist(N);
10062     return SDValue(N, 0);
10063   }
10064
10065   return SDValue();
10066 }
10067
10068 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10069 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10070   // We perform this optimization post type-legalization because
10071   // the type-legalizer often scalarizes integer-promoted vectors.
10072   // Performing this optimization before may create bit-casts which
10073   // will be type-legalized to complex code sequences.
10074   // We perform this optimization only before the operation legalizer because we
10075   // may introduce illegal operations.
10076   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10077     return SDValue();
10078
10079   unsigned NumInScalars = N->getNumOperands();
10080   SDLoc dl(N);
10081   EVT VT = N->getValueType(0);
10082
10083   // Check to see if this is a BUILD_VECTOR of a bunch of values
10084   // which come from any_extend or zero_extend nodes. If so, we can create
10085   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10086   // optimizations. We do not handle sign-extend because we can't fill the sign
10087   // using shuffles.
10088   EVT SourceType = MVT::Other;
10089   bool AllAnyExt = true;
10090
10091   for (unsigned i = 0; i != NumInScalars; ++i) {
10092     SDValue In = N->getOperand(i);
10093     // Ignore undef inputs.
10094     if (In.getOpcode() == ISD::UNDEF) continue;
10095
10096     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10097     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10098
10099     // Abort if the element is not an extension.
10100     if (!ZeroExt && !AnyExt) {
10101       SourceType = MVT::Other;
10102       break;
10103     }
10104
10105     // The input is a ZeroExt or AnyExt. Check the original type.
10106     EVT InTy = In.getOperand(0).getValueType();
10107
10108     // Check that all of the widened source types are the same.
10109     if (SourceType == MVT::Other)
10110       // First time.
10111       SourceType = InTy;
10112     else if (InTy != SourceType) {
10113       // Multiple income types. Abort.
10114       SourceType = MVT::Other;
10115       break;
10116     }
10117
10118     // Check if all of the extends are ANY_EXTENDs.
10119     AllAnyExt &= AnyExt;
10120   }
10121
10122   // In order to have valid types, all of the inputs must be extended from the
10123   // same source type and all of the inputs must be any or zero extend.
10124   // Scalar sizes must be a power of two.
10125   EVT OutScalarTy = VT.getScalarType();
10126   bool ValidTypes = SourceType != MVT::Other &&
10127                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10128                  isPowerOf2_32(SourceType.getSizeInBits());
10129
10130   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10131   // turn into a single shuffle instruction.
10132   if (!ValidTypes)
10133     return SDValue();
10134
10135   bool isLE = TLI.isLittleEndian();
10136   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10137   assert(ElemRatio > 1 && "Invalid element size ratio");
10138   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10139                                DAG.getConstant(0, SourceType);
10140
10141   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10142   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10143
10144   // Populate the new build_vector
10145   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10146     SDValue Cast = N->getOperand(i);
10147     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10148             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10149             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10150     SDValue In;
10151     if (Cast.getOpcode() == ISD::UNDEF)
10152       In = DAG.getUNDEF(SourceType);
10153     else
10154       In = Cast->getOperand(0);
10155     unsigned Index = isLE ? (i * ElemRatio) :
10156                             (i * ElemRatio + (ElemRatio - 1));
10157
10158     assert(Index < Ops.size() && "Invalid index");
10159     Ops[Index] = In;
10160   }
10161
10162   // The type of the new BUILD_VECTOR node.
10163   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10164   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10165          "Invalid vector size");
10166   // Check if the new vector type is legal.
10167   if (!isTypeLegal(VecVT)) return SDValue();
10168
10169   // Make the new BUILD_VECTOR.
10170   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10171
10172   // The new BUILD_VECTOR node has the potential to be further optimized.
10173   AddToWorklist(BV.getNode());
10174   // Bitcast to the desired type.
10175   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10176 }
10177
10178 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10179   EVT VT = N->getValueType(0);
10180
10181   unsigned NumInScalars = N->getNumOperands();
10182   SDLoc dl(N);
10183
10184   EVT SrcVT = MVT::Other;
10185   unsigned Opcode = ISD::DELETED_NODE;
10186   unsigned NumDefs = 0;
10187
10188   for (unsigned i = 0; i != NumInScalars; ++i) {
10189     SDValue In = N->getOperand(i);
10190     unsigned Opc = In.getOpcode();
10191
10192     if (Opc == ISD::UNDEF)
10193       continue;
10194
10195     // If all scalar values are floats and converted from integers.
10196     if (Opcode == ISD::DELETED_NODE &&
10197         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10198       Opcode = Opc;
10199     }
10200
10201     if (Opc != Opcode)
10202       return SDValue();
10203
10204     EVT InVT = In.getOperand(0).getValueType();
10205
10206     // If all scalar values are typed differently, bail out. It's chosen to
10207     // simplify BUILD_VECTOR of integer types.
10208     if (SrcVT == MVT::Other)
10209       SrcVT = InVT;
10210     if (SrcVT != InVT)
10211       return SDValue();
10212     NumDefs++;
10213   }
10214
10215   // If the vector has just one element defined, it's not worth to fold it into
10216   // a vectorized one.
10217   if (NumDefs < 2)
10218     return SDValue();
10219
10220   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10221          && "Should only handle conversion from integer to float.");
10222   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10223
10224   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10225
10226   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10227     return SDValue();
10228
10229   SmallVector<SDValue, 8> Opnds;
10230   for (unsigned i = 0; i != NumInScalars; ++i) {
10231     SDValue In = N->getOperand(i);
10232
10233     if (In.getOpcode() == ISD::UNDEF)
10234       Opnds.push_back(DAG.getUNDEF(SrcVT));
10235     else
10236       Opnds.push_back(In.getOperand(0));
10237   }
10238   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10239   AddToWorklist(BV.getNode());
10240
10241   return DAG.getNode(Opcode, dl, VT, BV);
10242 }
10243
10244 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10245   unsigned NumInScalars = N->getNumOperands();
10246   SDLoc dl(N);
10247   EVT VT = N->getValueType(0);
10248
10249   // A vector built entirely of undefs is undef.
10250   if (ISD::allOperandsUndef(N))
10251     return DAG.getUNDEF(VT);
10252
10253   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10254   if (V.getNode())
10255     return V;
10256
10257   V = reduceBuildVecConvertToConvertBuildVec(N);
10258   if (V.getNode())
10259     return V;
10260
10261   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10262   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10263   // at most two distinct vectors, turn this into a shuffle node.
10264
10265   // May only combine to shuffle after legalize if shuffle is legal.
10266   if (LegalOperations &&
10267       !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
10268     return SDValue();
10269
10270   SDValue VecIn1, VecIn2;
10271   for (unsigned i = 0; i != NumInScalars; ++i) {
10272     // Ignore undef inputs.
10273     if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
10274
10275     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10276     // constant index, bail out.
10277     if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10278         !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
10279       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10280       break;
10281     }
10282
10283     // We allow up to two distinct input vectors.
10284     SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
10285     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10286       continue;
10287
10288     if (!VecIn1.getNode()) {
10289       VecIn1 = ExtractedFromVec;
10290     } else if (!VecIn2.getNode()) {
10291       VecIn2 = ExtractedFromVec;
10292     } else {
10293       // Too many inputs.
10294       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10295       break;
10296     }
10297   }
10298
10299   // If everything is good, we can make a shuffle operation.
10300   if (VecIn1.getNode()) {
10301     SmallVector<int, 8> Mask;
10302     for (unsigned i = 0; i != NumInScalars; ++i) {
10303       if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
10304         Mask.push_back(-1);
10305         continue;
10306       }
10307
10308       // If extracting from the first vector, just use the index directly.
10309       SDValue Extract = N->getOperand(i);
10310       SDValue ExtVal = Extract.getOperand(1);
10311       if (Extract.getOperand(0) == VecIn1) {
10312         unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10313         if (ExtIndex > VT.getVectorNumElements())
10314           return SDValue();
10315
10316         Mask.push_back(ExtIndex);
10317         continue;
10318       }
10319
10320       // Otherwise, use InIdx + VecSize
10321       unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10322       Mask.push_back(Idx+NumInScalars);
10323     }
10324
10325     // We can't generate a shuffle node with mismatched input and output types.
10326     // Attempt to transform a single input vector to the correct type.
10327     if ((VT != VecIn1.getValueType())) {
10328       // We don't support shuffeling between TWO values of different types.
10329       if (VecIn2.getNode())
10330         return SDValue();
10331
10332       // We only support widening of vectors which are half the size of the
10333       // output registers. For example XMM->YMM widening on X86 with AVX.
10334       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10335         return SDValue();
10336
10337       // If the input vector type has a different base type to the output
10338       // vector type, bail out.
10339       if (VecIn1.getValueType().getVectorElementType() !=
10340           VT.getVectorElementType())
10341         return SDValue();
10342
10343       // Widen the input vector by adding undef values.
10344       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10345                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10346     }
10347
10348     // If VecIn2 is unused then change it to undef.
10349     VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10350
10351     // Check that we were able to transform all incoming values to the same
10352     // type.
10353     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10354         VecIn1.getValueType() != VT)
10355           return SDValue();
10356
10357     // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10358     if (!isTypeLegal(VT))
10359       return SDValue();
10360
10361     // Return the new VECTOR_SHUFFLE node.
10362     SDValue Ops[2];
10363     Ops[0] = VecIn1;
10364     Ops[1] = VecIn2;
10365     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10366   }
10367
10368   return SDValue();
10369 }
10370
10371 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10372   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10373   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10374   // inputs come from at most two distinct vectors, turn this into a shuffle
10375   // node.
10376
10377   // If we only have one input vector, we don't need to do any concatenation.
10378   if (N->getNumOperands() == 1)
10379     return N->getOperand(0);
10380
10381   // Check if all of the operands are undefs.
10382   EVT VT = N->getValueType(0);
10383   if (ISD::allOperandsUndef(N))
10384     return DAG.getUNDEF(VT);
10385
10386   // Optimize concat_vectors where one of the vectors is undef.
10387   if (N->getNumOperands() == 2 &&
10388       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10389     SDValue In = N->getOperand(0);
10390     assert(In.getValueType().isVector() && "Must concat vectors");
10391
10392     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10393     if (In->getOpcode() == ISD::BITCAST &&
10394         !In->getOperand(0)->getValueType(0).isVector()) {
10395       SDValue Scalar = In->getOperand(0);
10396       EVT SclTy = Scalar->getValueType(0);
10397
10398       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10399         return SDValue();
10400
10401       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10402                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10403       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10404         return SDValue();
10405
10406       SDLoc dl = SDLoc(N);
10407       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10408       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10409     }
10410   }
10411
10412   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10413   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10414   if (N->getNumOperands() == 2 &&
10415       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10416       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10417     EVT VT = N->getValueType(0);
10418     SDValue N0 = N->getOperand(0);
10419     SDValue N1 = N->getOperand(1);
10420     SmallVector<SDValue, 8> Opnds;
10421     unsigned BuildVecNumElts =  N0.getNumOperands();
10422
10423     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10424     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10425     if (SclTy0.isFloatingPoint()) {
10426       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10427         Opnds.push_back(N0.getOperand(i));
10428       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10429         Opnds.push_back(N1.getOperand(i));
10430     } else {
10431       // If BUILD_VECTOR are from built from integer, they may have different
10432       // operand types. Get the smaller type and truncate all operands to it.
10433       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10434       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10435         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10436                         N0.getOperand(i)));
10437       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10438         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10439                         N1.getOperand(i)));
10440     }
10441
10442     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10443   }
10444
10445   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10446   // nodes often generate nop CONCAT_VECTOR nodes.
10447   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10448   // place the incoming vectors at the exact same location.
10449   SDValue SingleSource = SDValue();
10450   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10451
10452   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10453     SDValue Op = N->getOperand(i);
10454
10455     if (Op.getOpcode() == ISD::UNDEF)
10456       continue;
10457
10458     // Check if this is the identity extract:
10459     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10460       return SDValue();
10461
10462     // Find the single incoming vector for the extract_subvector.
10463     if (SingleSource.getNode()) {
10464       if (Op.getOperand(0) != SingleSource)
10465         return SDValue();
10466     } else {
10467       SingleSource = Op.getOperand(0);
10468
10469       // Check the source type is the same as the type of the result.
10470       // If not, this concat may extend the vector, so we can not
10471       // optimize it away.
10472       if (SingleSource.getValueType() != N->getValueType(0))
10473         return SDValue();
10474     }
10475
10476     unsigned IdentityIndex = i * PartNumElem;
10477     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10478     // The extract index must be constant.
10479     if (!CS)
10480       return SDValue();
10481
10482     // Check that we are reading from the identity index.
10483     if (CS->getZExtValue() != IdentityIndex)
10484       return SDValue();
10485   }
10486
10487   if (SingleSource.getNode())
10488     return SingleSource;
10489
10490   return SDValue();
10491 }
10492
10493 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10494   EVT NVT = N->getValueType(0);
10495   SDValue V = N->getOperand(0);
10496
10497   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10498     // Combine:
10499     //    (extract_subvec (concat V1, V2, ...), i)
10500     // Into:
10501     //    Vi if possible
10502     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10503     // type.
10504     if (V->getOperand(0).getValueType() != NVT)
10505       return SDValue();
10506     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10507     unsigned NumElems = NVT.getVectorNumElements();
10508     assert((Idx % NumElems) == 0 &&
10509            "IDX in concat is not a multiple of the result vector length.");
10510     return V->getOperand(Idx / NumElems);
10511   }
10512
10513   // Skip bitcasting
10514   if (V->getOpcode() == ISD::BITCAST)
10515     V = V.getOperand(0);
10516
10517   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10518     SDLoc dl(N);
10519     // Handle only simple case where vector being inserted and vector
10520     // being extracted are of same type, and are half size of larger vectors.
10521     EVT BigVT = V->getOperand(0).getValueType();
10522     EVT SmallVT = V->getOperand(1).getValueType();
10523     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10524       return SDValue();
10525
10526     // Only handle cases where both indexes are constants with the same type.
10527     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10528     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10529
10530     if (InsIdx && ExtIdx &&
10531         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10532         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10533       // Combine:
10534       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10535       // Into:
10536       //    indices are equal or bit offsets are equal => V1
10537       //    otherwise => (extract_subvec V1, ExtIdx)
10538       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10539           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10540         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10541       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10542                          DAG.getNode(ISD::BITCAST, dl,
10543                                      N->getOperand(0).getValueType(),
10544                                      V->getOperand(0)), N->getOperand(1));
10545     }
10546   }
10547
10548   return SDValue();
10549 }
10550
10551 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10552 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10553   EVT VT = N->getValueType(0);
10554   unsigned NumElts = VT.getVectorNumElements();
10555
10556   SDValue N0 = N->getOperand(0);
10557   SDValue N1 = N->getOperand(1);
10558   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10559
10560   SmallVector<SDValue, 4> Ops;
10561   EVT ConcatVT = N0.getOperand(0).getValueType();
10562   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10563   unsigned NumConcats = NumElts / NumElemsPerConcat;
10564
10565   // Look at every vector that's inserted. We're looking for exact
10566   // subvector-sized copies from a concatenated vector
10567   for (unsigned I = 0; I != NumConcats; ++I) {
10568     // Make sure we're dealing with a copy.
10569     unsigned Begin = I * NumElemsPerConcat;
10570     bool AllUndef = true, NoUndef = true;
10571     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10572       if (SVN->getMaskElt(J) >= 0)
10573         AllUndef = false;
10574       else
10575         NoUndef = false;
10576     }
10577
10578     if (NoUndef) {
10579       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10580         return SDValue();
10581
10582       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10583         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10584           return SDValue();
10585
10586       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10587       if (FirstElt < N0.getNumOperands())
10588         Ops.push_back(N0.getOperand(FirstElt));
10589       else
10590         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10591
10592     } else if (AllUndef) {
10593       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10594     } else { // Mixed with general masks and undefs, can't do optimization.
10595       return SDValue();
10596     }
10597   }
10598
10599   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10600 }
10601
10602 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
10603   EVT VT = N->getValueType(0);
10604   unsigned NumElts = VT.getVectorNumElements();
10605
10606   SDValue N0 = N->getOperand(0);
10607   SDValue N1 = N->getOperand(1);
10608
10609   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
10610
10611   // Canonicalize shuffle undef, undef -> undef
10612   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
10613     return DAG.getUNDEF(VT);
10614
10615   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10616
10617   // Canonicalize shuffle v, v -> v, undef
10618   if (N0 == N1) {
10619     SmallVector<int, 8> NewMask;
10620     for (unsigned i = 0; i != NumElts; ++i) {
10621       int Idx = SVN->getMaskElt(i);
10622       if (Idx >= (int)NumElts) Idx -= NumElts;
10623       NewMask.push_back(Idx);
10624     }
10625     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
10626                                 &NewMask[0]);
10627   }
10628
10629   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
10630   if (N0.getOpcode() == ISD::UNDEF) {
10631     SmallVector<int, 8> NewMask;
10632     for (unsigned i = 0; i != NumElts; ++i) {
10633       int Idx = SVN->getMaskElt(i);
10634       if (Idx >= 0) {
10635         if (Idx >= (int)NumElts)
10636           Idx -= NumElts;
10637         else
10638           Idx = -1; // remove reference to lhs
10639       }
10640       NewMask.push_back(Idx);
10641     }
10642     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
10643                                 &NewMask[0]);
10644   }
10645
10646   // Remove references to rhs if it is undef
10647   if (N1.getOpcode() == ISD::UNDEF) {
10648     bool Changed = false;
10649     SmallVector<int, 8> NewMask;
10650     for (unsigned i = 0; i != NumElts; ++i) {
10651       int Idx = SVN->getMaskElt(i);
10652       if (Idx >= (int)NumElts) {
10653         Idx = -1;
10654         Changed = true;
10655       }
10656       NewMask.push_back(Idx);
10657     }
10658     if (Changed)
10659       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
10660   }
10661
10662   // If it is a splat, check if the argument vector is another splat or a
10663   // build_vector with all scalar elements the same.
10664   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
10665     SDNode *V = N0.getNode();
10666
10667     // If this is a bit convert that changes the element type of the vector but
10668     // not the number of vector elements, look through it.  Be careful not to
10669     // look though conversions that change things like v4f32 to v2f64.
10670     if (V->getOpcode() == ISD::BITCAST) {
10671       SDValue ConvInput = V->getOperand(0);
10672       if (ConvInput.getValueType().isVector() &&
10673           ConvInput.getValueType().getVectorNumElements() == NumElts)
10674         V = ConvInput.getNode();
10675     }
10676
10677     if (V->getOpcode() == ISD::BUILD_VECTOR) {
10678       assert(V->getNumOperands() == NumElts &&
10679              "BUILD_VECTOR has wrong number of operands");
10680       SDValue Base;
10681       bool AllSame = true;
10682       for (unsigned i = 0; i != NumElts; ++i) {
10683         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
10684           Base = V->getOperand(i);
10685           break;
10686         }
10687       }
10688       // Splat of <u, u, u, u>, return <u, u, u, u>
10689       if (!Base.getNode())
10690         return N0;
10691       for (unsigned i = 0; i != NumElts; ++i) {
10692         if (V->getOperand(i) != Base) {
10693           AllSame = false;
10694           break;
10695         }
10696       }
10697       // Splat of <x, x, x, x>, return <x, x, x, x>
10698       if (AllSame)
10699         return N0;
10700     }
10701   }
10702
10703   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10704       Level < AfterLegalizeVectorOps &&
10705       (N1.getOpcode() == ISD::UNDEF ||
10706       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
10707        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
10708     SDValue V = partitionShuffleOfConcats(N, DAG);
10709
10710     if (V.getNode())
10711       return V;
10712   }
10713
10714   // If this shuffle node is simply a swizzle of another shuffle node,
10715   // then try to simplify it.
10716   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10717       N1.getOpcode() == ISD::UNDEF) {
10718
10719     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10720
10721     // The incoming shuffle must be of the same type as the result of the
10722     // current shuffle.
10723     assert(OtherSV->getOperand(0).getValueType() == VT &&
10724            "Shuffle types don't match");
10725
10726     SmallVector<int, 4> Mask;
10727     // Compute the combined shuffle mask.
10728     for (unsigned i = 0; i != NumElts; ++i) {
10729       int Idx = SVN->getMaskElt(i);
10730       assert(Idx < (int)NumElts && "Index references undef operand");
10731       // Next, this index comes from the first value, which is the incoming
10732       // shuffle. Adopt the incoming index.
10733       if (Idx >= 0)
10734         Idx = OtherSV->getMaskElt(Idx);
10735       Mask.push_back(Idx);
10736     }
10737     
10738     bool CommuteOperands = false;
10739     if (N0.getOperand(1).getOpcode() != ISD::UNDEF) {
10740       // To be valid, the combine shuffle mask should only reference elements
10741       // from one of the two vectors in input to the inner shufflevector.
10742       bool IsValidMask = true;
10743       for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10744         // See if the combined mask only reference undefs or elements coming
10745         // from the first shufflevector operand.
10746         IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] < NumElts;
10747
10748       if (!IsValidMask) {
10749         IsValidMask = true;
10750         for (unsigned i = 0; i != NumElts && IsValidMask; ++i)
10751           // Check that all the elements come from the second shuffle operand.
10752           IsValidMask = Mask[i] < 0 || (unsigned)Mask[i] >= NumElts;
10753         CommuteOperands = IsValidMask;
10754       }
10755
10756       // Early exit if the combined shuffle mask is not valid.
10757       if (!IsValidMask)
10758         return SDValue();
10759     }
10760
10761     // See if this pair of shuffles can be safely folded according to either
10762     // of the following rules:
10763     //   shuffle(shuffle(x, y), undef) -> x
10764     //   shuffle(shuffle(x, undef), undef) -> x
10765     //   shuffle(shuffle(x, y), undef) -> y
10766     bool IsIdentityMask = true;
10767     unsigned BaseMaskIndex = CommuteOperands ? NumElts : 0;
10768     for (unsigned i = 0; i != NumElts && IsIdentityMask; ++i) {
10769       // Skip Undefs.
10770       if (Mask[i] < 0)
10771         continue;
10772
10773       // The combined shuffle must map each index to itself.
10774       IsIdentityMask = (unsigned)Mask[i] == i + BaseMaskIndex;
10775     }
10776     
10777     if (IsIdentityMask) {
10778       if (CommuteOperands)
10779         // optimize shuffle(shuffle(x, y), undef) -> y.
10780         return OtherSV->getOperand(1);
10781       
10782       // optimize shuffle(shuffle(x, undef), undef) -> x
10783       // optimize shuffle(shuffle(x, y), undef) -> x
10784       return OtherSV->getOperand(0);
10785     }
10786
10787     // It may still be beneficial to combine the two shuffles if the
10788     // resulting shuffle is legal.
10789     if (TLI.isTypeLegal(VT) && TLI.isShuffleMaskLegal(Mask, VT)) {
10790       if (!CommuteOperands)
10791         // shuffle(shuffle(x, undef, M1), undef, M2) -> shuffle(x, undef, M3).
10792         // shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(x, undef, M3)
10793         return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0), N1,
10794                                     &Mask[0]);
10795       
10796       //   shuffle(shuffle(x, y, M1), undef, M2) -> shuffle(undef, y, M3)
10797       return DAG.getVectorShuffle(VT, SDLoc(N), N1, N0->getOperand(1),
10798                                   &Mask[0]);
10799     }
10800   }
10801
10802   // Canonicalize shuffles according to rules:
10803   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
10804   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
10805   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
10806   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE && N0.getOpcode() != ISD::UNDEF &&
10807       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10808       TLI.isTypeLegal(VT)) {
10809     // The incoming shuffle must be of the same type as the result of the
10810     // current shuffle.
10811     assert(N1->getOperand(0).getValueType() == VT &&
10812            "Shuffle types don't match");
10813
10814     SDValue SV0 = N1->getOperand(0);
10815     SDValue SV1 = N1->getOperand(1);
10816     bool HasSameOp0 = N0 == SV0;
10817     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10818     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
10819       // Commute the operands of this shuffle so that next rule
10820       // will trigger.
10821       return DAG.getCommutedVectorShuffle(*SVN);
10822   }
10823
10824   // Try to fold according to rules:
10825   //   shuffle(shuffle(A, B, M0), B, M1) -> shuffle(A, B, M2)
10826   //   shuffle(shuffle(A, B, M0), A, M1) -> shuffle(A, B, M2)
10827   //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10828   //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10829   // Don't try to fold shuffles with illegal type.
10830   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
10831       N1.getOpcode() != ISD::UNDEF && TLI.isTypeLegal(VT)) {
10832     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
10833
10834     // The incoming shuffle must be of the same type as the result of the
10835     // current shuffle.
10836     assert(OtherSV->getOperand(0).getValueType() == VT &&
10837            "Shuffle types don't match");
10838
10839     SDValue SV0 = OtherSV->getOperand(0);
10840     SDValue SV1 = OtherSV->getOperand(1);
10841     bool HasSameOp0 = N1 == SV0;
10842     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
10843     if (!HasSameOp0 && !IsSV1Undef && N1 != SV1)
10844       // Early exit.
10845       return SDValue();
10846
10847     SmallVector<int, 4> Mask;
10848     // Compute the combined shuffle mask for a shuffle with SV0 as the first
10849     // operand, and SV1 as the second operand.
10850     for (unsigned i = 0; i != NumElts; ++i) {
10851       int Idx = SVN->getMaskElt(i);
10852       if (Idx < 0) {
10853         // Propagate Undef.
10854         Mask.push_back(Idx);
10855         continue;
10856       }
10857
10858       if (Idx < (int)NumElts) {
10859         Idx = OtherSV->getMaskElt(Idx);
10860         if (IsSV1Undef && Idx >= (int) NumElts)
10861           Idx = -1;  // Propagate Undef.
10862       } else
10863         Idx = HasSameOp0 ? Idx - NumElts : Idx;
10864
10865       Mask.push_back(Idx);
10866     }
10867
10868     // Avoid introducing shuffles with illegal mask.
10869     if (TLI.isShuffleMaskLegal(Mask, VT)) {
10870       if (IsSV1Undef)
10871         //   shuffle(shuffle(A, Undef, M0), B, M1) -> shuffle(A, B, M2)
10872         //   shuffle(shuffle(A, Undef, M0), A, M1) -> shuffle(A, Undef, M2)
10873         return DAG.getVectorShuffle(VT, SDLoc(N), SV0, N1, &Mask[0]);
10874       return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
10875     }
10876   }
10877
10878   return SDValue();
10879 }
10880
10881 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
10882   SDValue N0 = N->getOperand(0);
10883   SDValue N2 = N->getOperand(2);
10884
10885   // If the input vector is a concatenation, and the insert replaces
10886   // one of the halves, we can optimize into a single concat_vectors.
10887   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
10888       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
10889     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
10890     EVT VT = N->getValueType(0);
10891
10892     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10893     // (concat_vectors Z, Y)
10894     if (InsIdx == 0)
10895       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10896                          N->getOperand(1), N0.getOperand(1));
10897
10898     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
10899     // (concat_vectors X, Z)
10900     if (InsIdx == VT.getVectorNumElements()/2)
10901       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
10902                          N0.getOperand(0), N->getOperand(1));
10903   }
10904
10905   return SDValue();
10906 }
10907
10908 /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
10909 /// an AND to a vector_shuffle with the destination vector and a zero vector.
10910 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
10911 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
10912 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
10913   EVT VT = N->getValueType(0);
10914   SDLoc dl(N);
10915   SDValue LHS = N->getOperand(0);
10916   SDValue RHS = N->getOperand(1);
10917   if (N->getOpcode() == ISD::AND) {
10918     if (RHS.getOpcode() == ISD::BITCAST)
10919       RHS = RHS.getOperand(0);
10920     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
10921       SmallVector<int, 8> Indices;
10922       unsigned NumElts = RHS.getNumOperands();
10923       for (unsigned i = 0; i != NumElts; ++i) {
10924         SDValue Elt = RHS.getOperand(i);
10925         if (!isa<ConstantSDNode>(Elt))
10926           return SDValue();
10927
10928         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
10929           Indices.push_back(i);
10930         else if (cast<ConstantSDNode>(Elt)->isNullValue())
10931           Indices.push_back(NumElts);
10932         else
10933           return SDValue();
10934       }
10935
10936       // Let's see if the target supports this vector_shuffle.
10937       EVT RVT = RHS.getValueType();
10938       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
10939         return SDValue();
10940
10941       // Return the new VECTOR_SHUFFLE node.
10942       EVT EltVT = RVT.getVectorElementType();
10943       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
10944                                      DAG.getConstant(0, EltVT));
10945       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
10946       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
10947       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
10948       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
10949     }
10950   }
10951
10952   return SDValue();
10953 }
10954
10955 /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
10956 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
10957   assert(N->getValueType(0).isVector() &&
10958          "SimplifyVBinOp only works on vectors!");
10959
10960   SDValue LHS = N->getOperand(0);
10961   SDValue RHS = N->getOperand(1);
10962   SDValue Shuffle = XformToShuffleWithZero(N);
10963   if (Shuffle.getNode()) return Shuffle;
10964
10965   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
10966   // this operation.
10967   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
10968       RHS.getOpcode() == ISD::BUILD_VECTOR) {
10969     // Check if both vectors are constants. If not bail out.
10970     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
10971           cast<BuildVectorSDNode>(RHS)->isConstant()))
10972       return SDValue();
10973
10974     SmallVector<SDValue, 8> Ops;
10975     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
10976       SDValue LHSOp = LHS.getOperand(i);
10977       SDValue RHSOp = RHS.getOperand(i);
10978
10979       // Can't fold divide by zero.
10980       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
10981           N->getOpcode() == ISD::FDIV) {
10982         if ((RHSOp.getOpcode() == ISD::Constant &&
10983              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
10984             (RHSOp.getOpcode() == ISD::ConstantFP &&
10985              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
10986           break;
10987       }
10988
10989       EVT VT = LHSOp.getValueType();
10990       EVT RVT = RHSOp.getValueType();
10991       if (RVT != VT) {
10992         // Integer BUILD_VECTOR operands may have types larger than the element
10993         // size (e.g., when the element type is not legal).  Prior to type
10994         // legalization, the types may not match between the two BUILD_VECTORS.
10995         // Truncate one of the operands to make them match.
10996         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
10997           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
10998         } else {
10999           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11000           VT = RVT;
11001         }
11002       }
11003       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11004                                    LHSOp, RHSOp);
11005       if (FoldOp.getOpcode() != ISD::UNDEF &&
11006           FoldOp.getOpcode() != ISD::Constant &&
11007           FoldOp.getOpcode() != ISD::ConstantFP)
11008         break;
11009       Ops.push_back(FoldOp);
11010       AddToWorklist(FoldOp.getNode());
11011     }
11012
11013     if (Ops.size() == LHS.getNumOperands())
11014       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11015   }
11016
11017   // Type legalization might introduce new shuffles in the DAG.
11018   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11019   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11020   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11021       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11022       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11023       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11024     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11025     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11026
11027     if (SVN0->getMask().equals(SVN1->getMask())) {
11028       EVT VT = N->getValueType(0);
11029       SDValue UndefVector = LHS.getOperand(1);
11030       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11031                                      LHS.getOperand(0), RHS.getOperand(0));
11032       AddUsersToWorklist(N);
11033       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11034                                   &SVN0->getMask()[0]);
11035     }
11036   }
11037
11038   return SDValue();
11039 }
11040
11041 /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
11042 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11043   assert(N->getValueType(0).isVector() &&
11044          "SimplifyVUnaryOp only works on vectors!");
11045
11046   SDValue N0 = N->getOperand(0);
11047
11048   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11049     return SDValue();
11050
11051   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11052   SmallVector<SDValue, 8> Ops;
11053   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11054     SDValue Op = N0.getOperand(i);
11055     if (Op.getOpcode() != ISD::UNDEF &&
11056         Op.getOpcode() != ISD::ConstantFP)
11057       break;
11058     EVT EltVT = Op.getValueType();
11059     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11060     if (FoldOp.getOpcode() != ISD::UNDEF &&
11061         FoldOp.getOpcode() != ISD::ConstantFP)
11062       break;
11063     Ops.push_back(FoldOp);
11064     AddToWorklist(FoldOp.getNode());
11065   }
11066
11067   if (Ops.size() != N0.getNumOperands())
11068     return SDValue();
11069
11070   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11071 }
11072
11073 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11074                                     SDValue N1, SDValue N2){
11075   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11076
11077   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11078                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11079
11080   // If we got a simplified select_cc node back from SimplifySelectCC, then
11081   // break it down into a new SETCC node, and a new SELECT node, and then return
11082   // the SELECT node, since we were called with a SELECT node.
11083   if (SCC.getNode()) {
11084     // Check to see if we got a select_cc back (to turn into setcc/select).
11085     // Otherwise, just return whatever node we got back, like fabs.
11086     if (SCC.getOpcode() == ISD::SELECT_CC) {
11087       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11088                                   N0.getValueType(),
11089                                   SCC.getOperand(0), SCC.getOperand(1),
11090                                   SCC.getOperand(4));
11091       AddToWorklist(SETCC.getNode());
11092       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(),
11093                            SCC.getOperand(2), SCC.getOperand(3), SETCC);
11094     }
11095
11096     return SCC;
11097   }
11098   return SDValue();
11099 }
11100
11101 /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
11102 /// are the two values being selected between, see if we can simplify the
11103 /// select.  Callers of this should assume that TheSelect is deleted if this
11104 /// returns true.  As such, they should return the appropriate thing (e.g. the
11105 /// node) back to the top-level of the DAG combiner loop to avoid it being
11106 /// looked at.
11107 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11108                                     SDValue RHS) {
11109
11110   // Cannot simplify select with vector condition
11111   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11112
11113   // If this is a select from two identical things, try to pull the operation
11114   // through the select.
11115   if (LHS.getOpcode() != RHS.getOpcode() ||
11116       !LHS.hasOneUse() || !RHS.hasOneUse())
11117     return false;
11118
11119   // If this is a load and the token chain is identical, replace the select
11120   // of two loads with a load through a select of the address to load from.
11121   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11122   // constants have been dropped into the constant pool.
11123   if (LHS.getOpcode() == ISD::LOAD) {
11124     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11125     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11126
11127     // Token chains must be identical.
11128     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11129         // Do not let this transformation reduce the number of volatile loads.
11130         LLD->isVolatile() || RLD->isVolatile() ||
11131         // If this is an EXTLOAD, the VT's must match.
11132         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11133         // If this is an EXTLOAD, the kind of extension must match.
11134         (LLD->getExtensionType() != RLD->getExtensionType() &&
11135          // The only exception is if one of the extensions is anyext.
11136          LLD->getExtensionType() != ISD::EXTLOAD &&
11137          RLD->getExtensionType() != ISD::EXTLOAD) ||
11138         // FIXME: this discards src value information.  This is
11139         // over-conservative. It would be beneficial to be able to remember
11140         // both potential memory locations.  Since we are discarding
11141         // src value info, don't do the transformation if the memory
11142         // locations are not in the default address space.
11143         LLD->getPointerInfo().getAddrSpace() != 0 ||
11144         RLD->getPointerInfo().getAddrSpace() != 0 ||
11145         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11146                                       LLD->getBasePtr().getValueType()))
11147       return false;
11148
11149     // Check that the select condition doesn't reach either load.  If so,
11150     // folding this will induce a cycle into the DAG.  If not, this is safe to
11151     // xform, so create a select of the addresses.
11152     SDValue Addr;
11153     if (TheSelect->getOpcode() == ISD::SELECT) {
11154       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11155       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11156           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11157         return false;
11158       // The loads must not depend on one another.
11159       if (LLD->isPredecessorOf(RLD) ||
11160           RLD->isPredecessorOf(LLD))
11161         return false;
11162       Addr = DAG.getSelect(SDLoc(TheSelect),
11163                            LLD->getBasePtr().getValueType(),
11164                            TheSelect->getOperand(0), LLD->getBasePtr(),
11165                            RLD->getBasePtr());
11166     } else {  // Otherwise SELECT_CC
11167       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11168       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11169
11170       if ((LLD->hasAnyUseOfValue(1) &&
11171            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11172           (RLD->hasAnyUseOfValue(1) &&
11173            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11174         return false;
11175
11176       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11177                          LLD->getBasePtr().getValueType(),
11178                          TheSelect->getOperand(0),
11179                          TheSelect->getOperand(1),
11180                          LLD->getBasePtr(), RLD->getBasePtr(),
11181                          TheSelect->getOperand(4));
11182     }
11183
11184     SDValue Load;
11185     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11186       Load = DAG.getLoad(TheSelect->getValueType(0),
11187                          SDLoc(TheSelect),
11188                          // FIXME: Discards pointer and AA info.
11189                          LLD->getChain(), Addr, MachinePointerInfo(),
11190                          LLD->isVolatile(), LLD->isNonTemporal(),
11191                          LLD->isInvariant(), LLD->getAlignment());
11192     } else {
11193       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11194                             RLD->getExtensionType() : LLD->getExtensionType(),
11195                             SDLoc(TheSelect),
11196                             TheSelect->getValueType(0),
11197                             // FIXME: Discards pointer and AA info.
11198                             LLD->getChain(), Addr, MachinePointerInfo(),
11199                             LLD->getMemoryVT(), LLD->isVolatile(),
11200                             LLD->isNonTemporal(), LLD->getAlignment());
11201     }
11202
11203     // Users of the select now use the result of the load.
11204     CombineTo(TheSelect, Load);
11205
11206     // Users of the old loads now use the new load's chain.  We know the
11207     // old-load value is dead now.
11208     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11209     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11210     return true;
11211   }
11212
11213   return false;
11214 }
11215
11216 /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
11217 /// where 'cond' is the comparison specified by CC.
11218 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11219                                       SDValue N2, SDValue N3,
11220                                       ISD::CondCode CC, bool NotExtCompare) {
11221   // (x ? y : y) -> y.
11222   if (N2 == N3) return N2;
11223
11224   EVT VT = N2.getValueType();
11225   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11226   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11227   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11228
11229   // Determine if the condition we're dealing with is constant
11230   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11231                               N0, N1, CC, DL, false);
11232   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11233   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11234
11235   // fold select_cc true, x, y -> x
11236   if (SCCC && !SCCC->isNullValue())
11237     return N2;
11238   // fold select_cc false, x, y -> y
11239   if (SCCC && SCCC->isNullValue())
11240     return N3;
11241
11242   // Check to see if we can simplify the select into an fabs node
11243   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11244     // Allow either -0.0 or 0.0
11245     if (CFP->getValueAPF().isZero()) {
11246       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11247       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11248           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11249           N2 == N3.getOperand(0))
11250         return DAG.getNode(ISD::FABS, DL, VT, N0);
11251
11252       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11253       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11254           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11255           N2.getOperand(0) == N3)
11256         return DAG.getNode(ISD::FABS, DL, VT, N3);
11257     }
11258   }
11259
11260   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11261   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11262   // in it.  This is a win when the constant is not otherwise available because
11263   // it replaces two constant pool loads with one.  We only do this if the FP
11264   // type is known to be legal, because if it isn't, then we are before legalize
11265   // types an we want the other legalization to happen first (e.g. to avoid
11266   // messing with soft float) and if the ConstantFP is not legal, because if
11267   // it is legal, we may not need to store the FP constant in a constant pool.
11268   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11269     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11270       if (TLI.isTypeLegal(N2.getValueType()) &&
11271           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11272                TargetLowering::Legal &&
11273            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11274            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11275           // If both constants have multiple uses, then we won't need to do an
11276           // extra load, they are likely around in registers for other users.
11277           (TV->hasOneUse() || FV->hasOneUse())) {
11278         Constant *Elts[] = {
11279           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11280           const_cast<ConstantFP*>(TV->getConstantFPValue())
11281         };
11282         Type *FPTy = Elts[0]->getType();
11283         const DataLayout &TD = *TLI.getDataLayout();
11284
11285         // Create a ConstantArray of the two constants.
11286         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11287         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11288                                             TD.getPrefTypeAlignment(FPTy));
11289         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11290
11291         // Get the offsets to the 0 and 1 element of the array so that we can
11292         // select between them.
11293         SDValue Zero = DAG.getIntPtrConstant(0);
11294         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11295         SDValue One = DAG.getIntPtrConstant(EltSize);
11296
11297         SDValue Cond = DAG.getSetCC(DL,
11298                                     getSetCCResultType(N0.getValueType()),
11299                                     N0, N1, CC);
11300         AddToWorklist(Cond.getNode());
11301         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11302                                           Cond, One, Zero);
11303         AddToWorklist(CstOffset.getNode());
11304         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11305                             CstOffset);
11306         AddToWorklist(CPIdx.getNode());
11307         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11308                            MachinePointerInfo::getConstantPool(), false,
11309                            false, false, Alignment);
11310
11311       }
11312     }
11313
11314   // Check to see if we can perform the "gzip trick", transforming
11315   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11316   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11317       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11318        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11319     EVT XType = N0.getValueType();
11320     EVT AType = N2.getValueType();
11321     if (XType.bitsGE(AType)) {
11322       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11323       // single-bit constant.
11324       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11325         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11326         ShCtV = XType.getSizeInBits()-ShCtV-1;
11327         SDValue ShCt = DAG.getConstant(ShCtV,
11328                                        getShiftAmountTy(N0.getValueType()));
11329         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11330                                     XType, N0, ShCt);
11331         AddToWorklist(Shift.getNode());
11332
11333         if (XType.bitsGT(AType)) {
11334           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11335           AddToWorklist(Shift.getNode());
11336         }
11337
11338         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11339       }
11340
11341       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11342                                   XType, N0,
11343                                   DAG.getConstant(XType.getSizeInBits()-1,
11344                                          getShiftAmountTy(N0.getValueType())));
11345       AddToWorklist(Shift.getNode());
11346
11347       if (XType.bitsGT(AType)) {
11348         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11349         AddToWorklist(Shift.getNode());
11350       }
11351
11352       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11353     }
11354   }
11355
11356   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11357   // where y is has a single bit set.
11358   // A plaintext description would be, we can turn the SELECT_CC into an AND
11359   // when the condition can be materialized as an all-ones register.  Any
11360   // single bit-test can be materialized as an all-ones register with
11361   // shift-left and shift-right-arith.
11362   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11363       N0->getValueType(0) == VT &&
11364       N1C && N1C->isNullValue() &&
11365       N2C && N2C->isNullValue()) {
11366     SDValue AndLHS = N0->getOperand(0);
11367     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11368     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11369       // Shift the tested bit over the sign bit.
11370       APInt AndMask = ConstAndRHS->getAPIntValue();
11371       SDValue ShlAmt =
11372         DAG.getConstant(AndMask.countLeadingZeros(),
11373                         getShiftAmountTy(AndLHS.getValueType()));
11374       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11375
11376       // Now arithmetic right shift it all the way over, so the result is either
11377       // all-ones, or zero.
11378       SDValue ShrAmt =
11379         DAG.getConstant(AndMask.getBitWidth()-1,
11380                         getShiftAmountTy(Shl.getValueType()));
11381       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11382
11383       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11384     }
11385   }
11386
11387   // fold select C, 16, 0 -> shl C, 4
11388   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11389       TLI.getBooleanContents(N0.getValueType()) ==
11390           TargetLowering::ZeroOrOneBooleanContent) {
11391
11392     // If the caller doesn't want us to simplify this into a zext of a compare,
11393     // don't do it.
11394     if (NotExtCompare && N2C->getAPIntValue() == 1)
11395       return SDValue();
11396
11397     // Get a SetCC of the condition
11398     // NOTE: Don't create a SETCC if it's not legal on this target.
11399     if (!LegalOperations ||
11400         TLI.isOperationLegal(ISD::SETCC,
11401           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11402       SDValue Temp, SCC;
11403       // cast from setcc result type to select result type
11404       if (LegalTypes) {
11405         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11406                             N0, N1, CC);
11407         if (N2.getValueType().bitsLT(SCC.getValueType()))
11408           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11409                                         N2.getValueType());
11410         else
11411           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11412                              N2.getValueType(), SCC);
11413       } else {
11414         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11415         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11416                            N2.getValueType(), SCC);
11417       }
11418
11419       AddToWorklist(SCC.getNode());
11420       AddToWorklist(Temp.getNode());
11421
11422       if (N2C->getAPIntValue() == 1)
11423         return Temp;
11424
11425       // shl setcc result by log2 n2c
11426       return DAG.getNode(
11427           ISD::SHL, DL, N2.getValueType(), Temp,
11428           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11429                           getShiftAmountTy(Temp.getValueType())));
11430     }
11431   }
11432
11433   // Check to see if this is the equivalent of setcc
11434   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11435   // otherwise, go ahead with the folds.
11436   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11437     EVT XType = N0.getValueType();
11438     if (!LegalOperations ||
11439         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11440       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11441       if (Res.getValueType() != VT)
11442         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11443       return Res;
11444     }
11445
11446     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11447     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11448         (!LegalOperations ||
11449          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11450       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11451       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11452                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11453                                        getShiftAmountTy(Ctlz.getValueType())));
11454     }
11455     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11456     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11457       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11458                                   XType, DAG.getConstant(0, XType), N0);
11459       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11460       return DAG.getNode(ISD::SRL, DL, XType,
11461                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11462                          DAG.getConstant(XType.getSizeInBits()-1,
11463                                          getShiftAmountTy(XType)));
11464     }
11465     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11466     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11467       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11468                                  DAG.getConstant(XType.getSizeInBits()-1,
11469                                          getShiftAmountTy(N0.getValueType())));
11470       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11471     }
11472   }
11473
11474   // Check to see if this is an integer abs.
11475   // select_cc setg[te] X,  0,  X, -X ->
11476   // select_cc setgt    X, -1,  X, -X ->
11477   // select_cc setl[te] X,  0, -X,  X ->
11478   // select_cc setlt    X,  1, -X,  X ->
11479   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11480   if (N1C) {
11481     ConstantSDNode *SubC = nullptr;
11482     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11483          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11484         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11485       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11486     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11487               (N1C->isOne() && CC == ISD::SETLT)) &&
11488              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11489       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11490
11491     EVT XType = N0.getValueType();
11492     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11493       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11494                                   N0,
11495                                   DAG.getConstant(XType.getSizeInBits()-1,
11496                                          getShiftAmountTy(N0.getValueType())));
11497       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11498                                 XType, N0, Shift);
11499       AddToWorklist(Shift.getNode());
11500       AddToWorklist(Add.getNode());
11501       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11502     }
11503   }
11504
11505   return SDValue();
11506 }
11507
11508 /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
11509 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11510                                    SDValue N1, ISD::CondCode Cond,
11511                                    SDLoc DL, bool foldBooleans) {
11512   TargetLowering::DAGCombinerInfo
11513     DagCombineInfo(DAG, Level, false, this);
11514   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11515 }
11516
11517 /// BuildSDIV - Given an ISD::SDIV node expressing a divide by constant, return
11518 /// a DAG expression to select that will generate the same value by multiplying
11519 /// by a magic number.  See:
11520 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11521 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11522   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11523   if (!C)
11524     return SDValue();
11525
11526   // Avoid division by zero.
11527   if (!C->getAPIntValue())
11528     return SDValue();
11529
11530   std::vector<SDNode*> Built;
11531   SDValue S =
11532       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11533
11534   for (SDNode *N : Built)
11535     AddToWorklist(N);
11536   return S;
11537 }
11538
11539 /// BuildSDIVPow2 - Given an ISD::SDIV node expressing a divide by constant
11540 /// power of 2, return a DAG expression to select that will generate the same
11541 /// value by right shifting.
11542 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11543   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11544   if (!C)
11545     return SDValue();
11546
11547   // Avoid division by zero.
11548   if (!C->getAPIntValue())
11549     return SDValue();
11550
11551   std::vector<SDNode *> Built;
11552   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11553
11554   for (SDNode *N : Built)
11555     AddToWorklist(N);
11556   return S;
11557 }
11558
11559 /// BuildUDIV - Given an ISD::UDIV node expressing a divide by constant,
11560 /// return a DAG expression to select that will generate the same value by
11561 /// multiplying by a magic number.  See:
11562 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
11563 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11564   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11565   if (!C)
11566     return SDValue();
11567
11568   // Avoid division by zero.
11569   if (!C->getAPIntValue())
11570     return SDValue();
11571
11572   std::vector<SDNode*> Built;
11573   SDValue S =
11574       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11575
11576   for (SDNode *N : Built)
11577     AddToWorklist(N);
11578   return S;
11579 }
11580
11581 /// FindBaseOffset - Return true if base is a frame index, which is known not
11582 // to alias with anything but itself.  Provides base object and offset as
11583 // results.
11584 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
11585                            const GlobalValue *&GV, const void *&CV) {
11586   // Assume it is a primitive operation.
11587   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
11588
11589   // If it's an adding a simple constant then integrate the offset.
11590   if (Base.getOpcode() == ISD::ADD) {
11591     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
11592       Base = Base.getOperand(0);
11593       Offset += C->getZExtValue();
11594     }
11595   }
11596
11597   // Return the underlying GlobalValue, and update the Offset.  Return false
11598   // for GlobalAddressSDNode since the same GlobalAddress may be represented
11599   // by multiple nodes with different offsets.
11600   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
11601     GV = G->getGlobal();
11602     Offset += G->getOffset();
11603     return false;
11604   }
11605
11606   // Return the underlying Constant value, and update the Offset.  Return false
11607   // for ConstantSDNodes since the same constant pool entry may be represented
11608   // by multiple nodes with different offsets.
11609   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
11610     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
11611                                          : (const void *)C->getConstVal();
11612     Offset += C->getOffset();
11613     return false;
11614   }
11615   // If it's any of the following then it can't alias with anything but itself.
11616   return isa<FrameIndexSDNode>(Base);
11617 }
11618
11619 /// isAlias - Return true if there is any possibility that the two addresses
11620 /// overlap.
11621 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
11622   // If they are the same then they must be aliases.
11623   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
11624
11625   // If they are both volatile then they cannot be reordered.
11626   if (Op0->isVolatile() && Op1->isVolatile()) return true;
11627
11628   // Gather base node and offset information.
11629   SDValue Base1, Base2;
11630   int64_t Offset1, Offset2;
11631   const GlobalValue *GV1, *GV2;
11632   const void *CV1, *CV2;
11633   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
11634                                       Base1, Offset1, GV1, CV1);
11635   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
11636                                       Base2, Offset2, GV2, CV2);
11637
11638   // If they have a same base address then check to see if they overlap.
11639   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
11640     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11641              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11642
11643   // It is possible for different frame indices to alias each other, mostly
11644   // when tail call optimization reuses return address slots for arguments.
11645   // To catch this case, look up the actual index of frame indices to compute
11646   // the real alias relationship.
11647   if (isFrameIndex1 && isFrameIndex2) {
11648     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
11649     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
11650     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
11651     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
11652              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
11653   }
11654
11655   // Otherwise, if we know what the bases are, and they aren't identical, then
11656   // we know they cannot alias.
11657   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
11658     return false;
11659
11660   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
11661   // compared to the size and offset of the access, we may be able to prove they
11662   // do not alias.  This check is conservative for now to catch cases created by
11663   // splitting vector types.
11664   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
11665       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
11666       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
11667        Op1->getMemoryVT().getSizeInBits() >> 3) &&
11668       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
11669     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
11670     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
11671
11672     // There is no overlap between these relatively aligned accesses of similar
11673     // size, return no alias.
11674     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
11675         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
11676       return false;
11677   }
11678
11679   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0 ? CombinerGlobalAA :
11680     TLI.getTargetMachine().getSubtarget<TargetSubtargetInfo>().useAA();
11681 #ifndef NDEBUG
11682   if (CombinerAAOnlyFunc.getNumOccurrences() &&
11683       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
11684     UseAA = false;
11685 #endif
11686   if (UseAA &&
11687       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
11688     // Use alias analysis information.
11689     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
11690                                  Op1->getSrcValueOffset());
11691     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
11692         Op0->getSrcValueOffset() - MinOffset;
11693     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
11694         Op1->getSrcValueOffset() - MinOffset;
11695     AliasAnalysis::AliasResult AAResult =
11696         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
11697                                          Overlap1,
11698                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
11699                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
11700                                          Overlap2,
11701                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
11702     if (AAResult == AliasAnalysis::NoAlias)
11703       return false;
11704   }
11705
11706   // Otherwise we have to assume they alias.
11707   return true;
11708 }
11709
11710 /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
11711 /// looking for aliasing nodes and adding them to the Aliases vector.
11712 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
11713                                    SmallVectorImpl<SDValue> &Aliases) {
11714   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
11715   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
11716
11717   // Get alias information for node.
11718   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
11719
11720   // Starting off.
11721   Chains.push_back(OriginalChain);
11722   unsigned Depth = 0;
11723
11724   // Look at each chain and determine if it is an alias.  If so, add it to the
11725   // aliases list.  If not, then continue up the chain looking for the next
11726   // candidate.
11727   while (!Chains.empty()) {
11728     SDValue Chain = Chains.back();
11729     Chains.pop_back();
11730
11731     // For TokenFactor nodes, look at each operand and only continue up the
11732     // chain until we find two aliases.  If we've seen two aliases, assume we'll
11733     // find more and revert to original chain since the xform is unlikely to be
11734     // profitable.
11735     //
11736     // FIXME: The depth check could be made to return the last non-aliasing
11737     // chain we found before we hit a tokenfactor rather than the original
11738     // chain.
11739     if (Depth > 6 || Aliases.size() == 2) {
11740       Aliases.clear();
11741       Aliases.push_back(OriginalChain);
11742       return;
11743     }
11744
11745     // Don't bother if we've been before.
11746     if (!Visited.insert(Chain.getNode()))
11747       continue;
11748
11749     switch (Chain.getOpcode()) {
11750     case ISD::EntryToken:
11751       // Entry token is ideal chain operand, but handled in FindBetterChain.
11752       break;
11753
11754     case ISD::LOAD:
11755     case ISD::STORE: {
11756       // Get alias information for Chain.
11757       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
11758           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
11759
11760       // If chain is alias then stop here.
11761       if (!(IsLoad && IsOpLoad) &&
11762           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
11763         Aliases.push_back(Chain);
11764       } else {
11765         // Look further up the chain.
11766         Chains.push_back(Chain.getOperand(0));
11767         ++Depth;
11768       }
11769       break;
11770     }
11771
11772     case ISD::TokenFactor:
11773       // We have to check each of the operands of the token factor for "small"
11774       // token factors, so we queue them up.  Adding the operands to the queue
11775       // (stack) in reverse order maintains the original order and increases the
11776       // likelihood that getNode will find a matching token factor (CSE.)
11777       if (Chain.getNumOperands() > 16) {
11778         Aliases.push_back(Chain);
11779         break;
11780       }
11781       for (unsigned n = Chain.getNumOperands(); n;)
11782         Chains.push_back(Chain.getOperand(--n));
11783       ++Depth;
11784       break;
11785
11786     default:
11787       // For all other instructions we will just have to take what we can get.
11788       Aliases.push_back(Chain);
11789       break;
11790     }
11791   }
11792
11793   // We need to be careful here to also search for aliases through the
11794   // value operand of a store, etc. Consider the following situation:
11795   //   Token1 = ...
11796   //   L1 = load Token1, %52
11797   //   S1 = store Token1, L1, %51
11798   //   L2 = load Token1, %52+8
11799   //   S2 = store Token1, L2, %51+8
11800   //   Token2 = Token(S1, S2)
11801   //   L3 = load Token2, %53
11802   //   S3 = store Token2, L3, %52
11803   //   L4 = load Token2, %53+8
11804   //   S4 = store Token2, L4, %52+8
11805   // If we search for aliases of S3 (which loads address %52), and we look
11806   // only through the chain, then we'll miss the trivial dependence on L1
11807   // (which also loads from %52). We then might change all loads and
11808   // stores to use Token1 as their chain operand, which could result in
11809   // copying %53 into %52 before copying %52 into %51 (which should
11810   // happen first).
11811   //
11812   // The problem is, however, that searching for such data dependencies
11813   // can become expensive, and the cost is not directly related to the
11814   // chain depth. Instead, we'll rule out such configurations here by
11815   // insisting that we've visited all chain users (except for users
11816   // of the original chain, which is not necessary). When doing this,
11817   // we need to look through nodes we don't care about (otherwise, things
11818   // like register copies will interfere with trivial cases).
11819
11820   SmallVector<const SDNode *, 16> Worklist;
11821   for (SmallPtrSet<SDNode *, 16>::iterator I = Visited.begin(),
11822        IE = Visited.end(); I != IE; ++I)
11823     if (*I != OriginalChain.getNode())
11824       Worklist.push_back(*I);
11825
11826   while (!Worklist.empty()) {
11827     const SDNode *M = Worklist.pop_back_val();
11828
11829     // We have already visited M, and want to make sure we've visited any uses
11830     // of M that we care about. For uses that we've not visisted, and don't
11831     // care about, queue them to the worklist.
11832
11833     for (SDNode::use_iterator UI = M->use_begin(),
11834          UIE = M->use_end(); UI != UIE; ++UI)
11835       if (UI.getUse().getValueType() == MVT::Other && Visited.insert(*UI)) {
11836         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
11837           // We've not visited this use, and we care about it (it could have an
11838           // ordering dependency with the original node).
11839           Aliases.clear();
11840           Aliases.push_back(OriginalChain);
11841           return;
11842         }
11843
11844         // We've not visited this use, but we don't care about it. Mark it as
11845         // visited and enqueue it to the worklist.
11846         Worklist.push_back(*UI);
11847       }
11848   }
11849 }
11850
11851 /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
11852 /// for a better chain (aliasing node.)
11853 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
11854   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
11855
11856   // Accumulate all the aliases to this node.
11857   GatherAllAliases(N, OldChain, Aliases);
11858
11859   // If no operands then chain to entry token.
11860   if (Aliases.size() == 0)
11861     return DAG.getEntryNode();
11862
11863   // If a single operand then chain to it.  We don't need to revisit it.
11864   if (Aliases.size() == 1)
11865     return Aliases[0];
11866
11867   // Construct a custom tailored token factor.
11868   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
11869 }
11870
11871 // SelectionDAG::Combine - This is the entry point for the file.
11872 //
11873 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
11874                            CodeGenOpt::Level OptLevel) {
11875   /// run - This is the main entry point to this class.
11876   ///
11877   DAGCombiner(*this, AA, OptLevel).Run(Level);
11878 }