Combine fcmp + select to fminnum / fmaxnum if no nans and legal
[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/SmallBitVector.h"
21 #include "llvm/ADT/SmallPtrSet.h"
22 #include "llvm/ADT/SetVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/Analysis/AliasAnalysis.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/IR/DataLayout.h"
28 #include "llvm/IR/DerivedTypes.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetLowering.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   static cl::opt<bool>
81     MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
82                       cl::desc("DAG combiner may split indexing from loads"));
83
84 //------------------------------ DAGCombiner ---------------------------------//
85
86   class DAGCombiner {
87     SelectionDAG &DAG;
88     const TargetLowering &TLI;
89     CombineLevel Level;
90     CodeGenOpt::Level OptLevel;
91     bool LegalOperations;
92     bool LegalTypes;
93     bool ForCodeSize;
94
95     /// \brief Worklist of all of the nodes that need to be simplified.
96     ///
97     /// This must behave as a stack -- new nodes to process are pushed onto the
98     /// back and when processing we pop off of the back.
99     ///
100     /// The worklist will not contain duplicates but may contain null entries
101     /// due to nodes being deleted from the underlying DAG.
102     SmallVector<SDNode *, 64> Worklist;
103
104     /// \brief Mapping from an SDNode to its position on the worklist.
105     ///
106     /// This is used to find and remove nodes from the worklist (by nulling
107     /// them) when they are deleted from the underlying DAG. It relies on
108     /// stable indices of nodes within the worklist.
109     DenseMap<SDNode *, unsigned> WorklistMap;
110
111     /// \brief Set of nodes which have been combined (at least once).
112     ///
113     /// This is used to allow us to reliably add any operands of a DAG node
114     /// which have not yet been combined to the worklist.
115     SmallPtrSet<SDNode *, 64> CombinedNodes;
116
117     // AA - Used for DAG load/store alias analysis.
118     AliasAnalysis &AA;
119
120     /// When an instruction is simplified, add all users of the instruction to
121     /// the work lists because they might get more simplified now.
122     void AddUsersToWorklist(SDNode *N) {
123       for (SDNode *Node : N->uses())
124         AddToWorklist(Node);
125     }
126
127     /// Call the node-specific routine that folds each particular type of node.
128     SDValue visit(SDNode *N);
129
130   public:
131     /// Add to the worklist making sure its instance is at the back (next to be
132     /// processed.)
133     void AddToWorklist(SDNode *N) {
134       // Skip handle nodes as they can't usefully be combined and confuse the
135       // zero-use deletion strategy.
136       if (N->getOpcode() == ISD::HANDLENODE)
137         return;
138
139       if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
140         Worklist.push_back(N);
141     }
142
143     /// Remove all instances of N from the worklist.
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     void deleteAndRecombine(SDNode *N);
157     bool recursivelyDeleteUnusedNodes(SDNode *N);
158
159     SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
160                       bool AddTo = true);
161
162     SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
163       return CombineTo(N, &Res, 1, AddTo);
164     }
165
166     SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
167                       bool AddTo = true) {
168       SDValue To[] = { Res0, Res1 };
169       return CombineTo(N, To, 2, AddTo);
170     }
171
172     void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
173
174   private:
175
176     /// Check the specified integer node value to see if it can be simplified or
177     /// if things it uses can be simplified by bit propagation.
178     /// If so, return true.
179     bool SimplifyDemandedBits(SDValue Op) {
180       unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
181       APInt Demanded = APInt::getAllOnesValue(BitWidth);
182       return SimplifyDemandedBits(Op, Demanded);
183     }
184
185     bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
186
187     bool CombineToPreIndexedLoadStore(SDNode *N);
188     bool CombineToPostIndexedLoadStore(SDNode *N);
189     SDValue SplitIndexingFromLoad(LoadSDNode *LD);
190     bool SliceUpLoad(SDNode *N);
191
192     /// \brief Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
193     ///   load.
194     ///
195     /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
196     /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
197     /// \param EltNo index of the vector element to load.
198     /// \param OriginalLoad load that EVE came from to be replaced.
199     /// \returns EVE on success SDValue() on failure.
200     SDValue ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
201         SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad);
202     void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
203     SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
204     SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
205     SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
206     SDValue PromoteIntBinOp(SDValue Op);
207     SDValue PromoteIntShiftOp(SDValue Op);
208     SDValue PromoteExtend(SDValue Op);
209     bool PromoteLoad(SDValue Op);
210
211     void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
212                          SDValue Trunc, SDValue ExtLoad, SDLoc DL,
213                          ISD::NodeType ExtType);
214
215     /// Call the node-specific routine that knows how to fold each
216     /// particular type of node. If that doesn't do anything, try the
217     /// target-specific DAG combines.
218     SDValue combine(SDNode *N);
219
220     // Visitation implementation - Implement dag node combining for different
221     // node types.  The semantics are as follows:
222     // Return Value:
223     //   SDValue.getNode() == 0 - No change was made
224     //   SDValue.getNode() == N - N was replaced, is dead and has been handled.
225     //   otherwise              - N should be replaced by the returned Operand.
226     //
227     SDValue visitTokenFactor(SDNode *N);
228     SDValue visitMERGE_VALUES(SDNode *N);
229     SDValue visitADD(SDNode *N);
230     SDValue visitSUB(SDNode *N);
231     SDValue visitADDC(SDNode *N);
232     SDValue visitSUBC(SDNode *N);
233     SDValue visitADDE(SDNode *N);
234     SDValue visitSUBE(SDNode *N);
235     SDValue visitMUL(SDNode *N);
236     SDValue visitSDIV(SDNode *N);
237     SDValue visitUDIV(SDNode *N);
238     SDValue visitSREM(SDNode *N);
239     SDValue visitUREM(SDNode *N);
240     SDValue visitMULHU(SDNode *N);
241     SDValue visitMULHS(SDNode *N);
242     SDValue visitSMUL_LOHI(SDNode *N);
243     SDValue visitUMUL_LOHI(SDNode *N);
244     SDValue visitSMULO(SDNode *N);
245     SDValue visitUMULO(SDNode *N);
246     SDValue visitSDIVREM(SDNode *N);
247     SDValue visitUDIVREM(SDNode *N);
248     SDValue visitAND(SDNode *N);
249     SDValue visitOR(SDNode *N);
250     SDValue visitXOR(SDNode *N);
251     SDValue SimplifyVBinOp(SDNode *N);
252     SDValue SimplifyVUnaryOp(SDNode *N);
253     SDValue visitSHL(SDNode *N);
254     SDValue visitSRA(SDNode *N);
255     SDValue visitSRL(SDNode *N);
256     SDValue visitRotate(SDNode *N);
257     SDValue visitCTLZ(SDNode *N);
258     SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
259     SDValue visitCTTZ(SDNode *N);
260     SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
261     SDValue visitCTPOP(SDNode *N);
262     SDValue visitSELECT(SDNode *N);
263     SDValue visitVSELECT(SDNode *N);
264     SDValue visitSELECT_CC(SDNode *N);
265     SDValue visitSETCC(SDNode *N);
266     SDValue visitSIGN_EXTEND(SDNode *N);
267     SDValue visitZERO_EXTEND(SDNode *N);
268     SDValue visitANY_EXTEND(SDNode *N);
269     SDValue visitSIGN_EXTEND_INREG(SDNode *N);
270     SDValue visitTRUNCATE(SDNode *N);
271     SDValue visitBITCAST(SDNode *N);
272     SDValue visitBUILD_PAIR(SDNode *N);
273     SDValue visitFADD(SDNode *N);
274     SDValue visitFSUB(SDNode *N);
275     SDValue visitFMUL(SDNode *N);
276     SDValue visitFMA(SDNode *N);
277     SDValue visitFDIV(SDNode *N);
278     SDValue visitFREM(SDNode *N);
279     SDValue visitFSQRT(SDNode *N);
280     SDValue visitFCOPYSIGN(SDNode *N);
281     SDValue visitSINT_TO_FP(SDNode *N);
282     SDValue visitUINT_TO_FP(SDNode *N);
283     SDValue visitFP_TO_SINT(SDNode *N);
284     SDValue visitFP_TO_UINT(SDNode *N);
285     SDValue visitFP_ROUND(SDNode *N);
286     SDValue visitFP_ROUND_INREG(SDNode *N);
287     SDValue visitFP_EXTEND(SDNode *N);
288     SDValue visitFNEG(SDNode *N);
289     SDValue visitFABS(SDNode *N);
290     SDValue visitFCEIL(SDNode *N);
291     SDValue visitFTRUNC(SDNode *N);
292     SDValue visitFFLOOR(SDNode *N);
293     SDValue visitFMINNUM(SDNode *N);
294     SDValue visitFMAXNUM(SDNode *N);
295     SDValue visitBRCOND(SDNode *N);
296     SDValue visitBR_CC(SDNode *N);
297     SDValue visitLOAD(SDNode *N);
298     SDValue visitSTORE(SDNode *N);
299     SDValue visitINSERT_VECTOR_ELT(SDNode *N);
300     SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
301     SDValue visitBUILD_VECTOR(SDNode *N);
302     SDValue visitCONCAT_VECTORS(SDNode *N);
303     SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
304     SDValue visitVECTOR_SHUFFLE(SDNode *N);
305     SDValue visitINSERT_SUBVECTOR(SDNode *N);
306     SDValue visitMLOAD(SDNode *N);
307     SDValue visitMSTORE(SDNode *N);
308
309     SDValue XformToShuffleWithZero(SDNode *N);
310     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
311
312     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
313
314     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
315     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
316     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
317     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
318                              SDValue N3, ISD::CondCode CC,
319                              bool NotExtCompare = false);
320     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
321                           SDLoc DL, bool foldBooleans = true);
322
323     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
324                            SDValue &CC) const;
325     bool isOneUseSetCC(SDValue N) const;
326
327     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
328                                          unsigned HiOp);
329     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
330     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
331     SDValue BuildSDIV(SDNode *N);
332     SDValue BuildSDIVPow2(SDNode *N);
333     SDValue BuildUDIV(SDNode *N);
334     SDValue BuildReciprocalEstimate(SDValue Op);
335     SDValue BuildRsqrtEstimate(SDValue Op);
336     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
337     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
338     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
339                                bool DemandHighBits = true);
340     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
341     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
342                               SDValue InnerPos, SDValue InnerNeg,
343                               unsigned PosOpcode, unsigned NegOpcode,
344                               SDLoc DL);
345     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
346     SDValue ReduceLoadWidth(SDNode *N);
347     SDValue ReduceLoadOpStoreWidth(SDNode *N);
348     SDValue TransformFPLoadStorePair(SDNode *N);
349     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
350     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
351
352     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
353
354     /// Walk up chain skipping non-aliasing memory nodes,
355     /// looking for aliasing nodes and adding them to the Aliases vector.
356     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
357                           SmallVectorImpl<SDValue> &Aliases);
358
359     /// Return true if there is any possibility that the two addresses overlap.
360     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
361
362     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
363     /// chain (aliasing node.)
364     SDValue FindBetterChain(SDNode *N, SDValue Chain);
365
366     /// Merge consecutive store operations into a wide store.
367     /// This optimization uses wide integers or vectors when possible.
368     /// \return True if some memory operations were changed.
369     bool MergeConsecutiveStores(StoreSDNode *N);
370
371     /// \brief Try to transform a truncation where C is a constant:
372     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
373     ///
374     /// \p N needs to be a truncation and its first operand an AND. Other
375     /// requirements are checked by the function (e.g. that trunc is
376     /// single-use) and if missed an empty SDValue is returned.
377     SDValue distributeTruncateThroughAnd(SDNode *N);
378
379   public:
380     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
381         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
382           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
383       AttributeSet FnAttrs =
384           DAG.getMachineFunction().getFunction()->getAttributes();
385       ForCodeSize =
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
387                                Attribute::OptimizeForSize) ||
388           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
389     }
390
391     /// Runs the dag combiner on all nodes in the work list
392     void Run(CombineLevel AtLevel);
393
394     SelectionDAG &getDAG() const { return DAG; }
395
396     /// Returns a type large enough to hold any valid shift amount - before type
397     /// legalization these can be huge.
398     EVT getShiftAmountTy(EVT LHSTy) {
399       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
400       if (LHSTy.isVector())
401         return LHSTy;
402       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
403                         : TLI.getPointerTy();
404     }
405
406     /// This method returns true if we are running before type legalization or
407     /// if the specified VT is legal.
408     bool isTypeLegal(const EVT &VT) {
409       if (!LegalTypes) return true;
410       return TLI.isTypeLegal(VT);
411     }
412
413     /// Convenience wrapper around TargetLowering::getSetCCResultType
414     EVT getSetCCResultType(EVT VT) const {
415       return TLI.getSetCCResultType(*DAG.getContext(), VT);
416     }
417   };
418 }
419
420
421 namespace {
422 /// This class is a DAGUpdateListener that removes any deleted
423 /// nodes from the worklist.
424 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
425   DAGCombiner &DC;
426 public:
427   explicit WorklistRemover(DAGCombiner &dc)
428     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
429
430   void NodeDeleted(SDNode *N, SDNode *E) override {
431     DC.removeFromWorklist(N);
432   }
433 };
434 }
435
436 //===----------------------------------------------------------------------===//
437 //  TargetLowering::DAGCombinerInfo implementation
438 //===----------------------------------------------------------------------===//
439
440 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
441   ((DAGCombiner*)DC)->AddToWorklist(N);
442 }
443
444 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
445   ((DAGCombiner*)DC)->removeFromWorklist(N);
446 }
447
448 SDValue TargetLowering::DAGCombinerInfo::
449 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
450   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
451 }
452
453 SDValue TargetLowering::DAGCombinerInfo::
454 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
455   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
456 }
457
458
459 SDValue TargetLowering::DAGCombinerInfo::
460 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
461   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
462 }
463
464 void TargetLowering::DAGCombinerInfo::
465 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
466   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
467 }
468
469 //===----------------------------------------------------------------------===//
470 // Helper Functions
471 //===----------------------------------------------------------------------===//
472
473 void DAGCombiner::deleteAndRecombine(SDNode *N) {
474   removeFromWorklist(N);
475
476   // If the operands of this node are only used by the node, they will now be
477   // dead. Make sure to re-visit them and recursively delete dead nodes.
478   for (const SDValue &Op : N->ops())
479     // For an operand generating multiple values, one of the values may
480     // become dead allowing further simplification (e.g. split index
481     // arithmetic from an indexed load).
482     if (Op->hasOneUse() || Op->getNumValues() > 1)
483       AddToWorklist(Op.getNode());
484
485   DAG.DeleteNode(N);
486 }
487
488 /// Return 1 if we can compute the negated form of the specified expression for
489 /// the same cost as the expression itself, or 2 if we can compute the negated
490 /// form more cheaply than the expression itself.
491 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
492                                const TargetLowering &TLI,
493                                const TargetOptions *Options,
494                                unsigned Depth = 0) {
495   // fneg is removable even if it has multiple uses.
496   if (Op.getOpcode() == ISD::FNEG) return 2;
497
498   // Don't allow anything with multiple uses.
499   if (!Op.hasOneUse()) return 0;
500
501   // Don't recurse exponentially.
502   if (Depth > 6) return 0;
503
504   switch (Op.getOpcode()) {
505   default: return false;
506   case ISD::ConstantFP:
507     // Don't invert constant FP values after legalize.  The negated constant
508     // isn't necessarily legal.
509     return LegalOperations ? 0 : 1;
510   case ISD::FADD:
511     // FIXME: determine better conditions for this xform.
512     if (!Options->UnsafeFPMath) return 0;
513
514     // After operation legalization, it might not be legal to create new FSUBs.
515     if (LegalOperations &&
516         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
517       return 0;
518
519     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
520     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
521                                     Options, Depth + 1))
522       return V;
523     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
524     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
525                               Depth + 1);
526   case ISD::FSUB:
527     // We can't turn -(A-B) into B-A when we honor signed zeros.
528     if (!Options->UnsafeFPMath) return 0;
529
530     // fold (fneg (fsub A, B)) -> (fsub B, A)
531     return 1;
532
533   case ISD::FMUL:
534   case ISD::FDIV:
535     if (Options->HonorSignDependentRoundingFPMath()) return 0;
536
537     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
538     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
539                                     Options, Depth + 1))
540       return V;
541
542     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
543                               Depth + 1);
544
545   case ISD::FP_EXTEND:
546   case ISD::FP_ROUND:
547   case ISD::FSIN:
548     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
549                               Depth + 1);
550   }
551 }
552
553 /// If isNegatibleForFree returns true, return the newly negated expression.
554 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
555                                     bool LegalOperations, unsigned Depth = 0) {
556   const TargetOptions &Options = DAG.getTarget().Options;
557   // fneg is removable even if it has multiple uses.
558   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
559
560   // Don't allow anything with multiple uses.
561   assert(Op.hasOneUse() && "Unknown reuse!");
562
563   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
564   switch (Op.getOpcode()) {
565   default: llvm_unreachable("Unknown code");
566   case ISD::ConstantFP: {
567     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
568     V.changeSign();
569     return DAG.getConstantFP(V, Op.getValueType());
570   }
571   case ISD::FADD:
572     // FIXME: determine better conditions for this xform.
573     assert(Options.UnsafeFPMath);
574
575     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
576     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
577                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
578       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
579                          GetNegatedExpression(Op.getOperand(0), DAG,
580                                               LegalOperations, Depth+1),
581                          Op.getOperand(1));
582     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
583     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
584                        GetNegatedExpression(Op.getOperand(1), DAG,
585                                             LegalOperations, Depth+1),
586                        Op.getOperand(0));
587   case ISD::FSUB:
588     // We can't turn -(A-B) into B-A when we honor signed zeros.
589     assert(Options.UnsafeFPMath);
590
591     // fold (fneg (fsub 0, B)) -> B
592     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
593       if (N0CFP->getValueAPF().isZero())
594         return Op.getOperand(1);
595
596     // fold (fneg (fsub A, B)) -> (fsub B, A)
597     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
598                        Op.getOperand(1), Op.getOperand(0));
599
600   case ISD::FMUL:
601   case ISD::FDIV:
602     assert(!Options.HonorSignDependentRoundingFPMath());
603
604     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
605     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
606                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
607       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
608                          GetNegatedExpression(Op.getOperand(0), DAG,
609                                               LegalOperations, Depth+1),
610                          Op.getOperand(1));
611
612     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
613     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
614                        Op.getOperand(0),
615                        GetNegatedExpression(Op.getOperand(1), DAG,
616                                             LegalOperations, Depth+1));
617
618   case ISD::FP_EXTEND:
619   case ISD::FSIN:
620     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
621                        GetNegatedExpression(Op.getOperand(0), DAG,
622                                             LegalOperations, Depth+1));
623   case ISD::FP_ROUND:
624       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
625                          GetNegatedExpression(Op.getOperand(0), DAG,
626                                               LegalOperations, Depth+1),
627                          Op.getOperand(1));
628   }
629 }
630
631 // Return true if this node is a setcc, or is a select_cc
632 // that selects between the target values used for true and false, making it
633 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
634 // the appropriate nodes based on the type of node we are checking. This
635 // simplifies life a bit for the callers.
636 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
637                                     SDValue &CC) const {
638   if (N.getOpcode() == ISD::SETCC) {
639     LHS = N.getOperand(0);
640     RHS = N.getOperand(1);
641     CC  = N.getOperand(2);
642     return true;
643   }
644
645   if (N.getOpcode() != ISD::SELECT_CC ||
646       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
647       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
648     return false;
649
650   if (TLI.getBooleanContents(N.getValueType()) ==
651       TargetLowering::UndefinedBooleanContent)
652     return false;
653
654   LHS = N.getOperand(0);
655   RHS = N.getOperand(1);
656   CC  = N.getOperand(4);
657   return true;
658 }
659
660 /// Return true if this is a SetCC-equivalent operation with only one use.
661 /// If this is true, it allows the users to invert the operation for free when
662 /// it is profitable to do so.
663 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
664   SDValue N0, N1, N2;
665   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
666     return true;
667   return false;
668 }
669
670 /// Returns true if N is a BUILD_VECTOR node whose
671 /// elements are all the same constant or undefined.
672 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
673   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
674   if (!C)
675     return false;
676
677   APInt SplatUndef;
678   unsigned SplatBitSize;
679   bool HasAnyUndefs;
680   EVT EltVT = N->getValueType(0).getVectorElementType();
681   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
682                              HasAnyUndefs) &&
683           EltVT.getSizeInBits() >= SplatBitSize);
684 }
685
686 // \brief Returns the SDNode if it is a constant BuildVector or constant.
687 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
688   if (isa<ConstantSDNode>(N))
689     return N.getNode();
690   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
691   if (BV && BV->isConstant())
692     return BV;
693   return nullptr;
694 }
695
696 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
697 // int.
698 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
699   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
700     return CN;
701
702   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
703     BitVector UndefElements;
704     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
705
706     // BuildVectors can truncate their operands. Ignore that case here.
707     // FIXME: We blindly ignore splats which include undef which is overly
708     // pessimistic.
709     if (CN && UndefElements.none() &&
710         CN->getValueType(0) == N.getValueType().getScalarType())
711       return CN;
712   }
713
714   return nullptr;
715 }
716
717 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
718 // float.
719 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
720   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
721     return CN;
722
723   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
724     BitVector UndefElements;
725     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
726
727     if (CN && UndefElements.none())
728       return CN;
729   }
730
731   return nullptr;
732 }
733
734 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
735                                     SDValue N0, SDValue N1) {
736   EVT VT = N0.getValueType();
737   if (N0.getOpcode() == Opc) {
738     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
739       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
740         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
741         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
742         if (!OpNode.getNode())
743           return SDValue();
744         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
745       }
746       if (N0.hasOneUse()) {
747         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
748         // use
749         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
750         if (!OpNode.getNode())
751           return SDValue();
752         AddToWorklist(OpNode.getNode());
753         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
754       }
755     }
756   }
757
758   if (N1.getOpcode() == Opc) {
759     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
760       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
761         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
762         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
763         if (!OpNode.getNode())
764           return SDValue();
765         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
766       }
767       if (N1.hasOneUse()) {
768         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
769         // use
770         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
771         if (!OpNode.getNode())
772           return SDValue();
773         AddToWorklist(OpNode.getNode());
774         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
775       }
776     }
777   }
778
779   return SDValue();
780 }
781
782 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
783                                bool AddTo) {
784   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
785   ++NodesCombined;
786   DEBUG(dbgs() << "\nReplacing.1 ";
787         N->dump(&DAG);
788         dbgs() << "\nWith: ";
789         To[0].getNode()->dump(&DAG);
790         dbgs() << " and " << NumTo-1 << " other values\n");
791   for (unsigned i = 0, e = NumTo; i != e; ++i)
792     assert((!To[i].getNode() ||
793             N->getValueType(i) == To[i].getValueType()) &&
794            "Cannot combine value to value of different type!");
795
796   WorklistRemover DeadNodes(*this);
797   DAG.ReplaceAllUsesWith(N, To);
798   if (AddTo) {
799     // Push the new nodes and any users onto the worklist
800     for (unsigned i = 0, e = NumTo; i != e; ++i) {
801       if (To[i].getNode()) {
802         AddToWorklist(To[i].getNode());
803         AddUsersToWorklist(To[i].getNode());
804       }
805     }
806   }
807
808   // Finally, if the node is now dead, remove it from the graph.  The node
809   // may not be dead if the replacement process recursively simplified to
810   // something else needing this node.
811   if (N->use_empty())
812     deleteAndRecombine(N);
813   return SDValue(N, 0);
814 }
815
816 void DAGCombiner::
817 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
818   // Replace all uses.  If any nodes become isomorphic to other nodes and
819   // are deleted, make sure to remove them from our worklist.
820   WorklistRemover DeadNodes(*this);
821   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
822
823   // Push the new node and any (possibly new) users onto the worklist.
824   AddToWorklist(TLO.New.getNode());
825   AddUsersToWorklist(TLO.New.getNode());
826
827   // Finally, if the node is now dead, remove it from the graph.  The node
828   // may not be dead if the replacement process recursively simplified to
829   // something else needing this node.
830   if (TLO.Old.getNode()->use_empty())
831     deleteAndRecombine(TLO.Old.getNode());
832 }
833
834 /// Check the specified integer node value to see if it can be simplified or if
835 /// things it uses can be simplified by bit propagation. If so, return true.
836 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
837   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
838   APInt KnownZero, KnownOne;
839   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
840     return false;
841
842   // Revisit the node.
843   AddToWorklist(Op.getNode());
844
845   // Replace the old value with the new one.
846   ++NodesCombined;
847   DEBUG(dbgs() << "\nReplacing.2 ";
848         TLO.Old.getNode()->dump(&DAG);
849         dbgs() << "\nWith: ";
850         TLO.New.getNode()->dump(&DAG);
851         dbgs() << '\n');
852
853   CommitTargetLoweringOpt(TLO);
854   return true;
855 }
856
857 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
858   SDLoc dl(Load);
859   EVT VT = Load->getValueType(0);
860   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
861
862   DEBUG(dbgs() << "\nReplacing.9 ";
863         Load->dump(&DAG);
864         dbgs() << "\nWith: ";
865         Trunc.getNode()->dump(&DAG);
866         dbgs() << '\n');
867   WorklistRemover DeadNodes(*this);
868   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
869   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
870   deleteAndRecombine(Load);
871   AddToWorklist(Trunc.getNode());
872 }
873
874 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
875   Replace = false;
876   SDLoc dl(Op);
877   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
878     EVT MemVT = LD->getMemoryVT();
879     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
880       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
881                                                        : ISD::EXTLOAD)
882       : LD->getExtensionType();
883     Replace = true;
884     return DAG.getExtLoad(ExtType, dl, PVT,
885                           LD->getChain(), LD->getBasePtr(),
886                           MemVT, LD->getMemOperand());
887   }
888
889   unsigned Opc = Op.getOpcode();
890   switch (Opc) {
891   default: break;
892   case ISD::AssertSext:
893     return DAG.getNode(ISD::AssertSext, dl, PVT,
894                        SExtPromoteOperand(Op.getOperand(0), PVT),
895                        Op.getOperand(1));
896   case ISD::AssertZext:
897     return DAG.getNode(ISD::AssertZext, dl, PVT,
898                        ZExtPromoteOperand(Op.getOperand(0), PVT),
899                        Op.getOperand(1));
900   case ISD::Constant: {
901     unsigned ExtOpc =
902       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
903     return DAG.getNode(ExtOpc, dl, PVT, Op);
904   }
905   }
906
907   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
908     return SDValue();
909   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
910 }
911
912 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
913   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
914     return SDValue();
915   EVT OldVT = Op.getValueType();
916   SDLoc dl(Op);
917   bool Replace = false;
918   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
919   if (!NewOp.getNode())
920     return SDValue();
921   AddToWorklist(NewOp.getNode());
922
923   if (Replace)
924     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
925   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
926                      DAG.getValueType(OldVT));
927 }
928
929 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
930   EVT OldVT = Op.getValueType();
931   SDLoc dl(Op);
932   bool Replace = false;
933   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
934   if (!NewOp.getNode())
935     return SDValue();
936   AddToWorklist(NewOp.getNode());
937
938   if (Replace)
939     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
940   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
941 }
942
943 /// Promote the specified integer binary operation if the target indicates it is
944 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
945 /// i32 since i16 instructions are longer.
946 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
947   if (!LegalOperations)
948     return SDValue();
949
950   EVT VT = Op.getValueType();
951   if (VT.isVector() || !VT.isInteger())
952     return SDValue();
953
954   // If operation type is 'undesirable', e.g. i16 on x86, consider
955   // promoting it.
956   unsigned Opc = Op.getOpcode();
957   if (TLI.isTypeDesirableForOp(Opc, VT))
958     return SDValue();
959
960   EVT PVT = VT;
961   // Consult target whether it is a good idea to promote this operation and
962   // what's the right type to promote it to.
963   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
964     assert(PVT != VT && "Don't know what type to promote to!");
965
966     bool Replace0 = false;
967     SDValue N0 = Op.getOperand(0);
968     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
969     if (!NN0.getNode())
970       return SDValue();
971
972     bool Replace1 = false;
973     SDValue N1 = Op.getOperand(1);
974     SDValue NN1;
975     if (N0 == N1)
976       NN1 = NN0;
977     else {
978       NN1 = PromoteOperand(N1, PVT, Replace1);
979       if (!NN1.getNode())
980         return SDValue();
981     }
982
983     AddToWorklist(NN0.getNode());
984     if (NN1.getNode())
985       AddToWorklist(NN1.getNode());
986
987     if (Replace0)
988       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
989     if (Replace1)
990       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
991
992     DEBUG(dbgs() << "\nPromoting ";
993           Op.getNode()->dump(&DAG));
994     SDLoc dl(Op);
995     return DAG.getNode(ISD::TRUNCATE, dl, VT,
996                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
997   }
998   return SDValue();
999 }
1000
1001 /// Promote the specified integer shift operation if the target indicates it is
1002 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1003 /// i32 since i16 instructions are longer.
1004 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1005   if (!LegalOperations)
1006     return SDValue();
1007
1008   EVT VT = Op.getValueType();
1009   if (VT.isVector() || !VT.isInteger())
1010     return SDValue();
1011
1012   // If operation type is 'undesirable', e.g. i16 on x86, consider
1013   // promoting it.
1014   unsigned Opc = Op.getOpcode();
1015   if (TLI.isTypeDesirableForOp(Opc, VT))
1016     return SDValue();
1017
1018   EVT PVT = VT;
1019   // Consult target whether it is a good idea to promote this operation and
1020   // what's the right type to promote it to.
1021   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1022     assert(PVT != VT && "Don't know what type to promote to!");
1023
1024     bool Replace = false;
1025     SDValue N0 = Op.getOperand(0);
1026     if (Opc == ISD::SRA)
1027       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1028     else if (Opc == ISD::SRL)
1029       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1030     else
1031       N0 = PromoteOperand(N0, PVT, Replace);
1032     if (!N0.getNode())
1033       return SDValue();
1034
1035     AddToWorklist(N0.getNode());
1036     if (Replace)
1037       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1038
1039     DEBUG(dbgs() << "\nPromoting ";
1040           Op.getNode()->dump(&DAG));
1041     SDLoc dl(Op);
1042     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1043                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1044   }
1045   return SDValue();
1046 }
1047
1048 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1049   if (!LegalOperations)
1050     return SDValue();
1051
1052   EVT VT = Op.getValueType();
1053   if (VT.isVector() || !VT.isInteger())
1054     return SDValue();
1055
1056   // If operation type is 'undesirable', e.g. i16 on x86, consider
1057   // promoting it.
1058   unsigned Opc = Op.getOpcode();
1059   if (TLI.isTypeDesirableForOp(Opc, VT))
1060     return SDValue();
1061
1062   EVT PVT = VT;
1063   // Consult target whether it is a good idea to promote this operation and
1064   // what's the right type to promote it to.
1065   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1066     assert(PVT != VT && "Don't know what type to promote to!");
1067     // fold (aext (aext x)) -> (aext x)
1068     // fold (aext (zext x)) -> (zext x)
1069     // fold (aext (sext x)) -> (sext x)
1070     DEBUG(dbgs() << "\nPromoting ";
1071           Op.getNode()->dump(&DAG));
1072     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1073   }
1074   return SDValue();
1075 }
1076
1077 bool DAGCombiner::PromoteLoad(SDValue Op) {
1078   if (!LegalOperations)
1079     return false;
1080
1081   EVT VT = Op.getValueType();
1082   if (VT.isVector() || !VT.isInteger())
1083     return false;
1084
1085   // If operation type is 'undesirable', e.g. i16 on x86, consider
1086   // promoting it.
1087   unsigned Opc = Op.getOpcode();
1088   if (TLI.isTypeDesirableForOp(Opc, VT))
1089     return false;
1090
1091   EVT PVT = VT;
1092   // Consult target whether it is a good idea to promote this operation and
1093   // what's the right type to promote it to.
1094   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1095     assert(PVT != VT && "Don't know what type to promote to!");
1096
1097     SDLoc dl(Op);
1098     SDNode *N = Op.getNode();
1099     LoadSDNode *LD = cast<LoadSDNode>(N);
1100     EVT MemVT = LD->getMemoryVT();
1101     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1102       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, PVT, MemVT) ? ISD::ZEXTLOAD
1103                                                        : ISD::EXTLOAD)
1104       : LD->getExtensionType();
1105     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1106                                    LD->getChain(), LD->getBasePtr(),
1107                                    MemVT, LD->getMemOperand());
1108     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1109
1110     DEBUG(dbgs() << "\nPromoting ";
1111           N->dump(&DAG);
1112           dbgs() << "\nTo: ";
1113           Result.getNode()->dump(&DAG);
1114           dbgs() << '\n');
1115     WorklistRemover DeadNodes(*this);
1116     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1117     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1118     deleteAndRecombine(N);
1119     AddToWorklist(Result.getNode());
1120     return true;
1121   }
1122   return false;
1123 }
1124
1125 /// \brief Recursively delete a node which has no uses and any operands for
1126 /// which it is the only use.
1127 ///
1128 /// Note that this both deletes the nodes and removes them from the worklist.
1129 /// It also adds any nodes who have had a user deleted to the worklist as they
1130 /// may now have only one use and subject to other combines.
1131 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1132   if (!N->use_empty())
1133     return false;
1134
1135   SmallSetVector<SDNode *, 16> Nodes;
1136   Nodes.insert(N);
1137   do {
1138     N = Nodes.pop_back_val();
1139     if (!N)
1140       continue;
1141
1142     if (N->use_empty()) {
1143       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1144         Nodes.insert(N->getOperand(i).getNode());
1145
1146       removeFromWorklist(N);
1147       DAG.DeleteNode(N);
1148     } else {
1149       AddToWorklist(N);
1150     }
1151   } while (!Nodes.empty());
1152   return true;
1153 }
1154
1155 //===----------------------------------------------------------------------===//
1156 //  Main DAG Combiner implementation
1157 //===----------------------------------------------------------------------===//
1158
1159 void DAGCombiner::Run(CombineLevel AtLevel) {
1160   // set the instance variables, so that the various visit routines may use it.
1161   Level = AtLevel;
1162   LegalOperations = Level >= AfterLegalizeVectorOps;
1163   LegalTypes = Level >= AfterLegalizeTypes;
1164
1165   // Early exit if this basic block is in an optnone function.
1166   AttributeSet FnAttrs =
1167     DAG.getMachineFunction().getFunction()->getAttributes();
1168   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1169                            Attribute::OptimizeNone))
1170     return;
1171
1172   // Add all the dag nodes to the worklist.
1173   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1174        E = DAG.allnodes_end(); I != E; ++I)
1175     AddToWorklist(I);
1176
1177   // Create a dummy node (which is not added to allnodes), that adds a reference
1178   // to the root node, preventing it from being deleted, and tracking any
1179   // changes of the root.
1180   HandleSDNode Dummy(DAG.getRoot());
1181
1182   // while the worklist isn't empty, find a node and
1183   // try and combine it.
1184   while (!WorklistMap.empty()) {
1185     SDNode *N;
1186     // The Worklist holds the SDNodes in order, but it may contain null entries.
1187     do {
1188       N = Worklist.pop_back_val();
1189     } while (!N);
1190
1191     bool GoodWorklistEntry = WorklistMap.erase(N);
1192     (void)GoodWorklistEntry;
1193     assert(GoodWorklistEntry &&
1194            "Found a worklist entry without a corresponding map entry!");
1195
1196     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1197     // N is deleted from the DAG, since they too may now be dead or may have a
1198     // reduced number of uses, allowing other xforms.
1199     if (recursivelyDeleteUnusedNodes(N))
1200       continue;
1201
1202     WorklistRemover DeadNodes(*this);
1203
1204     // If this combine is running after legalizing the DAG, re-legalize any
1205     // nodes pulled off the worklist.
1206     if (Level == AfterLegalizeDAG) {
1207       SmallSetVector<SDNode *, 16> UpdatedNodes;
1208       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1209
1210       for (SDNode *LN : UpdatedNodes) {
1211         AddToWorklist(LN);
1212         AddUsersToWorklist(LN);
1213       }
1214       if (!NIsValid)
1215         continue;
1216     }
1217
1218     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1219
1220     // Add any operands of the new node which have not yet been combined to the
1221     // worklist as well. Because the worklist uniques things already, this
1222     // won't repeatedly process the same operand.
1223     CombinedNodes.insert(N);
1224     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1225       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1226         AddToWorklist(N->getOperand(i).getNode());
1227
1228     SDValue RV = combine(N);
1229
1230     if (!RV.getNode())
1231       continue;
1232
1233     ++NodesCombined;
1234
1235     // If we get back the same node we passed in, rather than a new node or
1236     // zero, we know that the node must have defined multiple values and
1237     // CombineTo was used.  Since CombineTo takes care of the worklist
1238     // mechanics for us, we have no work to do in this case.
1239     if (RV.getNode() == N)
1240       continue;
1241
1242     assert(N->getOpcode() != ISD::DELETED_NODE &&
1243            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1244            "Node was deleted but visit returned new node!");
1245
1246     DEBUG(dbgs() << " ... into: ";
1247           RV.getNode()->dump(&DAG));
1248
1249     // Transfer debug value.
1250     DAG.TransferDbgValues(SDValue(N, 0), RV);
1251     if (N->getNumValues() == RV.getNode()->getNumValues())
1252       DAG.ReplaceAllUsesWith(N, RV.getNode());
1253     else {
1254       assert(N->getValueType(0) == RV.getValueType() &&
1255              N->getNumValues() == 1 && "Type mismatch");
1256       SDValue OpV = RV;
1257       DAG.ReplaceAllUsesWith(N, &OpV);
1258     }
1259
1260     // Push the new node and any users onto the worklist
1261     AddToWorklist(RV.getNode());
1262     AddUsersToWorklist(RV.getNode());
1263
1264     // Finally, if the node is now dead, remove it from the graph.  The node
1265     // may not be dead if the replacement process recursively simplified to
1266     // something else needing this node. This will also take care of adding any
1267     // operands which have lost a user to the worklist.
1268     recursivelyDeleteUnusedNodes(N);
1269   }
1270
1271   // If the root changed (e.g. it was a dead load, update the root).
1272   DAG.setRoot(Dummy.getValue());
1273   DAG.RemoveDeadNodes();
1274 }
1275
1276 SDValue DAGCombiner::visit(SDNode *N) {
1277   switch (N->getOpcode()) {
1278   default: break;
1279   case ISD::TokenFactor:        return visitTokenFactor(N);
1280   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1281   case ISD::ADD:                return visitADD(N);
1282   case ISD::SUB:                return visitSUB(N);
1283   case ISD::ADDC:               return visitADDC(N);
1284   case ISD::SUBC:               return visitSUBC(N);
1285   case ISD::ADDE:               return visitADDE(N);
1286   case ISD::SUBE:               return visitSUBE(N);
1287   case ISD::MUL:                return visitMUL(N);
1288   case ISD::SDIV:               return visitSDIV(N);
1289   case ISD::UDIV:               return visitUDIV(N);
1290   case ISD::SREM:               return visitSREM(N);
1291   case ISD::UREM:               return visitUREM(N);
1292   case ISD::MULHU:              return visitMULHU(N);
1293   case ISD::MULHS:              return visitMULHS(N);
1294   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1295   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1296   case ISD::SMULO:              return visitSMULO(N);
1297   case ISD::UMULO:              return visitUMULO(N);
1298   case ISD::SDIVREM:            return visitSDIVREM(N);
1299   case ISD::UDIVREM:            return visitUDIVREM(N);
1300   case ISD::AND:                return visitAND(N);
1301   case ISD::OR:                 return visitOR(N);
1302   case ISD::XOR:                return visitXOR(N);
1303   case ISD::SHL:                return visitSHL(N);
1304   case ISD::SRA:                return visitSRA(N);
1305   case ISD::SRL:                return visitSRL(N);
1306   case ISD::ROTR:
1307   case ISD::ROTL:               return visitRotate(N);
1308   case ISD::CTLZ:               return visitCTLZ(N);
1309   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1310   case ISD::CTTZ:               return visitCTTZ(N);
1311   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1312   case ISD::CTPOP:              return visitCTPOP(N);
1313   case ISD::SELECT:             return visitSELECT(N);
1314   case ISD::VSELECT:            return visitVSELECT(N);
1315   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1316   case ISD::SETCC:              return visitSETCC(N);
1317   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1318   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1319   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1320   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1321   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1322   case ISD::BITCAST:            return visitBITCAST(N);
1323   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1324   case ISD::FADD:               return visitFADD(N);
1325   case ISD::FSUB:               return visitFSUB(N);
1326   case ISD::FMUL:               return visitFMUL(N);
1327   case ISD::FMA:                return visitFMA(N);
1328   case ISD::FDIV:               return visitFDIV(N);
1329   case ISD::FREM:               return visitFREM(N);
1330   case ISD::FSQRT:              return visitFSQRT(N);
1331   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1332   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1333   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1334   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1335   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1336   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1337   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1338   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1339   case ISD::FNEG:               return visitFNEG(N);
1340   case ISD::FABS:               return visitFABS(N);
1341   case ISD::FFLOOR:             return visitFFLOOR(N);
1342   case ISD::FMINNUM:            return visitFMINNUM(N);
1343   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1344   case ISD::FCEIL:              return visitFCEIL(N);
1345   case ISD::FTRUNC:             return visitFTRUNC(N);
1346   case ISD::BRCOND:             return visitBRCOND(N);
1347   case ISD::BR_CC:              return visitBR_CC(N);
1348   case ISD::LOAD:               return visitLOAD(N);
1349   case ISD::STORE:              return visitSTORE(N);
1350   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1351   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1352   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1353   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1354   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1355   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1356   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1357   case ISD::MLOAD:              return visitMLOAD(N);
1358   case ISD::MSTORE:             return visitMSTORE(N);
1359   }
1360   return SDValue();
1361 }
1362
1363 SDValue DAGCombiner::combine(SDNode *N) {
1364   SDValue RV = visit(N);
1365
1366   // If nothing happened, try a target-specific DAG combine.
1367   if (!RV.getNode()) {
1368     assert(N->getOpcode() != ISD::DELETED_NODE &&
1369            "Node was deleted but visit returned NULL!");
1370
1371     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1372         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1373
1374       // Expose the DAG combiner to the target combiner impls.
1375       TargetLowering::DAGCombinerInfo
1376         DagCombineInfo(DAG, Level, false, this);
1377
1378       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1379     }
1380   }
1381
1382   // If nothing happened still, try promoting the operation.
1383   if (!RV.getNode()) {
1384     switch (N->getOpcode()) {
1385     default: break;
1386     case ISD::ADD:
1387     case ISD::SUB:
1388     case ISD::MUL:
1389     case ISD::AND:
1390     case ISD::OR:
1391     case ISD::XOR:
1392       RV = PromoteIntBinOp(SDValue(N, 0));
1393       break;
1394     case ISD::SHL:
1395     case ISD::SRA:
1396     case ISD::SRL:
1397       RV = PromoteIntShiftOp(SDValue(N, 0));
1398       break;
1399     case ISD::SIGN_EXTEND:
1400     case ISD::ZERO_EXTEND:
1401     case ISD::ANY_EXTEND:
1402       RV = PromoteExtend(SDValue(N, 0));
1403       break;
1404     case ISD::LOAD:
1405       if (PromoteLoad(SDValue(N, 0)))
1406         RV = SDValue(N, 0);
1407       break;
1408     }
1409   }
1410
1411   // If N is a commutative binary node, try commuting it to enable more
1412   // sdisel CSE.
1413   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1414       N->getNumValues() == 1) {
1415     SDValue N0 = N->getOperand(0);
1416     SDValue N1 = N->getOperand(1);
1417
1418     // Constant operands are canonicalized to RHS.
1419     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1420       SDValue Ops[] = {N1, N0};
1421       SDNode *CSENode;
1422       if (const BinaryWithFlagsSDNode *BinNode =
1423               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1424         CSENode = DAG.getNodeIfExists(
1425             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1426             BinNode->hasNoSignedWrap(), BinNode->isExact());
1427       } else {
1428         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1429       }
1430       if (CSENode)
1431         return SDValue(CSENode, 0);
1432     }
1433   }
1434
1435   return RV;
1436 }
1437
1438 /// Given a node, return its input chain if it has one, otherwise return a null
1439 /// sd operand.
1440 static SDValue getInputChainForNode(SDNode *N) {
1441   if (unsigned NumOps = N->getNumOperands()) {
1442     if (N->getOperand(0).getValueType() == MVT::Other)
1443       return N->getOperand(0);
1444     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1445       return N->getOperand(NumOps-1);
1446     for (unsigned i = 1; i < NumOps-1; ++i)
1447       if (N->getOperand(i).getValueType() == MVT::Other)
1448         return N->getOperand(i);
1449   }
1450   return SDValue();
1451 }
1452
1453 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1454   // If N has two operands, where one has an input chain equal to the other,
1455   // the 'other' chain is redundant.
1456   if (N->getNumOperands() == 2) {
1457     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1458       return N->getOperand(0);
1459     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1460       return N->getOperand(1);
1461   }
1462
1463   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1464   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1465   SmallPtrSet<SDNode*, 16> SeenOps;
1466   bool Changed = false;             // If we should replace this token factor.
1467
1468   // Start out with this token factor.
1469   TFs.push_back(N);
1470
1471   // Iterate through token factors.  The TFs grows when new token factors are
1472   // encountered.
1473   for (unsigned i = 0; i < TFs.size(); ++i) {
1474     SDNode *TF = TFs[i];
1475
1476     // Check each of the operands.
1477     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1478       SDValue Op = TF->getOperand(i);
1479
1480       switch (Op.getOpcode()) {
1481       case ISD::EntryToken:
1482         // Entry tokens don't need to be added to the list. They are
1483         // rededundant.
1484         Changed = true;
1485         break;
1486
1487       case ISD::TokenFactor:
1488         if (Op.hasOneUse() &&
1489             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1490           // Queue up for processing.
1491           TFs.push_back(Op.getNode());
1492           // Clean up in case the token factor is removed.
1493           AddToWorklist(Op.getNode());
1494           Changed = true;
1495           break;
1496         }
1497         // Fall thru
1498
1499       default:
1500         // Only add if it isn't already in the list.
1501         if (SeenOps.insert(Op.getNode()).second)
1502           Ops.push_back(Op);
1503         else
1504           Changed = true;
1505         break;
1506       }
1507     }
1508   }
1509
1510   SDValue Result;
1511
1512   // If we've change things around then replace token factor.
1513   if (Changed) {
1514     if (Ops.empty()) {
1515       // The entry token is the only possible outcome.
1516       Result = DAG.getEntryNode();
1517     } else {
1518       // New and improved token factor.
1519       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1520     }
1521
1522     // Don't add users to work list.
1523     return CombineTo(N, Result, false);
1524   }
1525
1526   return Result;
1527 }
1528
1529 /// MERGE_VALUES can always be eliminated.
1530 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1531   WorklistRemover DeadNodes(*this);
1532   // Replacing results may cause a different MERGE_VALUES to suddenly
1533   // be CSE'd with N, and carry its uses with it. Iterate until no
1534   // uses remain, to ensure that the node can be safely deleted.
1535   // First add the users of this node to the work list so that they
1536   // can be tried again once they have new operands.
1537   AddUsersToWorklist(N);
1538   do {
1539     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1540       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1541   } while (!N->use_empty());
1542   deleteAndRecombine(N);
1543   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1544 }
1545
1546 SDValue DAGCombiner::visitADD(SDNode *N) {
1547   SDValue N0 = N->getOperand(0);
1548   SDValue N1 = N->getOperand(1);
1549   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1550   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1551   EVT VT = N0.getValueType();
1552
1553   // fold vector ops
1554   if (VT.isVector()) {
1555     SDValue FoldedVOp = SimplifyVBinOp(N);
1556     if (FoldedVOp.getNode()) return FoldedVOp;
1557
1558     // fold (add x, 0) -> x, vector edition
1559     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1560       return N0;
1561     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1562       return N1;
1563   }
1564
1565   // fold (add x, undef) -> undef
1566   if (N0.getOpcode() == ISD::UNDEF)
1567     return N0;
1568   if (N1.getOpcode() == ISD::UNDEF)
1569     return N1;
1570   // fold (add c1, c2) -> c1+c2
1571   if (N0C && N1C)
1572     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1573   // canonicalize constant to RHS
1574   if (N0C && !N1C)
1575     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1576   // fold (add x, 0) -> x
1577   if (N1C && N1C->isNullValue())
1578     return N0;
1579   // fold (add Sym, c) -> Sym+c
1580   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1581     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1582         GA->getOpcode() == ISD::GlobalAddress)
1583       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1584                                   GA->getOffset() +
1585                                     (uint64_t)N1C->getSExtValue());
1586   // fold ((c1-A)+c2) -> (c1+c2)-A
1587   if (N1C && N0.getOpcode() == ISD::SUB)
1588     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1589       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1590                          DAG.getConstant(N1C->getAPIntValue()+
1591                                          N0C->getAPIntValue(), VT),
1592                          N0.getOperand(1));
1593   // reassociate add
1594   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1595   if (RADD.getNode())
1596     return RADD;
1597   // fold ((0-A) + B) -> B-A
1598   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1599       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1600     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1601   // fold (A + (0-B)) -> A-B
1602   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1603       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1604     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1605   // fold (A+(B-A)) -> B
1606   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1607     return N1.getOperand(0);
1608   // fold ((B-A)+A) -> B
1609   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1610     return N0.getOperand(0);
1611   // fold (A+(B-(A+C))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(0))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(1));
1616   // fold (A+(B-(C+A))) to (B-C)
1617   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1618       N0 == N1.getOperand(1).getOperand(1))
1619     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1620                        N1.getOperand(1).getOperand(0));
1621   // fold (A+((B-A)+or-C)) to (B+or-C)
1622   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1623       N1.getOperand(0).getOpcode() == ISD::SUB &&
1624       N0 == N1.getOperand(0).getOperand(1))
1625     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1626                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1627
1628   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1629   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1630     SDValue N00 = N0.getOperand(0);
1631     SDValue N01 = N0.getOperand(1);
1632     SDValue N10 = N1.getOperand(0);
1633     SDValue N11 = N1.getOperand(1);
1634
1635     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1636       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1637                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1638                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1639   }
1640
1641   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1642     return SDValue(N, 0);
1643
1644   // fold (a+b) -> (a|b) iff a and b share no bits.
1645   if (VT.isInteger() && !VT.isVector()) {
1646     APInt LHSZero, LHSOne;
1647     APInt RHSZero, RHSOne;
1648     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1649
1650     if (LHSZero.getBoolValue()) {
1651       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1652
1653       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1654       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1655       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1656         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1657           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1658       }
1659     }
1660   }
1661
1662   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1663   if (N1.getOpcode() == ISD::SHL &&
1664       N1.getOperand(0).getOpcode() == ISD::SUB)
1665     if (ConstantSDNode *C =
1666           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1667       if (C->getAPIntValue() == 0)
1668         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1669                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1670                                        N1.getOperand(0).getOperand(1),
1671                                        N1.getOperand(1)));
1672   if (N0.getOpcode() == ISD::SHL &&
1673       N0.getOperand(0).getOpcode() == ISD::SUB)
1674     if (ConstantSDNode *C =
1675           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1676       if (C->getAPIntValue() == 0)
1677         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1678                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1679                                        N0.getOperand(0).getOperand(1),
1680                                        N0.getOperand(1)));
1681
1682   if (N1.getOpcode() == ISD::AND) {
1683     SDValue AndOp0 = N1.getOperand(0);
1684     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1685     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1686     unsigned DestBits = VT.getScalarType().getSizeInBits();
1687
1688     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1689     // and similar xforms where the inner op is either ~0 or 0.
1690     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1691       SDLoc DL(N);
1692       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1693     }
1694   }
1695
1696   // add (sext i1), X -> sub X, (zext i1)
1697   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1698       N0.getOperand(0).getValueType() == MVT::i1 &&
1699       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1700     SDLoc DL(N);
1701     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1702     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1703   }
1704
1705   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1706   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1707     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1708     if (TN->getVT() == MVT::i1) {
1709       SDLoc DL(N);
1710       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1711                                  DAG.getConstant(1, VT));
1712       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1713     }
1714   }
1715
1716   return SDValue();
1717 }
1718
1719 SDValue DAGCombiner::visitADDC(SDNode *N) {
1720   SDValue N0 = N->getOperand(0);
1721   SDValue N1 = N->getOperand(1);
1722   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1723   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1724   EVT VT = N0.getValueType();
1725
1726   // If the flag result is dead, turn this into an ADD.
1727   if (!N->hasAnyUseOfValue(1))
1728     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1729                      DAG.getNode(ISD::CARRY_FALSE,
1730                                  SDLoc(N), MVT::Glue));
1731
1732   // canonicalize constant to RHS.
1733   if (N0C && !N1C)
1734     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1735
1736   // fold (addc x, 0) -> x + no carry out
1737   if (N1C && N1C->isNullValue())
1738     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1739                                         SDLoc(N), MVT::Glue));
1740
1741   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1742   APInt LHSZero, LHSOne;
1743   APInt RHSZero, RHSOne;
1744   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1745
1746   if (LHSZero.getBoolValue()) {
1747     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1748
1749     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1750     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1751     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1752       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1753                        DAG.getNode(ISD::CARRY_FALSE,
1754                                    SDLoc(N), MVT::Glue));
1755   }
1756
1757   return SDValue();
1758 }
1759
1760 SDValue DAGCombiner::visitADDE(SDNode *N) {
1761   SDValue N0 = N->getOperand(0);
1762   SDValue N1 = N->getOperand(1);
1763   SDValue CarryIn = N->getOperand(2);
1764   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1765   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1766
1767   // canonicalize constant to RHS
1768   if (N0C && !N1C)
1769     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1770                        N1, N0, CarryIn);
1771
1772   // fold (adde x, y, false) -> (addc x, y)
1773   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1774     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1775
1776   return SDValue();
1777 }
1778
1779 // Since it may not be valid to emit a fold to zero for vector initializers
1780 // check if we can before folding.
1781 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1782                              SelectionDAG &DAG,
1783                              bool LegalOperations, bool LegalTypes) {
1784   if (!VT.isVector())
1785     return DAG.getConstant(0, VT);
1786   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1787     return DAG.getConstant(0, VT);
1788   return SDValue();
1789 }
1790
1791 SDValue DAGCombiner::visitSUB(SDNode *N) {
1792   SDValue N0 = N->getOperand(0);
1793   SDValue N1 = N->getOperand(1);
1794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1796   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1797     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1798   EVT VT = N0.getValueType();
1799
1800   // fold vector ops
1801   if (VT.isVector()) {
1802     SDValue FoldedVOp = SimplifyVBinOp(N);
1803     if (FoldedVOp.getNode()) return FoldedVOp;
1804
1805     // fold (sub x, 0) -> x, vector edition
1806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1807       return N0;
1808   }
1809
1810   // fold (sub x, x) -> 0
1811   // FIXME: Refactor this and xor and other similar operations together.
1812   if (N0 == N1)
1813     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1814   // fold (sub c1, c2) -> c1-c2
1815   if (N0C && N1C)
1816     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1817   // fold (sub x, c) -> (add x, -c)
1818   if (N1C)
1819     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1820                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1821   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1822   if (N0C && N0C->isAllOnesValue())
1823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1824   // fold A-(A-B) -> B
1825   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1826     return N1.getOperand(1);
1827   // fold (A+B)-A -> B
1828   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1829     return N0.getOperand(1);
1830   // fold (A+B)-B -> A
1831   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1832     return N0.getOperand(0);
1833   // fold C2-(A+C1) -> (C2-C1)-A
1834   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1835     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1836                                    VT);
1837     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1838                        N1.getOperand(0));
1839   }
1840   // fold ((A+(B+or-C))-B) -> A+or-C
1841   if (N0.getOpcode() == ISD::ADD &&
1842       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1843        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1844       N0.getOperand(1).getOperand(0) == N1)
1845     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1846                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1847   // fold ((A+(C+B))-B) -> A+C
1848   if (N0.getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOpcode() == ISD::ADD &&
1850       N0.getOperand(1).getOperand(1) == N1)
1851     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1852                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1853   // fold ((A-(B-C))-C) -> A-B
1854   if (N0.getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOpcode() == ISD::SUB &&
1856       N0.getOperand(1).getOperand(1) == N1)
1857     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1858                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1859
1860   // If either operand of a sub is undef, the result is undef
1861   if (N0.getOpcode() == ISD::UNDEF)
1862     return N0;
1863   if (N1.getOpcode() == ISD::UNDEF)
1864     return N1;
1865
1866   // If the relocation model supports it, consider symbol offsets.
1867   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1868     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1869       // fold (sub Sym, c) -> Sym-c
1870       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1871         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1872                                     GA->getOffset() -
1873                                       (uint64_t)N1C->getSExtValue());
1874       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1875       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1876         if (GA->getGlobal() == GB->getGlobal())
1877           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1878                                  VT);
1879     }
1880
1881   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1882   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1883     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1884     if (TN->getVT() == MVT::i1) {
1885       SDLoc DL(N);
1886       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1887                                  DAG.getConstant(1, VT));
1888       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1889     }
1890   }
1891
1892   return SDValue();
1893 }
1894
1895 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1896   SDValue N0 = N->getOperand(0);
1897   SDValue N1 = N->getOperand(1);
1898   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1899   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1900   EVT VT = N0.getValueType();
1901
1902   // If the flag result is dead, turn this into an SUB.
1903   if (!N->hasAnyUseOfValue(1))
1904     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1905                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1906                                  MVT::Glue));
1907
1908   // fold (subc x, x) -> 0 + no borrow
1909   if (N0 == N1)
1910     return CombineTo(N, DAG.getConstant(0, VT),
1911                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                  MVT::Glue));
1913
1914   // fold (subc x, 0) -> x + no borrow
1915   if (N1C && N1C->isNullValue())
1916     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1917                                         MVT::Glue));
1918
1919   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1920   if (N0C && N0C->isAllOnesValue())
1921     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1922                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1923                                  MVT::Glue));
1924
1925   return SDValue();
1926 }
1927
1928 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1929   SDValue N0 = N->getOperand(0);
1930   SDValue N1 = N->getOperand(1);
1931   SDValue CarryIn = N->getOperand(2);
1932
1933   // fold (sube x, y, false) -> (subc x, y)
1934   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1935     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1936
1937   return SDValue();
1938 }
1939
1940 SDValue DAGCombiner::visitMUL(SDNode *N) {
1941   SDValue N0 = N->getOperand(0);
1942   SDValue N1 = N->getOperand(1);
1943   EVT VT = N0.getValueType();
1944
1945   // fold (mul x, undef) -> 0
1946   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1947     return DAG.getConstant(0, VT);
1948
1949   bool N0IsConst = false;
1950   bool N1IsConst = false;
1951   APInt ConstValue0, ConstValue1;
1952   // fold vector ops
1953   if (VT.isVector()) {
1954     SDValue FoldedVOp = SimplifyVBinOp(N);
1955     if (FoldedVOp.getNode()) return FoldedVOp;
1956
1957     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1958     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1959   } else {
1960     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1961     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1962                             : APInt();
1963     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1964     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1965                             : APInt();
1966   }
1967
1968   // fold (mul c1, c2) -> c1*c2
1969   if (N0IsConst && N1IsConst)
1970     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1971
1972   // canonicalize constant to RHS
1973   if (N0IsConst && !N1IsConst)
1974     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1975   // fold (mul x, 0) -> 0
1976   if (N1IsConst && ConstValue1 == 0)
1977     return N1;
1978   // We require a splat of the entire scalar bit width for non-contiguous
1979   // bit patterns.
1980   bool IsFullSplat =
1981     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1982   // fold (mul x, 1) -> x
1983   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1984     return N0;
1985   // fold (mul x, -1) -> 0-x
1986   if (N1IsConst && ConstValue1.isAllOnesValue())
1987     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1988                        DAG.getConstant(0, VT), N0);
1989   // fold (mul x, (1 << c)) -> x << c
1990   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1991     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1992                        DAG.getConstant(ConstValue1.logBase2(),
1993                                        getShiftAmountTy(N0.getValueType())));
1994   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1995   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1996     unsigned Log2Val = (-ConstValue1).logBase2();
1997     // FIXME: If the input is something that is easily negated (e.g. a
1998     // single-use add), we should put the negate there.
1999     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2000                        DAG.getConstant(0, VT),
2001                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2002                             DAG.getConstant(Log2Val,
2003                                       getShiftAmountTy(N0.getValueType()))));
2004   }
2005
2006   APInt Val;
2007   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2008   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2009       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2010                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2011     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2012                              N1, N0.getOperand(1));
2013     AddToWorklist(C3.getNode());
2014     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2015                        N0.getOperand(0), C3);
2016   }
2017
2018   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2019   // use.
2020   {
2021     SDValue Sh(nullptr,0), Y(nullptr,0);
2022     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2023     if (N0.getOpcode() == ISD::SHL &&
2024         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2025                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2026         N0.getNode()->hasOneUse()) {
2027       Sh = N0; Y = N1;
2028     } else if (N1.getOpcode() == ISD::SHL &&
2029                isa<ConstantSDNode>(N1.getOperand(1)) &&
2030                N1.getNode()->hasOneUse()) {
2031       Sh = N1; Y = N0;
2032     }
2033
2034     if (Sh.getNode()) {
2035       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2036                                 Sh.getOperand(0), Y);
2037       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2038                          Mul, Sh.getOperand(1));
2039     }
2040   }
2041
2042   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2043   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2044       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2045                      isa<ConstantSDNode>(N0.getOperand(1))))
2046     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2047                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2048                                    N0.getOperand(0), N1),
2049                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2050                                    N0.getOperand(1), N1));
2051
2052   // reassociate mul
2053   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2054   if (RMUL.getNode())
2055     return RMUL;
2056
2057   return SDValue();
2058 }
2059
2060 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2061   SDValue N0 = N->getOperand(0);
2062   SDValue N1 = N->getOperand(1);
2063   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2064   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2065   EVT VT = N->getValueType(0);
2066
2067   // fold vector ops
2068   if (VT.isVector()) {
2069     SDValue FoldedVOp = SimplifyVBinOp(N);
2070     if (FoldedVOp.getNode()) return FoldedVOp;
2071   }
2072
2073   // fold (sdiv c1, c2) -> c1/c2
2074   if (N0C && N1C && !N1C->isNullValue())
2075     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2076   // fold (sdiv X, 1) -> X
2077   if (N1C && N1C->getAPIntValue() == 1LL)
2078     return N0;
2079   // fold (sdiv X, -1) -> 0-X
2080   if (N1C && N1C->isAllOnesValue())
2081     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2082                        DAG.getConstant(0, VT), N0);
2083   // If we know the sign bits of both operands are zero, strength reduce to a
2084   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2085   if (!VT.isVector()) {
2086     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2087       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2088                          N0, N1);
2089   }
2090
2091   // fold (sdiv X, pow2) -> simple ops after legalize
2092   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2093                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2094     // If dividing by powers of two is cheap, then don't perform the following
2095     // fold.
2096     if (TLI.isPow2SDivCheap())
2097       return SDValue();
2098
2099     // Target-specific implementation of sdiv x, pow2.
2100     SDValue Res = BuildSDIVPow2(N);
2101     if (Res.getNode())
2102       return Res;
2103
2104     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2105
2106     // Splat the sign bit into the register
2107     SDValue SGN =
2108         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2109                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2110                                     getShiftAmountTy(N0.getValueType())));
2111     AddToWorklist(SGN.getNode());
2112
2113     // Add (N0 < 0) ? abs2 - 1 : 0;
2114     SDValue SRL =
2115         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2116                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2117                                     getShiftAmountTy(SGN.getValueType())));
2118     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2119     AddToWorklist(SRL.getNode());
2120     AddToWorklist(ADD.getNode());    // Divide by pow2
2121     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2122                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2123
2124     // If we're dividing by a positive value, we're done.  Otherwise, we must
2125     // negate the result.
2126     if (N1C->getAPIntValue().isNonNegative())
2127       return SRA;
2128
2129     AddToWorklist(SRA.getNode());
2130     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2131   }
2132
2133   // if integer divide is expensive and we satisfy the requirements, emit an
2134   // alternate sequence.
2135   if (N1C && !TLI.isIntDivCheap()) {
2136     SDValue Op = BuildSDIV(N);
2137     if (Op.getNode()) return Op;
2138   }
2139
2140   // undef / X -> 0
2141   if (N0.getOpcode() == ISD::UNDEF)
2142     return DAG.getConstant(0, VT);
2143   // X / undef -> undef
2144   if (N1.getOpcode() == ISD::UNDEF)
2145     return N1;
2146
2147   return SDValue();
2148 }
2149
2150 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2151   SDValue N0 = N->getOperand(0);
2152   SDValue N1 = N->getOperand(1);
2153   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2154   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2155   EVT VT = N->getValueType(0);
2156
2157   // fold vector ops
2158   if (VT.isVector()) {
2159     SDValue FoldedVOp = SimplifyVBinOp(N);
2160     if (FoldedVOp.getNode()) return FoldedVOp;
2161   }
2162
2163   // fold (udiv c1, c2) -> c1/c2
2164   if (N0C && N1C && !N1C->isNullValue())
2165     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2166   // fold (udiv x, (1 << c)) -> x >>u c
2167   if (N1C && N1C->getAPIntValue().isPowerOf2())
2168     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2169                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2170                                        getShiftAmountTy(N0.getValueType())));
2171   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2172   if (N1.getOpcode() == ISD::SHL) {
2173     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2174       if (SHC->getAPIntValue().isPowerOf2()) {
2175         EVT ADDVT = N1.getOperand(1).getValueType();
2176         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2177                                   N1.getOperand(1),
2178                                   DAG.getConstant(SHC->getAPIntValue()
2179                                                                   .logBase2(),
2180                                                   ADDVT));
2181         AddToWorklist(Add.getNode());
2182         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2183       }
2184     }
2185   }
2186   // fold (udiv x, c) -> alternate
2187   if (N1C && !TLI.isIntDivCheap()) {
2188     SDValue Op = BuildUDIV(N);
2189     if (Op.getNode()) return Op;
2190   }
2191
2192   // undef / X -> 0
2193   if (N0.getOpcode() == ISD::UNDEF)
2194     return DAG.getConstant(0, VT);
2195   // X / undef -> undef
2196   if (N1.getOpcode() == ISD::UNDEF)
2197     return N1;
2198
2199   return SDValue();
2200 }
2201
2202 SDValue DAGCombiner::visitSREM(SDNode *N) {
2203   SDValue N0 = N->getOperand(0);
2204   SDValue N1 = N->getOperand(1);
2205   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2206   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2207   EVT VT = N->getValueType(0);
2208
2209   // fold (srem c1, c2) -> c1%c2
2210   if (N0C && N1C && !N1C->isNullValue())
2211     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2212   // If we know the sign bits of both operands are zero, strength reduce to a
2213   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2214   if (!VT.isVector()) {
2215     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2216       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2217   }
2218
2219   // If X/C can be simplified by the division-by-constant logic, lower
2220   // X%C to the equivalent of X-X/C*C.
2221   if (N1C && !N1C->isNullValue()) {
2222     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2223     AddToWorklist(Div.getNode());
2224     SDValue OptimizedDiv = combine(Div.getNode());
2225     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2226       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2227                                 OptimizedDiv, N1);
2228       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2229       AddToWorklist(Mul.getNode());
2230       return Sub;
2231     }
2232   }
2233
2234   // undef % X -> 0
2235   if (N0.getOpcode() == ISD::UNDEF)
2236     return DAG.getConstant(0, VT);
2237   // X % undef -> undef
2238   if (N1.getOpcode() == ISD::UNDEF)
2239     return N1;
2240
2241   return SDValue();
2242 }
2243
2244 SDValue DAGCombiner::visitUREM(SDNode *N) {
2245   SDValue N0 = N->getOperand(0);
2246   SDValue N1 = N->getOperand(1);
2247   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2248   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2249   EVT VT = N->getValueType(0);
2250
2251   // fold (urem c1, c2) -> c1%c2
2252   if (N0C && N1C && !N1C->isNullValue())
2253     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2254   // fold (urem x, pow2) -> (and x, pow2-1)
2255   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2256     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2257                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2258   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2259   if (N1.getOpcode() == ISD::SHL) {
2260     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2261       if (SHC->getAPIntValue().isPowerOf2()) {
2262         SDValue Add =
2263           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2264                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2265                                  VT));
2266         AddToWorklist(Add.getNode());
2267         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2268       }
2269     }
2270   }
2271
2272   // If X/C can be simplified by the division-by-constant logic, lower
2273   // X%C to the equivalent of X-X/C*C.
2274   if (N1C && !N1C->isNullValue()) {
2275     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2276     AddToWorklist(Div.getNode());
2277     SDValue OptimizedDiv = combine(Div.getNode());
2278     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2279       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2280                                 OptimizedDiv, N1);
2281       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2282       AddToWorklist(Mul.getNode());
2283       return Sub;
2284     }
2285   }
2286
2287   // undef % X -> 0
2288   if (N0.getOpcode() == ISD::UNDEF)
2289     return DAG.getConstant(0, VT);
2290   // X % undef -> undef
2291   if (N1.getOpcode() == ISD::UNDEF)
2292     return N1;
2293
2294   return SDValue();
2295 }
2296
2297 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2298   SDValue N0 = N->getOperand(0);
2299   SDValue N1 = N->getOperand(1);
2300   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2301   EVT VT = N->getValueType(0);
2302   SDLoc DL(N);
2303
2304   // fold (mulhs x, 0) -> 0
2305   if (N1C && N1C->isNullValue())
2306     return N1;
2307   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2308   if (N1C && N1C->getAPIntValue() == 1)
2309     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2310                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2311                                        getShiftAmountTy(N0.getValueType())));
2312   // fold (mulhs 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 mulhs 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::SIGN_EXTEND, DL, NewVT, N0);
2324       N1 = DAG.getNode(ISD::SIGN_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 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2336   SDValue N0 = N->getOperand(0);
2337   SDValue N1 = N->getOperand(1);
2338   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2339   EVT VT = N->getValueType(0);
2340   SDLoc DL(N);
2341
2342   // fold (mulhu x, 0) -> 0
2343   if (N1C && N1C->isNullValue())
2344     return N1;
2345   // fold (mulhu x, 1) -> 0
2346   if (N1C && N1C->getAPIntValue() == 1)
2347     return DAG.getConstant(0, N0.getValueType());
2348   // fold (mulhu x, undef) -> 0
2349   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2350     return DAG.getConstant(0, VT);
2351
2352   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2353   // plus a shift.
2354   if (VT.isSimple() && !VT.isVector()) {
2355     MVT Simple = VT.getSimpleVT();
2356     unsigned SimpleSize = Simple.getSizeInBits();
2357     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2358     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2359       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2360       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2361       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2362       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2363             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2364       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2365     }
2366   }
2367
2368   return SDValue();
2369 }
2370
2371 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2372 /// give the opcodes for the two computations that are being performed. Return
2373 /// true if a simplification was made.
2374 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2375                                                 unsigned HiOp) {
2376   // If the high half is not needed, just compute the low half.
2377   bool HiExists = N->hasAnyUseOfValue(1);
2378   if (!HiExists &&
2379       (!LegalOperations ||
2380        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2381     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2382     return CombineTo(N, Res, Res);
2383   }
2384
2385   // If the low half is not needed, just compute the high half.
2386   bool LoExists = N->hasAnyUseOfValue(0);
2387   if (!LoExists &&
2388       (!LegalOperations ||
2389        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2390     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2391     return CombineTo(N, Res, Res);
2392   }
2393
2394   // If both halves are used, return as it is.
2395   if (LoExists && HiExists)
2396     return SDValue();
2397
2398   // If the two computed results can be simplified separately, separate them.
2399   if (LoExists) {
2400     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2401     AddToWorklist(Lo.getNode());
2402     SDValue LoOpt = combine(Lo.getNode());
2403     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2404         (!LegalOperations ||
2405          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2406       return CombineTo(N, LoOpt, LoOpt);
2407   }
2408
2409   if (HiExists) {
2410     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2411     AddToWorklist(Hi.getNode());
2412     SDValue HiOpt = combine(Hi.getNode());
2413     if (HiOpt.getNode() && HiOpt != Hi &&
2414         (!LegalOperations ||
2415          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2416       return CombineTo(N, HiOpt, HiOpt);
2417   }
2418
2419   return SDValue();
2420 }
2421
2422 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2423   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2424   if (Res.getNode()) return Res;
2425
2426   EVT VT = N->getValueType(0);
2427   SDLoc DL(N);
2428
2429   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2430   // plus a shift.
2431   if (VT.isSimple() && !VT.isVector()) {
2432     MVT Simple = VT.getSimpleVT();
2433     unsigned SimpleSize = Simple.getSizeInBits();
2434     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2435     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2436       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2437       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2438       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2439       // Compute the high part as N1.
2440       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2441             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2442       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2443       // Compute the low part as N0.
2444       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2445       return CombineTo(N, Lo, Hi);
2446     }
2447   }
2448
2449   return SDValue();
2450 }
2451
2452 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2453   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2454   if (Res.getNode()) return Res;
2455
2456   EVT VT = N->getValueType(0);
2457   SDLoc DL(N);
2458
2459   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2460   // plus a shift.
2461   if (VT.isSimple() && !VT.isVector()) {
2462     MVT Simple = VT.getSimpleVT();
2463     unsigned SimpleSize = Simple.getSizeInBits();
2464     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2465     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2466       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2467       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2468       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2469       // Compute the high part as N1.
2470       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2471             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2472       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2473       // Compute the low part as N0.
2474       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2475       return CombineTo(N, Lo, Hi);
2476     }
2477   }
2478
2479   return SDValue();
2480 }
2481
2482 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2483   // (smulo x, 2) -> (saddo x, x)
2484   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2485     if (C2->getAPIntValue() == 2)
2486       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2487                          N->getOperand(0), N->getOperand(0));
2488
2489   return SDValue();
2490 }
2491
2492 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2493   // (umulo x, 2) -> (uaddo x, x)
2494   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2495     if (C2->getAPIntValue() == 2)
2496       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2497                          N->getOperand(0), N->getOperand(0));
2498
2499   return SDValue();
2500 }
2501
2502 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2503   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2504   if (Res.getNode()) return Res;
2505
2506   return SDValue();
2507 }
2508
2509 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2510   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2511   if (Res.getNode()) return Res;
2512
2513   return SDValue();
2514 }
2515
2516 /// If this is a binary operator with two operands of the same opcode, try to
2517 /// simplify it.
2518 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2519   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2520   EVT VT = N0.getValueType();
2521   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2522
2523   // Bail early if none of these transforms apply.
2524   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2525
2526   // For each of OP in AND/OR/XOR:
2527   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2528   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2529   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2530   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2531   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2532   //
2533   // do not sink logical op inside of a vector extend, since it may combine
2534   // into a vsetcc.
2535   EVT Op0VT = N0.getOperand(0).getValueType();
2536   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2537        N0.getOpcode() == ISD::SIGN_EXTEND ||
2538        N0.getOpcode() == ISD::BSWAP ||
2539        // Avoid infinite looping with PromoteIntBinOp.
2540        (N0.getOpcode() == ISD::ANY_EXTEND &&
2541         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2542        (N0.getOpcode() == ISD::TRUNCATE &&
2543         (!TLI.isZExtFree(VT, Op0VT) ||
2544          !TLI.isTruncateFree(Op0VT, VT)) &&
2545         TLI.isTypeLegal(Op0VT))) &&
2546       !VT.isVector() &&
2547       Op0VT == N1.getOperand(0).getValueType() &&
2548       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2549     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2550                                  N0.getOperand(0).getValueType(),
2551                                  N0.getOperand(0), N1.getOperand(0));
2552     AddToWorklist(ORNode.getNode());
2553     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2554   }
2555
2556   // For each of OP in SHL/SRL/SRA/AND...
2557   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2558   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2559   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2560   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2561        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2562       N0.getOperand(1) == N1.getOperand(1)) {
2563     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2564                                  N0.getOperand(0).getValueType(),
2565                                  N0.getOperand(0), N1.getOperand(0));
2566     AddToWorklist(ORNode.getNode());
2567     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2568                        ORNode, N0.getOperand(1));
2569   }
2570
2571   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2572   // Only perform this optimization after type legalization and before
2573   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2574   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2575   // we don't want to undo this promotion.
2576   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2577   // on scalars.
2578   if ((N0.getOpcode() == ISD::BITCAST ||
2579        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2580       Level == AfterLegalizeTypes) {
2581     SDValue In0 = N0.getOperand(0);
2582     SDValue In1 = N1.getOperand(0);
2583     EVT In0Ty = In0.getValueType();
2584     EVT In1Ty = In1.getValueType();
2585     SDLoc DL(N);
2586     // If both incoming values are integers, and the original types are the
2587     // same.
2588     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2589       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2590       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2591       AddToWorklist(Op.getNode());
2592       return BC;
2593     }
2594   }
2595
2596   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2597   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2598   // If both shuffles use the same mask, and both shuffle within a single
2599   // vector, then it is worthwhile to move the swizzle after the operation.
2600   // The type-legalizer generates this pattern when loading illegal
2601   // vector types from memory. In many cases this allows additional shuffle
2602   // optimizations.
2603   // There are other cases where moving the shuffle after the xor/and/or
2604   // is profitable even if shuffles don't perform a swizzle.
2605   // If both shuffles use the same mask, and both shuffles have the same first
2606   // or second operand, then it might still be profitable to move the shuffle
2607   // after the xor/and/or operation.
2608   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2609     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2610     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2611
2612     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2613            "Inputs to shuffles are not the same type");
2614
2615     // Check that both shuffles use the same mask. The masks are known to be of
2616     // the same length because the result vector type is the same.
2617     // Check also that shuffles have only one use to avoid introducing extra
2618     // instructions.
2619     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2620         SVN0->getMask().equals(SVN1->getMask())) {
2621       SDValue ShOp = N0->getOperand(1);
2622
2623       // Don't try to fold this node if it requires introducing a
2624       // build vector of all zeros that might be illegal at this stage.
2625       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2626         if (!LegalTypes)
2627           ShOp = DAG.getConstant(0, VT);
2628         else
2629           ShOp = SDValue();
2630       }
2631
2632       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2633       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2634       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2635       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2636         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2637                                       N0->getOperand(0), N1->getOperand(0));
2638         AddToWorklist(NewNode.getNode());
2639         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2640                                     &SVN0->getMask()[0]);
2641       }
2642
2643       // Don't try to fold this node if it requires introducing a
2644       // build vector of all zeros that might be illegal at this stage.
2645       ShOp = N0->getOperand(0);
2646       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2647         if (!LegalTypes)
2648           ShOp = DAG.getConstant(0, VT);
2649         else
2650           ShOp = SDValue();
2651       }
2652
2653       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2654       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2655       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2656       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2657         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2658                                       N0->getOperand(1), N1->getOperand(1));
2659         AddToWorklist(NewNode.getNode());
2660         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2661                                     &SVN0->getMask()[0]);
2662       }
2663     }
2664   }
2665
2666   return SDValue();
2667 }
2668
2669 SDValue DAGCombiner::visitAND(SDNode *N) {
2670   SDValue N0 = N->getOperand(0);
2671   SDValue N1 = N->getOperand(1);
2672   SDValue LL, LR, RL, RR, CC0, CC1;
2673   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2674   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2675   EVT VT = N1.getValueType();
2676   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2677
2678   // fold vector ops
2679   if (VT.isVector()) {
2680     SDValue FoldedVOp = SimplifyVBinOp(N);
2681     if (FoldedVOp.getNode()) return FoldedVOp;
2682
2683     // fold (and x, 0) -> 0, vector edition
2684     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2685       // do not return N0, because undef node may exist in N0
2686       return DAG.getConstant(
2687           APInt::getNullValue(
2688               N0.getValueType().getScalarType().getSizeInBits()),
2689           N0.getValueType());
2690     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2691       // do not return N1, because undef node may exist in N1
2692       return DAG.getConstant(
2693           APInt::getNullValue(
2694               N1.getValueType().getScalarType().getSizeInBits()),
2695           N1.getValueType());
2696
2697     // fold (and x, -1) -> x, vector edition
2698     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2699       return N1;
2700     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2701       return N0;
2702   }
2703
2704   // fold (and x, undef) -> 0
2705   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2706     return DAG.getConstant(0, VT);
2707   // fold (and c1, c2) -> c1&c2
2708   if (N0C && N1C)
2709     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2710   // canonicalize constant to RHS
2711   if (N0C && !N1C)
2712     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2713   // fold (and x, -1) -> x
2714   if (N1C && N1C->isAllOnesValue())
2715     return N0;
2716   // if (and x, c) is known to be zero, return 0
2717   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2718                                    APInt::getAllOnesValue(BitWidth)))
2719     return DAG.getConstant(0, VT);
2720   // reassociate and
2721   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2722   if (RAND.getNode())
2723     return RAND;
2724   // fold (and (or x, C), D) -> D if (C & D) == D
2725   if (N1C && N0.getOpcode() == ISD::OR)
2726     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2727       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2728         return N1;
2729   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2730   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2731     SDValue N0Op0 = N0.getOperand(0);
2732     APInt Mask = ~N1C->getAPIntValue();
2733     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2734     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2735       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2736                                  N0.getValueType(), N0Op0);
2737
2738       // Replace uses of the AND with uses of the Zero extend node.
2739       CombineTo(N, Zext);
2740
2741       // We actually want to replace all uses of the any_extend with the
2742       // zero_extend, to avoid duplicating things.  This will later cause this
2743       // AND to be folded.
2744       CombineTo(N0.getNode(), Zext);
2745       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2746     }
2747   }
2748   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2749   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2750   // already be zero by virtue of the width of the base type of the load.
2751   //
2752   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2753   // more cases.
2754   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2755        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2756       N0.getOpcode() == ISD::LOAD) {
2757     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2758                                          N0 : N0.getOperand(0) );
2759
2760     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2761     // This can be a pure constant or a vector splat, in which case we treat the
2762     // vector as a scalar and use the splat value.
2763     APInt Constant = APInt::getNullValue(1);
2764     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2765       Constant = C->getAPIntValue();
2766     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2767       APInt SplatValue, SplatUndef;
2768       unsigned SplatBitSize;
2769       bool HasAnyUndefs;
2770       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2771                                              SplatBitSize, HasAnyUndefs);
2772       if (IsSplat) {
2773         // Undef bits can contribute to a possible optimisation if set, so
2774         // set them.
2775         SplatValue |= SplatUndef;
2776
2777         // The splat value may be something like "0x00FFFFFF", which means 0 for
2778         // the first vector value and FF for the rest, repeating. We need a mask
2779         // that will apply equally to all members of the vector, so AND all the
2780         // lanes of the constant together.
2781         EVT VT = Vector->getValueType(0);
2782         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2783
2784         // If the splat value has been compressed to a bitlength lower
2785         // than the size of the vector lane, we need to re-expand it to
2786         // the lane size.
2787         if (BitWidth > SplatBitSize)
2788           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2789                SplatBitSize < BitWidth;
2790                SplatBitSize = SplatBitSize * 2)
2791             SplatValue |= SplatValue.shl(SplatBitSize);
2792
2793         Constant = APInt::getAllOnesValue(BitWidth);
2794         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2795           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2796       }
2797     }
2798
2799     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2800     // actually legal and isn't going to get expanded, else this is a false
2801     // optimisation.
2802     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2803                                                     Load->getValueType(0),
2804                                                     Load->getMemoryVT());
2805
2806     // Resize the constant to the same size as the original memory access before
2807     // extension. If it is still the AllOnesValue then this AND is completely
2808     // unneeded.
2809     Constant =
2810       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2811
2812     bool B;
2813     switch (Load->getExtensionType()) {
2814     default: B = false; break;
2815     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2816     case ISD::ZEXTLOAD:
2817     case ISD::NON_EXTLOAD: B = true; break;
2818     }
2819
2820     if (B && Constant.isAllOnesValue()) {
2821       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2822       // preserve semantics once we get rid of the AND.
2823       SDValue NewLoad(Load, 0);
2824       if (Load->getExtensionType() == ISD::EXTLOAD) {
2825         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2826                               Load->getValueType(0), SDLoc(Load),
2827                               Load->getChain(), Load->getBasePtr(),
2828                               Load->getOffset(), Load->getMemoryVT(),
2829                               Load->getMemOperand());
2830         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2831         if (Load->getNumValues() == 3) {
2832           // PRE/POST_INC loads have 3 values.
2833           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2834                            NewLoad.getValue(2) };
2835           CombineTo(Load, To, 3, true);
2836         } else {
2837           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2838         }
2839       }
2840
2841       // Fold the AND away, taking care not to fold to the old load node if we
2842       // replaced it.
2843       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2844
2845       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2846     }
2847   }
2848   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2849   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2850     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2851     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2852
2853     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2854         LL.getValueType().isInteger()) {
2855       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2856       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2857         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2858                                      LR.getValueType(), LL, RL);
2859         AddToWorklist(ORNode.getNode());
2860         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2861       }
2862       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2863       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2864         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2865                                       LR.getValueType(), LL, RL);
2866         AddToWorklist(ANDNode.getNode());
2867         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2868       }
2869       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2870       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2871         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2872                                      LR.getValueType(), LL, RL);
2873         AddToWorklist(ORNode.getNode());
2874         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2875       }
2876     }
2877     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2878     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2879         Op0 == Op1 && LL.getValueType().isInteger() &&
2880       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2881                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2882                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2883                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2884       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2885                                     LL, DAG.getConstant(1, LL.getValueType()));
2886       AddToWorklist(ADDNode.getNode());
2887       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2888                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2889     }
2890     // canonicalize equivalent to ll == rl
2891     if (LL == RR && LR == RL) {
2892       Op1 = ISD::getSetCCSwappedOperands(Op1);
2893       std::swap(RL, RR);
2894     }
2895     if (LL == RL && LR == RR) {
2896       bool isInteger = LL.getValueType().isInteger();
2897       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2898       if (Result != ISD::SETCC_INVALID &&
2899           (!LegalOperations ||
2900            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2901             TLI.isOperationLegal(ISD::SETCC,
2902                             getSetCCResultType(N0.getSimpleValueType())))))
2903         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2904                             LL, LR, Result);
2905     }
2906   }
2907
2908   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2909   if (N0.getOpcode() == N1.getOpcode()) {
2910     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2911     if (Tmp.getNode()) return Tmp;
2912   }
2913
2914   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2915   // fold (and (sra)) -> (and (srl)) when possible.
2916   if (!VT.isVector() &&
2917       SimplifyDemandedBits(SDValue(N, 0)))
2918     return SDValue(N, 0);
2919
2920   // fold (zext_inreg (extload x)) -> (zextload x)
2921   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2922     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2923     EVT MemVT = LN0->getMemoryVT();
2924     // If we zero all the possible extended bits, then we can turn this into
2925     // a zextload if we are running before legalize or the operation is legal.
2926     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2927     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2928                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2929         ((!LegalOperations && !LN0->isVolatile()) ||
2930          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2931       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2932                                        LN0->getChain(), LN0->getBasePtr(),
2933                                        MemVT, LN0->getMemOperand());
2934       AddToWorklist(N);
2935       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2936       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2937     }
2938   }
2939   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2940   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2941       N0.hasOneUse()) {
2942     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2943     EVT MemVT = LN0->getMemoryVT();
2944     // If we zero all the possible extended bits, then we can turn this into
2945     // a zextload if we are running before legalize or the operation is legal.
2946     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2947     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2948                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2949         ((!LegalOperations && !LN0->isVolatile()) ||
2950          TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
2951       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2952                                        LN0->getChain(), LN0->getBasePtr(),
2953                                        MemVT, LN0->getMemOperand());
2954       AddToWorklist(N);
2955       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2956       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2957     }
2958   }
2959
2960   // fold (and (load x), 255) -> (zextload x, i8)
2961   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2962   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2963   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2964               (N0.getOpcode() == ISD::ANY_EXTEND &&
2965                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2966     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2967     LoadSDNode *LN0 = HasAnyExt
2968       ? cast<LoadSDNode>(N0.getOperand(0))
2969       : cast<LoadSDNode>(N0);
2970     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2971         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2972       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2973       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2974         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2975         EVT LoadedVT = LN0->getMemoryVT();
2976         EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2977
2978         if (ExtVT == LoadedVT &&
2979             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2980                                                     ExtVT))) {
2981
2982           SDValue NewLoad =
2983             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2984                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2985                            LN0->getMemOperand());
2986           AddToWorklist(N);
2987           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2988           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2989         }
2990
2991         // Do not change the width of a volatile load.
2992         // Do not generate loads of non-round integer types since these can
2993         // be expensive (and would be wrong if the type is not byte sized).
2994         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2995             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy,
2996                                                     ExtVT))) {
2997           EVT PtrType = LN0->getOperand(1).getValueType();
2998
2999           unsigned Alignment = LN0->getAlignment();
3000           SDValue NewPtr = LN0->getBasePtr();
3001
3002           // For big endian targets, we need to add an offset to the pointer
3003           // to load the correct bytes.  For little endian systems, we merely
3004           // need to read fewer bytes from the same pointer.
3005           if (TLI.isBigEndian()) {
3006             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3007             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3008             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3009             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3010                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3011             Alignment = MinAlign(Alignment, PtrOff);
3012           }
3013
3014           AddToWorklist(NewPtr.getNode());
3015
3016           SDValue Load =
3017             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3018                            LN0->getChain(), NewPtr,
3019                            LN0->getPointerInfo(),
3020                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3021                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3022           AddToWorklist(N);
3023           CombineTo(LN0, Load, Load.getValue(1));
3024           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3025         }
3026       }
3027     }
3028   }
3029
3030   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3031       VT.getSizeInBits() <= 64) {
3032     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3033       APInt ADDC = ADDI->getAPIntValue();
3034       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3035         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3036         // immediate for an add, but it is legal if its top c2 bits are set,
3037         // transform the ADD so the immediate doesn't need to be materialized
3038         // in a register.
3039         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3040           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3041                                              SRLI->getZExtValue());
3042           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3043             ADDC |= Mask;
3044             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3045               SDValue NewAdd =
3046                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3047                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3048               CombineTo(N0.getNode(), NewAdd);
3049               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3050             }
3051           }
3052         }
3053       }
3054     }
3055   }
3056
3057   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3058   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3059     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3060                                        N0.getOperand(1), false);
3061     if (BSwap.getNode())
3062       return BSwap;
3063   }
3064
3065   return SDValue();
3066 }
3067
3068 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3069 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3070                                         bool DemandHighBits) {
3071   if (!LegalOperations)
3072     return SDValue();
3073
3074   EVT VT = N->getValueType(0);
3075   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3076     return SDValue();
3077   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3078     return SDValue();
3079
3080   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3081   bool LookPassAnd0 = false;
3082   bool LookPassAnd1 = false;
3083   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3084       std::swap(N0, N1);
3085   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3086       std::swap(N0, N1);
3087   if (N0.getOpcode() == ISD::AND) {
3088     if (!N0.getNode()->hasOneUse())
3089       return SDValue();
3090     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3091     if (!N01C || N01C->getZExtValue() != 0xFF00)
3092       return SDValue();
3093     N0 = N0.getOperand(0);
3094     LookPassAnd0 = true;
3095   }
3096
3097   if (N1.getOpcode() == ISD::AND) {
3098     if (!N1.getNode()->hasOneUse())
3099       return SDValue();
3100     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3101     if (!N11C || N11C->getZExtValue() != 0xFF)
3102       return SDValue();
3103     N1 = N1.getOperand(0);
3104     LookPassAnd1 = true;
3105   }
3106
3107   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3108     std::swap(N0, N1);
3109   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3110     return SDValue();
3111   if (!N0.getNode()->hasOneUse() ||
3112       !N1.getNode()->hasOneUse())
3113     return SDValue();
3114
3115   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3116   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3117   if (!N01C || !N11C)
3118     return SDValue();
3119   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3120     return SDValue();
3121
3122   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3123   SDValue N00 = N0->getOperand(0);
3124   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3125     if (!N00.getNode()->hasOneUse())
3126       return SDValue();
3127     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3128     if (!N001C || N001C->getZExtValue() != 0xFF)
3129       return SDValue();
3130     N00 = N00.getOperand(0);
3131     LookPassAnd0 = true;
3132   }
3133
3134   SDValue N10 = N1->getOperand(0);
3135   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3136     if (!N10.getNode()->hasOneUse())
3137       return SDValue();
3138     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3139     if (!N101C || N101C->getZExtValue() != 0xFF00)
3140       return SDValue();
3141     N10 = N10.getOperand(0);
3142     LookPassAnd1 = true;
3143   }
3144
3145   if (N00 != N10)
3146     return SDValue();
3147
3148   // Make sure everything beyond the low halfword gets set to zero since the SRL
3149   // 16 will clear the top bits.
3150   unsigned OpSizeInBits = VT.getSizeInBits();
3151   if (DemandHighBits && OpSizeInBits > 16) {
3152     // If the left-shift isn't masked out then the only way this is a bswap is
3153     // if all bits beyond the low 8 are 0. In that case the entire pattern
3154     // reduces to a left shift anyway: leave it for other parts of the combiner.
3155     if (!LookPassAnd0)
3156       return SDValue();
3157
3158     // However, if the right shift isn't masked out then it might be because
3159     // it's not needed. See if we can spot that too.
3160     if (!LookPassAnd1 &&
3161         !DAG.MaskedValueIsZero(
3162             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3163       return SDValue();
3164   }
3165
3166   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3167   if (OpSizeInBits > 16)
3168     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3169                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3170   return Res;
3171 }
3172
3173 /// Return true if the specified node is an element that makes up a 32-bit
3174 /// packed halfword byteswap.
3175 /// ((x & 0x000000ff) << 8) |
3176 /// ((x & 0x0000ff00) >> 8) |
3177 /// ((x & 0x00ff0000) << 8) |
3178 /// ((x & 0xff000000) >> 8)
3179 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3180   if (!N.getNode()->hasOneUse())
3181     return false;
3182
3183   unsigned Opc = N.getOpcode();
3184   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3185     return false;
3186
3187   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3188   if (!N1C)
3189     return false;
3190
3191   unsigned Num;
3192   switch (N1C->getZExtValue()) {
3193   default:
3194     return false;
3195   case 0xFF:       Num = 0; break;
3196   case 0xFF00:     Num = 1; break;
3197   case 0xFF0000:   Num = 2; break;
3198   case 0xFF000000: Num = 3; break;
3199   }
3200
3201   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3202   SDValue N0 = N.getOperand(0);
3203   if (Opc == ISD::AND) {
3204     if (Num == 0 || Num == 2) {
3205       // (x >> 8) & 0xff
3206       // (x >> 8) & 0xff0000
3207       if (N0.getOpcode() != ISD::SRL)
3208         return false;
3209       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3210       if (!C || C->getZExtValue() != 8)
3211         return false;
3212     } else {
3213       // (x << 8) & 0xff00
3214       // (x << 8) & 0xff000000
3215       if (N0.getOpcode() != ISD::SHL)
3216         return false;
3217       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3218       if (!C || C->getZExtValue() != 8)
3219         return false;
3220     }
3221   } else if (Opc == ISD::SHL) {
3222     // (x & 0xff) << 8
3223     // (x & 0xff0000) << 8
3224     if (Num != 0 && Num != 2)
3225       return false;
3226     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3227     if (!C || C->getZExtValue() != 8)
3228       return false;
3229   } else { // Opc == ISD::SRL
3230     // (x & 0xff00) >> 8
3231     // (x & 0xff000000) >> 8
3232     if (Num != 1 && Num != 3)
3233       return false;
3234     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3235     if (!C || C->getZExtValue() != 8)
3236       return false;
3237   }
3238
3239   if (Parts[Num])
3240     return false;
3241
3242   Parts[Num] = N0.getOperand(0).getNode();
3243   return true;
3244 }
3245
3246 /// Match a 32-bit packed halfword bswap. That is
3247 /// ((x & 0x000000ff) << 8) |
3248 /// ((x & 0x0000ff00) >> 8) |
3249 /// ((x & 0x00ff0000) << 8) |
3250 /// ((x & 0xff000000) >> 8)
3251 /// => (rotl (bswap x), 16)
3252 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3253   if (!LegalOperations)
3254     return SDValue();
3255
3256   EVT VT = N->getValueType(0);
3257   if (VT != MVT::i32)
3258     return SDValue();
3259   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3260     return SDValue();
3261
3262   // Look for either
3263   // (or (or (and), (and)), (or (and), (and)))
3264   // (or (or (or (and), (and)), (and)), (and))
3265   if (N0.getOpcode() != ISD::OR)
3266     return SDValue();
3267   SDValue N00 = N0.getOperand(0);
3268   SDValue N01 = N0.getOperand(1);
3269   SDNode *Parts[4] = {};
3270
3271   if (N1.getOpcode() == ISD::OR &&
3272       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3273     // (or (or (and), (and)), (or (and), (and)))
3274     SDValue N000 = N00.getOperand(0);
3275     if (!isBSwapHWordElement(N000, Parts))
3276       return SDValue();
3277
3278     SDValue N001 = N00.getOperand(1);
3279     if (!isBSwapHWordElement(N001, Parts))
3280       return SDValue();
3281     SDValue N010 = N01.getOperand(0);
3282     if (!isBSwapHWordElement(N010, Parts))
3283       return SDValue();
3284     SDValue N011 = N01.getOperand(1);
3285     if (!isBSwapHWordElement(N011, Parts))
3286       return SDValue();
3287   } else {
3288     // (or (or (or (and), (and)), (and)), (and))
3289     if (!isBSwapHWordElement(N1, Parts))
3290       return SDValue();
3291     if (!isBSwapHWordElement(N01, Parts))
3292       return SDValue();
3293     if (N00.getOpcode() != ISD::OR)
3294       return SDValue();
3295     SDValue N000 = N00.getOperand(0);
3296     if (!isBSwapHWordElement(N000, Parts))
3297       return SDValue();
3298     SDValue N001 = N00.getOperand(1);
3299     if (!isBSwapHWordElement(N001, Parts))
3300       return SDValue();
3301   }
3302
3303   // Make sure the parts are all coming from the same node.
3304   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3305     return SDValue();
3306
3307   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3308                               SDValue(Parts[0],0));
3309
3310   // Result of the bswap should be rotated by 16. If it's not legal, then
3311   // do  (x << 16) | (x >> 16).
3312   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3313   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3314     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3315   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3316     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3317   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3318                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3319                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3320 }
3321
3322 SDValue DAGCombiner::visitOR(SDNode *N) {
3323   SDValue N0 = N->getOperand(0);
3324   SDValue N1 = N->getOperand(1);
3325   SDValue LL, LR, RL, RR, CC0, CC1;
3326   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3327   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3328   EVT VT = N1.getValueType();
3329
3330   // fold vector ops
3331   if (VT.isVector()) {
3332     SDValue FoldedVOp = SimplifyVBinOp(N);
3333     if (FoldedVOp.getNode()) return FoldedVOp;
3334
3335     // fold (or x, 0) -> x, vector edition
3336     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3337       return N1;
3338     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3339       return N0;
3340
3341     // fold (or x, -1) -> -1, vector edition
3342     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3343       // do not return N0, because undef node may exist in N0
3344       return DAG.getConstant(
3345           APInt::getAllOnesValue(
3346               N0.getValueType().getScalarType().getSizeInBits()),
3347           N0.getValueType());
3348     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3349       // do not return N1, because undef node may exist in N1
3350       return DAG.getConstant(
3351           APInt::getAllOnesValue(
3352               N1.getValueType().getScalarType().getSizeInBits()),
3353           N1.getValueType());
3354
3355     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3356     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3357     // Do this only if the resulting shuffle is legal.
3358     if (isa<ShuffleVectorSDNode>(N0) &&
3359         isa<ShuffleVectorSDNode>(N1) &&
3360         // Avoid folding a node with illegal type.
3361         TLI.isTypeLegal(VT) &&
3362         N0->getOperand(1) == N1->getOperand(1) &&
3363         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3364       bool CanFold = true;
3365       unsigned NumElts = VT.getVectorNumElements();
3366       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3367       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3368       // We construct two shuffle masks:
3369       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3370       // and N1 as the second operand.
3371       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3372       // and N0 as the second operand.
3373       // We do this because OR is commutable and therefore there might be
3374       // two ways to fold this node into a shuffle.
3375       SmallVector<int,4> Mask1;
3376       SmallVector<int,4> Mask2;
3377
3378       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3379         int M0 = SV0->getMaskElt(i);
3380         int M1 = SV1->getMaskElt(i);
3381
3382         // Both shuffle indexes are undef. Propagate Undef.
3383         if (M0 < 0 && M1 < 0) {
3384           Mask1.push_back(M0);
3385           Mask2.push_back(M0);
3386           continue;
3387         }
3388
3389         if (M0 < 0 || M1 < 0 ||
3390             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3391             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3392           CanFold = false;
3393           break;
3394         }
3395
3396         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3397         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3398       }
3399
3400       if (CanFold) {
3401         // Fold this sequence only if the resulting shuffle is 'legal'.
3402         if (TLI.isShuffleMaskLegal(Mask1, VT))
3403           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3404                                       N1->getOperand(0), &Mask1[0]);
3405         if (TLI.isShuffleMaskLegal(Mask2, VT))
3406           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3407                                       N0->getOperand(0), &Mask2[0]);
3408       }
3409     }
3410   }
3411
3412   // fold (or x, undef) -> -1
3413   if (!LegalOperations &&
3414       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3415     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3416     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3417   }
3418   // fold (or c1, c2) -> c1|c2
3419   if (N0C && N1C)
3420     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3421   // canonicalize constant to RHS
3422   if (N0C && !N1C)
3423     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3424   // fold (or x, 0) -> x
3425   if (N1C && N1C->isNullValue())
3426     return N0;
3427   // fold (or x, -1) -> -1
3428   if (N1C && N1C->isAllOnesValue())
3429     return N1;
3430   // fold (or x, c) -> c iff (x & ~c) == 0
3431   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3432     return N1;
3433
3434   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3435   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3436   if (BSwap.getNode())
3437     return BSwap;
3438   BSwap = MatchBSwapHWordLow(N, N0, N1);
3439   if (BSwap.getNode())
3440     return BSwap;
3441
3442   // reassociate or
3443   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3444   if (ROR.getNode())
3445     return ROR;
3446   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3447   // iff (c1 & c2) == 0.
3448   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3449              isa<ConstantSDNode>(N0.getOperand(1))) {
3450     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3451     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3452       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3453       if (!COR.getNode())
3454         return SDValue();
3455       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3456                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3457                                      N0.getOperand(0), N1), COR);
3458     }
3459   }
3460   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3461   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3462     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3463     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3464
3465     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3466         LL.getValueType().isInteger()) {
3467       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3468       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3469       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3470           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3471         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3472                                      LR.getValueType(), LL, RL);
3473         AddToWorklist(ORNode.getNode());
3474         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3475       }
3476       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3477       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3478       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3479           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3480         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3481                                       LR.getValueType(), LL, RL);
3482         AddToWorklist(ANDNode.getNode());
3483         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3484       }
3485     }
3486     // canonicalize equivalent to ll == rl
3487     if (LL == RR && LR == RL) {
3488       Op1 = ISD::getSetCCSwappedOperands(Op1);
3489       std::swap(RL, RR);
3490     }
3491     if (LL == RL && LR == RR) {
3492       bool isInteger = LL.getValueType().isInteger();
3493       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3494       if (Result != ISD::SETCC_INVALID &&
3495           (!LegalOperations ||
3496            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3497             TLI.isOperationLegal(ISD::SETCC,
3498               getSetCCResultType(N0.getValueType())))))
3499         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3500                             LL, LR, Result);
3501     }
3502   }
3503
3504   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3505   if (N0.getOpcode() == N1.getOpcode()) {
3506     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3507     if (Tmp.getNode()) return Tmp;
3508   }
3509
3510   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3511   if (N0.getOpcode() == ISD::AND &&
3512       N1.getOpcode() == ISD::AND &&
3513       N0.getOperand(1).getOpcode() == ISD::Constant &&
3514       N1.getOperand(1).getOpcode() == ISD::Constant &&
3515       // Don't increase # computations.
3516       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3517     // We can only do this xform if we know that bits from X that are set in C2
3518     // but not in C1 are already zero.  Likewise for Y.
3519     const APInt &LHSMask =
3520       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3521     const APInt &RHSMask =
3522       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3523
3524     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3525         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3526       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3527                               N0.getOperand(0), N1.getOperand(0));
3528       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3529                          DAG.getConstant(LHSMask | RHSMask, VT));
3530     }
3531   }
3532
3533   // See if this is some rotate idiom.
3534   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3535     return SDValue(Rot, 0);
3536
3537   // Simplify the operands using demanded-bits information.
3538   if (!VT.isVector() &&
3539       SimplifyDemandedBits(SDValue(N, 0)))
3540     return SDValue(N, 0);
3541
3542   return SDValue();
3543 }
3544
3545 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3546 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3547   if (Op.getOpcode() == ISD::AND) {
3548     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3549       Mask = Op.getOperand(1);
3550       Op = Op.getOperand(0);
3551     } else {
3552       return false;
3553     }
3554   }
3555
3556   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3557     Shift = Op;
3558     return true;
3559   }
3560
3561   return false;
3562 }
3563
3564 // Return true if we can prove that, whenever Neg and Pos are both in the
3565 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3566 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3567 //
3568 //     (or (shift1 X, Neg), (shift2 X, Pos))
3569 //
3570 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3571 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3572 // to consider shift amounts with defined behavior.
3573 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3574   // If OpSize is a power of 2 then:
3575   //
3576   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3577   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3578   //
3579   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3580   // for the stronger condition:
3581   //
3582   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3583   //
3584   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3585   // we can just replace Neg with Neg' for the rest of the function.
3586   //
3587   // In other cases we check for the even stronger condition:
3588   //
3589   //     Neg == OpSize - Pos                                    [B]
3590   //
3591   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3592   // behavior if Pos == 0 (and consequently Neg == OpSize).
3593   //
3594   // We could actually use [A] whenever OpSize is a power of 2, but the
3595   // only extra cases that it would match are those uninteresting ones
3596   // where Neg and Pos are never in range at the same time.  E.g. for
3597   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3598   // as well as (sub 32, Pos), but:
3599   //
3600   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3601   //
3602   // always invokes undefined behavior for 32-bit X.
3603   //
3604   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3605   unsigned MaskLoBits = 0;
3606   if (Neg.getOpcode() == ISD::AND &&
3607       isPowerOf2_64(OpSize) &&
3608       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3609       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3610     Neg = Neg.getOperand(0);
3611     MaskLoBits = Log2_64(OpSize);
3612   }
3613
3614   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3615   if (Neg.getOpcode() != ISD::SUB)
3616     return 0;
3617   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3618   if (!NegC)
3619     return 0;
3620   SDValue NegOp1 = Neg.getOperand(1);
3621
3622   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3623   // Pos'.  The truncation is redundant for the purpose of the equality.
3624   if (MaskLoBits &&
3625       Pos.getOpcode() == ISD::AND &&
3626       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3627       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3628     Pos = Pos.getOperand(0);
3629
3630   // The condition we need is now:
3631   //
3632   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3633   //
3634   // If NegOp1 == Pos then we need:
3635   //
3636   //              OpSize & Mask == NegC & Mask
3637   //
3638   // (because "x & Mask" is a truncation and distributes through subtraction).
3639   APInt Width;
3640   if (Pos == NegOp1)
3641     Width = NegC->getAPIntValue();
3642   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3643   // Then the condition we want to prove becomes:
3644   //
3645   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3646   //
3647   // which, again because "x & Mask" is a truncation, becomes:
3648   //
3649   //                NegC & Mask == (OpSize - PosC) & Mask
3650   //              OpSize & Mask == (NegC + PosC) & Mask
3651   else if (Pos.getOpcode() == ISD::ADD &&
3652            Pos.getOperand(0) == NegOp1 &&
3653            Pos.getOperand(1).getOpcode() == ISD::Constant)
3654     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3655              NegC->getAPIntValue());
3656   else
3657     return false;
3658
3659   // Now we just need to check that OpSize & Mask == Width & Mask.
3660   if (MaskLoBits)
3661     // Opsize & Mask is 0 since Mask is Opsize - 1.
3662     return Width.getLoBits(MaskLoBits) == 0;
3663   return Width == OpSize;
3664 }
3665
3666 // A subroutine of MatchRotate used once we have found an OR of two opposite
3667 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3668 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3669 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3670 // Neg with outer conversions stripped away.
3671 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3672                                        SDValue Neg, SDValue InnerPos,
3673                                        SDValue InnerNeg, unsigned PosOpcode,
3674                                        unsigned NegOpcode, SDLoc DL) {
3675   // fold (or (shl x, (*ext y)),
3676   //          (srl x, (*ext (sub 32, y)))) ->
3677   //   (rotl x, y) or (rotr x, (sub 32, y))
3678   //
3679   // fold (or (shl x, (*ext (sub 32, y))),
3680   //          (srl x, (*ext y))) ->
3681   //   (rotr x, y) or (rotl x, (sub 32, y))
3682   EVT VT = Shifted.getValueType();
3683   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3684     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3685     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3686                        HasPos ? Pos : Neg).getNode();
3687   }
3688
3689   return nullptr;
3690 }
3691
3692 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3693 // idioms for rotate, and if the target supports rotation instructions, generate
3694 // a rot[lr].
3695 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3696   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3697   EVT VT = LHS.getValueType();
3698   if (!TLI.isTypeLegal(VT)) return nullptr;
3699
3700   // The target must have at least one rotate flavor.
3701   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3702   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3703   if (!HasROTL && !HasROTR) return nullptr;
3704
3705   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3706   SDValue LHSShift;   // The shift.
3707   SDValue LHSMask;    // AND value if any.
3708   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3709     return nullptr; // Not part of a rotate.
3710
3711   SDValue RHSShift;   // The shift.
3712   SDValue RHSMask;    // AND value if any.
3713   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3714     return nullptr; // Not part of a rotate.
3715
3716   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3717     return nullptr;   // Not shifting the same value.
3718
3719   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3720     return nullptr;   // Shifts must disagree.
3721
3722   // Canonicalize shl to left side in a shl/srl pair.
3723   if (RHSShift.getOpcode() == ISD::SHL) {
3724     std::swap(LHS, RHS);
3725     std::swap(LHSShift, RHSShift);
3726     std::swap(LHSMask , RHSMask );
3727   }
3728
3729   unsigned OpSizeInBits = VT.getSizeInBits();
3730   SDValue LHSShiftArg = LHSShift.getOperand(0);
3731   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3732   SDValue RHSShiftArg = RHSShift.getOperand(0);
3733   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3734
3735   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3736   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3737   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3738       RHSShiftAmt.getOpcode() == ISD::Constant) {
3739     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3740     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3741     if ((LShVal + RShVal) != OpSizeInBits)
3742       return nullptr;
3743
3744     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3745                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3746
3747     // If there is an AND of either shifted operand, apply it to the result.
3748     if (LHSMask.getNode() || RHSMask.getNode()) {
3749       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3750
3751       if (LHSMask.getNode()) {
3752         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3753         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3754       }
3755       if (RHSMask.getNode()) {
3756         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3757         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3758       }
3759
3760       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3761     }
3762
3763     return Rot.getNode();
3764   }
3765
3766   // If there is a mask here, and we have a variable shift, we can't be sure
3767   // that we're masking out the right stuff.
3768   if (LHSMask.getNode() || RHSMask.getNode())
3769     return nullptr;
3770
3771   // If the shift amount is sign/zext/any-extended just peel it off.
3772   SDValue LExtOp0 = LHSShiftAmt;
3773   SDValue RExtOp0 = RHSShiftAmt;
3774   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3775        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3776        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3777        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3778       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3779        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3780        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3781        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3782     LExtOp0 = LHSShiftAmt.getOperand(0);
3783     RExtOp0 = RHSShiftAmt.getOperand(0);
3784   }
3785
3786   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3787                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3788   if (TryL)
3789     return TryL;
3790
3791   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3792                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3793   if (TryR)
3794     return TryR;
3795
3796   return nullptr;
3797 }
3798
3799 SDValue DAGCombiner::visitXOR(SDNode *N) {
3800   SDValue N0 = N->getOperand(0);
3801   SDValue N1 = N->getOperand(1);
3802   SDValue LHS, RHS, CC;
3803   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3804   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3805   EVT VT = N0.getValueType();
3806
3807   // fold vector ops
3808   if (VT.isVector()) {
3809     SDValue FoldedVOp = SimplifyVBinOp(N);
3810     if (FoldedVOp.getNode()) return FoldedVOp;
3811
3812     // fold (xor x, 0) -> x, vector edition
3813     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3814       return N1;
3815     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3816       return N0;
3817   }
3818
3819   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3820   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3821     return DAG.getConstant(0, VT);
3822   // fold (xor x, undef) -> undef
3823   if (N0.getOpcode() == ISD::UNDEF)
3824     return N0;
3825   if (N1.getOpcode() == ISD::UNDEF)
3826     return N1;
3827   // fold (xor c1, c2) -> c1^c2
3828   if (N0C && N1C)
3829     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3830   // canonicalize constant to RHS
3831   if (N0C && !N1C)
3832     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3833   // fold (xor x, 0) -> x
3834   if (N1C && N1C->isNullValue())
3835     return N0;
3836   // reassociate xor
3837   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3838   if (RXOR.getNode())
3839     return RXOR;
3840
3841   // fold !(x cc y) -> (x !cc y)
3842   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3843     bool isInt = LHS.getValueType().isInteger();
3844     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3845                                                isInt);
3846
3847     if (!LegalOperations ||
3848         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3849       switch (N0.getOpcode()) {
3850       default:
3851         llvm_unreachable("Unhandled SetCC Equivalent!");
3852       case ISD::SETCC:
3853         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3854       case ISD::SELECT_CC:
3855         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3856                                N0.getOperand(3), NotCC);
3857       }
3858     }
3859   }
3860
3861   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3862   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3863       N0.getNode()->hasOneUse() &&
3864       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3865     SDValue V = N0.getOperand(0);
3866     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3867                     DAG.getConstant(1, V.getValueType()));
3868     AddToWorklist(V.getNode());
3869     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3870   }
3871
3872   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3873   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3874       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3875     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3876     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3877       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3878       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3879       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3880       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3881       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3882     }
3883   }
3884   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3885   if (N1C && N1C->isAllOnesValue() &&
3886       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3887     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3888     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3889       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3890       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3891       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3892       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3893       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3894     }
3895   }
3896   // fold (xor (and x, y), y) -> (and (not x), y)
3897   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3898       N0->getOperand(1) == N1) {
3899     SDValue X = N0->getOperand(0);
3900     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3901     AddToWorklist(NotX.getNode());
3902     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3903   }
3904   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3905   if (N1C && N0.getOpcode() == ISD::XOR) {
3906     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3907     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3908     if (N00C)
3909       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3910                          DAG.getConstant(N1C->getAPIntValue() ^
3911                                          N00C->getAPIntValue(), VT));
3912     if (N01C)
3913       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3914                          DAG.getConstant(N1C->getAPIntValue() ^
3915                                          N01C->getAPIntValue(), VT));
3916   }
3917   // fold (xor x, x) -> 0
3918   if (N0 == N1)
3919     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3920
3921   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3922   if (N0.getOpcode() == N1.getOpcode()) {
3923     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3924     if (Tmp.getNode()) return Tmp;
3925   }
3926
3927   // Simplify the expression using non-local knowledge.
3928   if (!VT.isVector() &&
3929       SimplifyDemandedBits(SDValue(N, 0)))
3930     return SDValue(N, 0);
3931
3932   return SDValue();
3933 }
3934
3935 /// Handle transforms common to the three shifts, when the shift amount is a
3936 /// constant.
3937 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3938   // We can't and shouldn't fold opaque constants.
3939   if (Amt->isOpaque())
3940     return SDValue();
3941
3942   SDNode *LHS = N->getOperand(0).getNode();
3943   if (!LHS->hasOneUse()) return SDValue();
3944
3945   // We want to pull some binops through shifts, so that we have (and (shift))
3946   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3947   // thing happens with address calculations, so it's important to canonicalize
3948   // it.
3949   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3950
3951   switch (LHS->getOpcode()) {
3952   default: return SDValue();
3953   case ISD::OR:
3954   case ISD::XOR:
3955     HighBitSet = false; // We can only transform sra if the high bit is clear.
3956     break;
3957   case ISD::AND:
3958     HighBitSet = true;  // We can only transform sra if the high bit is set.
3959     break;
3960   case ISD::ADD:
3961     if (N->getOpcode() != ISD::SHL)
3962       return SDValue(); // only shl(add) not sr[al](add).
3963     HighBitSet = false; // We can only transform sra if the high bit is clear.
3964     break;
3965   }
3966
3967   // We require the RHS of the binop to be a constant and not opaque as well.
3968   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3969   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3970
3971   // FIXME: disable this unless the input to the binop is a shift by a constant.
3972   // If it is not a shift, it pessimizes some common cases like:
3973   //
3974   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3975   //    int bar(int *X, int i) { return X[i & 255]; }
3976   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3977   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3978        BinOpLHSVal->getOpcode() != ISD::SRA &&
3979        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3980       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3981     return SDValue();
3982
3983   EVT VT = N->getValueType(0);
3984
3985   // If this is a signed shift right, and the high bit is modified by the
3986   // logical operation, do not perform the transformation. The highBitSet
3987   // boolean indicates the value of the high bit of the constant which would
3988   // cause it to be modified for this operation.
3989   if (N->getOpcode() == ISD::SRA) {
3990     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3991     if (BinOpRHSSignSet != HighBitSet)
3992       return SDValue();
3993   }
3994
3995   if (!TLI.isDesirableToCommuteWithShift(LHS))
3996     return SDValue();
3997
3998   // Fold the constants, shifting the binop RHS by the shift amount.
3999   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
4000                                N->getValueType(0),
4001                                LHS->getOperand(1), N->getOperand(1));
4002   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4003
4004   // Create the new shift.
4005   SDValue NewShift = DAG.getNode(N->getOpcode(),
4006                                  SDLoc(LHS->getOperand(0)),
4007                                  VT, LHS->getOperand(0), N->getOperand(1));
4008
4009   // Create the new binop.
4010   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4011 }
4012
4013 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4014   assert(N->getOpcode() == ISD::TRUNCATE);
4015   assert(N->getOperand(0).getOpcode() == ISD::AND);
4016
4017   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4018   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4019     SDValue N01 = N->getOperand(0).getOperand(1);
4020
4021     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4022       EVT TruncVT = N->getValueType(0);
4023       SDValue N00 = N->getOperand(0).getOperand(0);
4024       APInt TruncC = N01C->getAPIntValue();
4025       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4026
4027       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4028                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4029                          DAG.getConstant(TruncC, TruncVT));
4030     }
4031   }
4032
4033   return SDValue();
4034 }
4035
4036 SDValue DAGCombiner::visitRotate(SDNode *N) {
4037   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4038   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4039       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4040     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4041     if (NewOp1.getNode())
4042       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4043                          N->getOperand(0), NewOp1);
4044   }
4045   return SDValue();
4046 }
4047
4048 SDValue DAGCombiner::visitSHL(SDNode *N) {
4049   SDValue N0 = N->getOperand(0);
4050   SDValue N1 = N->getOperand(1);
4051   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4052   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4053   EVT VT = N0.getValueType();
4054   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4055
4056   // fold vector ops
4057   if (VT.isVector()) {
4058     SDValue FoldedVOp = SimplifyVBinOp(N);
4059     if (FoldedVOp.getNode()) return FoldedVOp;
4060
4061     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4062     // If setcc produces all-one true value then:
4063     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4064     if (N1CV && N1CV->isConstant()) {
4065       if (N0.getOpcode() == ISD::AND) {
4066         SDValue N00 = N0->getOperand(0);
4067         SDValue N01 = N0->getOperand(1);
4068         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4069
4070         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4071             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4072                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4073           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4074           if (C.getNode())
4075             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4076         }
4077       } else {
4078         N1C = isConstOrConstSplat(N1);
4079       }
4080     }
4081   }
4082
4083   // fold (shl c1, c2) -> c1<<c2
4084   if (N0C && N1C)
4085     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4086   // fold (shl 0, x) -> 0
4087   if (N0C && N0C->isNullValue())
4088     return N0;
4089   // fold (shl x, c >= size(x)) -> undef
4090   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4091     return DAG.getUNDEF(VT);
4092   // fold (shl x, 0) -> x
4093   if (N1C && N1C->isNullValue())
4094     return N0;
4095   // fold (shl undef, x) -> 0
4096   if (N0.getOpcode() == ISD::UNDEF)
4097     return DAG.getConstant(0, VT);
4098   // if (shl x, c) is known to be zero, return 0
4099   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4100                             APInt::getAllOnesValue(OpSizeInBits)))
4101     return DAG.getConstant(0, VT);
4102   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4103   if (N1.getOpcode() == ISD::TRUNCATE &&
4104       N1.getOperand(0).getOpcode() == ISD::AND) {
4105     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4106     if (NewOp1.getNode())
4107       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4108   }
4109
4110   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4111     return SDValue(N, 0);
4112
4113   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4114   if (N1C && N0.getOpcode() == ISD::SHL) {
4115     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4116       uint64_t c1 = N0C1->getZExtValue();
4117       uint64_t c2 = N1C->getZExtValue();
4118       if (c1 + c2 >= OpSizeInBits)
4119         return DAG.getConstant(0, VT);
4120       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4121                          DAG.getConstant(c1 + c2, N1.getValueType()));
4122     }
4123   }
4124
4125   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4126   // For this to be valid, the second form must not preserve any of the bits
4127   // that are shifted out by the inner shift in the first form.  This means
4128   // the outer shift size must be >= the number of bits added by the ext.
4129   // As a corollary, we don't care what kind of ext it is.
4130   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4131               N0.getOpcode() == ISD::ANY_EXTEND ||
4132               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4133       N0.getOperand(0).getOpcode() == ISD::SHL) {
4134     SDValue N0Op0 = N0.getOperand(0);
4135     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4136       uint64_t c1 = N0Op0C1->getZExtValue();
4137       uint64_t c2 = N1C->getZExtValue();
4138       EVT InnerShiftVT = N0Op0.getValueType();
4139       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4140       if (c2 >= OpSizeInBits - InnerShiftSize) {
4141         if (c1 + c2 >= OpSizeInBits)
4142           return DAG.getConstant(0, VT);
4143         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4144                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4145                                        N0Op0->getOperand(0)),
4146                            DAG.getConstant(c1 + c2, N1.getValueType()));
4147       }
4148     }
4149   }
4150
4151   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4152   // Only fold this if the inner zext has no other uses to avoid increasing
4153   // the total number of instructions.
4154   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4155       N0.getOperand(0).getOpcode() == ISD::SRL) {
4156     SDValue N0Op0 = N0.getOperand(0);
4157     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4158       uint64_t c1 = N0Op0C1->getZExtValue();
4159       if (c1 < VT.getScalarSizeInBits()) {
4160         uint64_t c2 = N1C->getZExtValue();
4161         if (c1 == c2) {
4162           SDValue NewOp0 = N0.getOperand(0);
4163           EVT CountVT = NewOp0.getOperand(1).getValueType();
4164           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4165                                        NewOp0, DAG.getConstant(c2, CountVT));
4166           AddToWorklist(NewSHL.getNode());
4167           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4168         }
4169       }
4170     }
4171   }
4172
4173   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4174   //                               (and (srl x, (sub c1, c2), MASK)
4175   // Only fold this if the inner shift has no other uses -- if it does, folding
4176   // this will increase the total number of instructions.
4177   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4178     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4179       uint64_t c1 = N0C1->getZExtValue();
4180       if (c1 < OpSizeInBits) {
4181         uint64_t c2 = N1C->getZExtValue();
4182         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4183         SDValue Shift;
4184         if (c2 > c1) {
4185           Mask = Mask.shl(c2 - c1);
4186           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4187                               DAG.getConstant(c2 - c1, N1.getValueType()));
4188         } else {
4189           Mask = Mask.lshr(c1 - c2);
4190           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4191                               DAG.getConstant(c1 - c2, N1.getValueType()));
4192         }
4193         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4194                            DAG.getConstant(Mask, VT));
4195       }
4196     }
4197   }
4198   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4199   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4200     unsigned BitSize = VT.getScalarSizeInBits();
4201     SDValue HiBitsMask =
4202       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4203                                             BitSize - N1C->getZExtValue()), VT);
4204     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4205                        HiBitsMask);
4206   }
4207
4208   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4209   // Variant of version done on multiply, except mul by a power of 2 is turned
4210   // into a shift.
4211   APInt Val;
4212   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4213       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4214        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4215     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4216     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4217     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4218   }
4219
4220   if (N1C) {
4221     SDValue NewSHL = visitShiftByConstant(N, N1C);
4222     if (NewSHL.getNode())
4223       return NewSHL;
4224   }
4225
4226   return SDValue();
4227 }
4228
4229 SDValue DAGCombiner::visitSRA(SDNode *N) {
4230   SDValue N0 = N->getOperand(0);
4231   SDValue N1 = N->getOperand(1);
4232   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4233   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4234   EVT VT = N0.getValueType();
4235   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4236
4237   // fold vector ops
4238   if (VT.isVector()) {
4239     SDValue FoldedVOp = SimplifyVBinOp(N);
4240     if (FoldedVOp.getNode()) return FoldedVOp;
4241
4242     N1C = isConstOrConstSplat(N1);
4243   }
4244
4245   // fold (sra c1, c2) -> (sra c1, c2)
4246   if (N0C && N1C)
4247     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4248   // fold (sra 0, x) -> 0
4249   if (N0C && N0C->isNullValue())
4250     return N0;
4251   // fold (sra -1, x) -> -1
4252   if (N0C && N0C->isAllOnesValue())
4253     return N0;
4254   // fold (sra x, (setge c, size(x))) -> undef
4255   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4256     return DAG.getUNDEF(VT);
4257   // fold (sra x, 0) -> x
4258   if (N1C && N1C->isNullValue())
4259     return N0;
4260   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4261   // sext_inreg.
4262   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4263     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4264     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4265     if (VT.isVector())
4266       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4267                                ExtVT, VT.getVectorNumElements());
4268     if ((!LegalOperations ||
4269          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4270       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4271                          N0.getOperand(0), DAG.getValueType(ExtVT));
4272   }
4273
4274   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4275   if (N1C && N0.getOpcode() == ISD::SRA) {
4276     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4277       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4278       if (Sum >= OpSizeInBits)
4279         Sum = OpSizeInBits - 1;
4280       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4281                          DAG.getConstant(Sum, N1.getValueType()));
4282     }
4283   }
4284
4285   // fold (sra (shl X, m), (sub result_size, n))
4286   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4287   // result_size - n != m.
4288   // If truncate is free for the target sext(shl) is likely to result in better
4289   // code.
4290   if (N0.getOpcode() == ISD::SHL && N1C) {
4291     // Get the two constanst of the shifts, CN0 = m, CN = n.
4292     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4293     if (N01C) {
4294       LLVMContext &Ctx = *DAG.getContext();
4295       // Determine what the truncate's result bitsize and type would be.
4296       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4297
4298       if (VT.isVector())
4299         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4300
4301       // Determine the residual right-shift amount.
4302       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4303
4304       // If the shift is not a no-op (in which case this should be just a sign
4305       // extend already), the truncated to type is legal, sign_extend is legal
4306       // on that type, and the truncate to that type is both legal and free,
4307       // perform the transform.
4308       if ((ShiftAmt > 0) &&
4309           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4310           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4311           TLI.isTruncateFree(VT, TruncVT)) {
4312
4313           SDValue Amt = DAG.getConstant(ShiftAmt,
4314               getShiftAmountTy(N0.getOperand(0).getValueType()));
4315           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4316                                       N0.getOperand(0), Amt);
4317           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4318                                       Shift);
4319           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4320                              N->getValueType(0), Trunc);
4321       }
4322     }
4323   }
4324
4325   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4326   if (N1.getOpcode() == ISD::TRUNCATE &&
4327       N1.getOperand(0).getOpcode() == ISD::AND) {
4328     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4329     if (NewOp1.getNode())
4330       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4331   }
4332
4333   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4334   //      if c1 is equal to the number of bits the trunc removes
4335   if (N0.getOpcode() == ISD::TRUNCATE &&
4336       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4337        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4338       N0.getOperand(0).hasOneUse() &&
4339       N0.getOperand(0).getOperand(1).hasOneUse() &&
4340       N1C) {
4341     SDValue N0Op0 = N0.getOperand(0);
4342     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4343       unsigned LargeShiftVal = LargeShift->getZExtValue();
4344       EVT LargeVT = N0Op0.getValueType();
4345
4346       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4347         SDValue Amt =
4348           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4349                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4350         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4351                                   N0Op0.getOperand(0), Amt);
4352         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4353       }
4354     }
4355   }
4356
4357   // Simplify, based on bits shifted out of the LHS.
4358   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4359     return SDValue(N, 0);
4360
4361
4362   // If the sign bit is known to be zero, switch this to a SRL.
4363   if (DAG.SignBitIsZero(N0))
4364     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4365
4366   if (N1C) {
4367     SDValue NewSRA = visitShiftByConstant(N, N1C);
4368     if (NewSRA.getNode())
4369       return NewSRA;
4370   }
4371
4372   return SDValue();
4373 }
4374
4375 SDValue DAGCombiner::visitSRL(SDNode *N) {
4376   SDValue N0 = N->getOperand(0);
4377   SDValue N1 = N->getOperand(1);
4378   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4379   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4380   EVT VT = N0.getValueType();
4381   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4382
4383   // fold vector ops
4384   if (VT.isVector()) {
4385     SDValue FoldedVOp = SimplifyVBinOp(N);
4386     if (FoldedVOp.getNode()) return FoldedVOp;
4387
4388     N1C = isConstOrConstSplat(N1);
4389   }
4390
4391   // fold (srl c1, c2) -> c1 >>u c2
4392   if (N0C && N1C)
4393     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4394   // fold (srl 0, x) -> 0
4395   if (N0C && N0C->isNullValue())
4396     return N0;
4397   // fold (srl x, c >= size(x)) -> undef
4398   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4399     return DAG.getUNDEF(VT);
4400   // fold (srl x, 0) -> x
4401   if (N1C && N1C->isNullValue())
4402     return N0;
4403   // if (srl x, c) is known to be zero, return 0
4404   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4405                                    APInt::getAllOnesValue(OpSizeInBits)))
4406     return DAG.getConstant(0, VT);
4407
4408   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4409   if (N1C && N0.getOpcode() == ISD::SRL) {
4410     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4411       uint64_t c1 = N01C->getZExtValue();
4412       uint64_t c2 = N1C->getZExtValue();
4413       if (c1 + c2 >= OpSizeInBits)
4414         return DAG.getConstant(0, VT);
4415       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4416                          DAG.getConstant(c1 + c2, N1.getValueType()));
4417     }
4418   }
4419
4420   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4421   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4422       N0.getOperand(0).getOpcode() == ISD::SRL &&
4423       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4424     uint64_t c1 =
4425       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4426     uint64_t c2 = N1C->getZExtValue();
4427     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4428     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4429     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4430     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4431     if (c1 + OpSizeInBits == InnerShiftSize) {
4432       if (c1 + c2 >= InnerShiftSize)
4433         return DAG.getConstant(0, VT);
4434       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4435                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4436                                      N0.getOperand(0)->getOperand(0),
4437                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4438     }
4439   }
4440
4441   // fold (srl (shl x, c), c) -> (and x, cst2)
4442   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4443     unsigned BitSize = N0.getScalarValueSizeInBits();
4444     if (BitSize <= 64) {
4445       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4446       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4447                          DAG.getConstant(~0ULL >> ShAmt, VT));
4448     }
4449   }
4450
4451   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4452   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4453     // Shifting in all undef bits?
4454     EVT SmallVT = N0.getOperand(0).getValueType();
4455     unsigned BitSize = SmallVT.getScalarSizeInBits();
4456     if (N1C->getZExtValue() >= BitSize)
4457       return DAG.getUNDEF(VT);
4458
4459     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4460       uint64_t ShiftAmt = N1C->getZExtValue();
4461       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4462                                        N0.getOperand(0),
4463                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4464       AddToWorklist(SmallShift.getNode());
4465       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4466       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4467                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4468                          DAG.getConstant(Mask, VT));
4469     }
4470   }
4471
4472   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4473   // bit, which is unmodified by sra.
4474   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4475     if (N0.getOpcode() == ISD::SRA)
4476       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4477   }
4478
4479   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4480   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4481       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4482     APInt KnownZero, KnownOne;
4483     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4484
4485     // If any of the input bits are KnownOne, then the input couldn't be all
4486     // zeros, thus the result of the srl will always be zero.
4487     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4488
4489     // If all of the bits input the to ctlz node are known to be zero, then
4490     // the result of the ctlz is "32" and the result of the shift is one.
4491     APInt UnknownBits = ~KnownZero;
4492     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4493
4494     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4495     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4496       // Okay, we know that only that the single bit specified by UnknownBits
4497       // could be set on input to the CTLZ node. If this bit is set, the SRL
4498       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4499       // to an SRL/XOR pair, which is likely to simplify more.
4500       unsigned ShAmt = UnknownBits.countTrailingZeros();
4501       SDValue Op = N0.getOperand(0);
4502
4503       if (ShAmt) {
4504         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4505                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4506         AddToWorklist(Op.getNode());
4507       }
4508
4509       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4510                          Op, DAG.getConstant(1, VT));
4511     }
4512   }
4513
4514   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4515   if (N1.getOpcode() == ISD::TRUNCATE &&
4516       N1.getOperand(0).getOpcode() == ISD::AND) {
4517     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4518     if (NewOp1.getNode())
4519       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4520   }
4521
4522   // fold operands of srl based on knowledge that the low bits are not
4523   // demanded.
4524   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4525     return SDValue(N, 0);
4526
4527   if (N1C) {
4528     SDValue NewSRL = visitShiftByConstant(N, N1C);
4529     if (NewSRL.getNode())
4530       return NewSRL;
4531   }
4532
4533   // Attempt to convert a srl of a load into a narrower zero-extending load.
4534   SDValue NarrowLoad = ReduceLoadWidth(N);
4535   if (NarrowLoad.getNode())
4536     return NarrowLoad;
4537
4538   // Here is a common situation. We want to optimize:
4539   //
4540   //   %a = ...
4541   //   %b = and i32 %a, 2
4542   //   %c = srl i32 %b, 1
4543   //   brcond i32 %c ...
4544   //
4545   // into
4546   //
4547   //   %a = ...
4548   //   %b = and %a, 2
4549   //   %c = setcc eq %b, 0
4550   //   brcond %c ...
4551   //
4552   // However when after the source operand of SRL is optimized into AND, the SRL
4553   // itself may not be optimized further. Look for it and add the BRCOND into
4554   // the worklist.
4555   if (N->hasOneUse()) {
4556     SDNode *Use = *N->use_begin();
4557     if (Use->getOpcode() == ISD::BRCOND)
4558       AddToWorklist(Use);
4559     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4560       // Also look pass the truncate.
4561       Use = *Use->use_begin();
4562       if (Use->getOpcode() == ISD::BRCOND)
4563         AddToWorklist(Use);
4564     }
4565   }
4566
4567   return SDValue();
4568 }
4569
4570 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4571   SDValue N0 = N->getOperand(0);
4572   EVT VT = N->getValueType(0);
4573
4574   // fold (ctlz c1) -> c2
4575   if (isa<ConstantSDNode>(N0))
4576     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4577   return SDValue();
4578 }
4579
4580 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4581   SDValue N0 = N->getOperand(0);
4582   EVT VT = N->getValueType(0);
4583
4584   // fold (ctlz_zero_undef c1) -> c2
4585   if (isa<ConstantSDNode>(N0))
4586     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4587   return SDValue();
4588 }
4589
4590 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4591   SDValue N0 = N->getOperand(0);
4592   EVT VT = N->getValueType(0);
4593
4594   // fold (cttz c1) -> c2
4595   if (isa<ConstantSDNode>(N0))
4596     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4597   return SDValue();
4598 }
4599
4600 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4601   SDValue N0 = N->getOperand(0);
4602   EVT VT = N->getValueType(0);
4603
4604   // fold (cttz_zero_undef c1) -> c2
4605   if (isa<ConstantSDNode>(N0))
4606     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4607   return SDValue();
4608 }
4609
4610 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4611   SDValue N0 = N->getOperand(0);
4612   EVT VT = N->getValueType(0);
4613
4614   // fold (ctpop c1) -> c2
4615   if (isa<ConstantSDNode>(N0))
4616     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4617   return SDValue();
4618 }
4619
4620
4621 /// \brief Generate Min/Max node
4622 static SDValue combineMinNumMaxNum(SDLoc DL, EVT VT, SDValue LHS, SDValue RHS,
4623                                    SDValue True, SDValue False,
4624                                    ISD::CondCode CC, const TargetLowering &TLI,
4625                                    SelectionDAG &DAG) {
4626   if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
4627     return SDValue();
4628
4629   switch (CC) {
4630   case ISD::SETOLT:
4631   case ISD::SETOLE:
4632   case ISD::SETLT:
4633   case ISD::SETLE:
4634   case ISD::SETULT:
4635   case ISD::SETULE: {
4636     unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
4637     if (TLI.isOperationLegal(Opcode, VT))
4638       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4639     return SDValue();
4640   }
4641   case ISD::SETOGT:
4642   case ISD::SETOGE:
4643   case ISD::SETGT:
4644   case ISD::SETGE:
4645   case ISD::SETUGT:
4646   case ISD::SETUGE: {
4647     unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
4648     if (TLI.isOperationLegal(Opcode, VT))
4649       return DAG.getNode(Opcode, DL, VT, LHS, RHS);
4650     return SDValue();
4651   }
4652   default:
4653     return SDValue();
4654   }
4655 }
4656
4657 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4658   SDValue N0 = N->getOperand(0);
4659   SDValue N1 = N->getOperand(1);
4660   SDValue N2 = N->getOperand(2);
4661   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4662   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4663   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4664   EVT VT = N->getValueType(0);
4665   EVT VT0 = N0.getValueType();
4666
4667   // fold (select C, X, X) -> X
4668   if (N1 == N2)
4669     return N1;
4670   // fold (select true, X, Y) -> X
4671   if (N0C && !N0C->isNullValue())
4672     return N1;
4673   // fold (select false, X, Y) -> Y
4674   if (N0C && N0C->isNullValue())
4675     return N2;
4676   // fold (select C, 1, X) -> (or C, X)
4677   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4678     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4679   // fold (select C, 0, 1) -> (xor C, 1)
4680   // We can't do this reliably if integer based booleans have different contents
4681   // to floating point based booleans. This is because we can't tell whether we
4682   // have an integer-based boolean or a floating-point-based boolean unless we
4683   // can find the SETCC that produced it and inspect its operands. This is
4684   // fairly easy if C is the SETCC node, but it can potentially be
4685   // undiscoverable (or not reasonably discoverable). For example, it could be
4686   // in another basic block or it could require searching a complicated
4687   // expression.
4688   if (VT.isInteger() &&
4689       (VT0 == MVT::i1 || (VT0.isInteger() &&
4690                           TLI.getBooleanContents(false, false) ==
4691                               TLI.getBooleanContents(false, true) &&
4692                           TLI.getBooleanContents(false, false) ==
4693                               TargetLowering::ZeroOrOneBooleanContent)) &&
4694       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4695     SDValue XORNode;
4696     if (VT == VT0)
4697       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4698                          N0, DAG.getConstant(1, VT0));
4699     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4700                           N0, DAG.getConstant(1, VT0));
4701     AddToWorklist(XORNode.getNode());
4702     if (VT.bitsGT(VT0))
4703       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4704     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4705   }
4706   // fold (select C, 0, X) -> (and (not C), X)
4707   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4708     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4709     AddToWorklist(NOTNode.getNode());
4710     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4711   }
4712   // fold (select C, X, 1) -> (or (not C), X)
4713   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4714     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4715     AddToWorklist(NOTNode.getNode());
4716     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4717   }
4718   // fold (select C, X, 0) -> (and C, X)
4719   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4720     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4721   // fold (select X, X, Y) -> (or X, Y)
4722   // fold (select X, 1, Y) -> (or X, Y)
4723   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4724     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4725   // fold (select X, Y, X) -> (and X, Y)
4726   // fold (select X, Y, 0) -> (and X, Y)
4727   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4728     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4729
4730   // If we can fold this based on the true/false value, do so.
4731   if (SimplifySelectOps(N, N1, N2))
4732     return SDValue(N, 0);  // Don't revisit N.
4733
4734   // fold selects based on a setcc into other things, such as min/max/abs
4735   if (N0.getOpcode() == ISD::SETCC) {
4736     // select x, y (fcmp lt x, y) -> fminnum x, y
4737     // select x, y (fcmp gt x, y) -> fmaxnum x, y
4738     //
4739     // This is OK if we don't care about what happens if either operand is a
4740     // NaN.
4741     //
4742
4743     // FIXME: Instead of testing for UnsafeFPMath, this should be checking for
4744     // no signed zeros as well as no nans.
4745     const TargetOptions &Options = DAG.getTarget().Options;
4746     if (Options.UnsafeFPMath &&
4747         VT.isFloatingPoint() && N0.hasOneUse() &&
4748         DAG.isKnownNeverNaN(N1) && DAG.isKnownNeverNaN(N2)) {
4749       ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4750
4751       SDValue FMinMax =
4752           combineMinNumMaxNum(SDLoc(N), VT, N0.getOperand(0), N0.getOperand(1),
4753                               N1, N2, CC, TLI, DAG);
4754       if (FMinMax)
4755         return FMinMax;
4756     }
4757
4758     if ((!LegalOperations &&
4759          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4760         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4761       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4762                          N0.getOperand(0), N0.getOperand(1),
4763                          N1, N2, N0.getOperand(2));
4764     return SimplifySelect(SDLoc(N), N0, N1, N2);
4765   }
4766
4767   return SDValue();
4768 }
4769
4770 static
4771 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4772   SDLoc DL(N);
4773   EVT LoVT, HiVT;
4774   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4775
4776   // Split the inputs.
4777   SDValue Lo, Hi, LL, LH, RL, RH;
4778   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4779   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4780
4781   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4782   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4783
4784   return std::make_pair(Lo, Hi);
4785 }
4786
4787 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4788 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4789 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4790   SDLoc dl(N);
4791   SDValue Cond = N->getOperand(0);
4792   SDValue LHS = N->getOperand(1);
4793   SDValue RHS = N->getOperand(2);
4794   EVT VT = N->getValueType(0);
4795   int NumElems = VT.getVectorNumElements();
4796   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4797          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4798          Cond.getOpcode() == ISD::BUILD_VECTOR);
4799
4800   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4801   // binary ones here.
4802   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4803     return SDValue();
4804
4805   // We're sure we have an even number of elements due to the
4806   // concat_vectors we have as arguments to vselect.
4807   // Skip BV elements until we find one that's not an UNDEF
4808   // After we find an UNDEF element, keep looping until we get to half the
4809   // length of the BV and see if all the non-undef nodes are the same.
4810   ConstantSDNode *BottomHalf = nullptr;
4811   for (int i = 0; i < NumElems / 2; ++i) {
4812     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4813       continue;
4814
4815     if (BottomHalf == nullptr)
4816       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4817     else if (Cond->getOperand(i).getNode() != BottomHalf)
4818       return SDValue();
4819   }
4820
4821   // Do the same for the second half of the BuildVector
4822   ConstantSDNode *TopHalf = nullptr;
4823   for (int i = NumElems / 2; i < NumElems; ++i) {
4824     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4825       continue;
4826
4827     if (TopHalf == nullptr)
4828       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4829     else if (Cond->getOperand(i).getNode() != TopHalf)
4830       return SDValue();
4831   }
4832
4833   assert(TopHalf && BottomHalf &&
4834          "One half of the selector was all UNDEFs and the other was all the "
4835          "same value. This should have been addressed before this function.");
4836   return DAG.getNode(
4837       ISD::CONCAT_VECTORS, dl, VT,
4838       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4839       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4840 }
4841
4842 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4843
4844   if (Level >= AfterLegalizeTypes)
4845     return SDValue();
4846
4847   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4848   SDValue Mask = MST->getMask();
4849   SDValue Data  = MST->getData();
4850   SDLoc DL(N);
4851
4852   // If the MSTORE data type requires splitting and the mask is provided by a
4853   // SETCC, then split both nodes and its operands before legalization. This
4854   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4855   // and enables future optimizations (e.g. min/max pattern matching on X86).
4856   if (Mask.getOpcode() == ISD::SETCC) {
4857
4858     // Check if any splitting is required.
4859     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4860         TargetLowering::TypeSplitVector)
4861       return SDValue();
4862
4863     SDValue MaskLo, MaskHi, Lo, Hi;
4864     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4865
4866     EVT LoVT, HiVT;
4867     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4868
4869     SDValue Chain = MST->getChain();
4870     SDValue Ptr   = MST->getBasePtr();
4871
4872     EVT MemoryVT = MST->getMemoryVT();
4873     unsigned Alignment = MST->getOriginalAlignment();
4874
4875     // if Alignment is equal to the vector size,
4876     // take the half of it for the second part
4877     unsigned SecondHalfAlignment =
4878       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4879          Alignment/2 : Alignment;
4880
4881     EVT LoMemVT, HiMemVT;
4882     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4883
4884     SDValue DataLo, DataHi;
4885     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4886
4887     MachineMemOperand *MMO = DAG.getMachineFunction().
4888       getMachineMemOperand(MST->getPointerInfo(), 
4889                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4890                            Alignment, MST->getAAInfo(), MST->getRanges());
4891
4892     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4893
4894     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4895     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4896                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4897
4898     MMO = DAG.getMachineFunction().
4899       getMachineMemOperand(MST->getPointerInfo(), 
4900                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4901                            SecondHalfAlignment, MST->getAAInfo(),
4902                            MST->getRanges());
4903
4904     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4905
4906     AddToWorklist(Lo.getNode());
4907     AddToWorklist(Hi.getNode());
4908
4909     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4910   }
4911   return SDValue();
4912 }
4913
4914 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4915
4916   if (Level >= AfterLegalizeTypes)
4917     return SDValue();
4918
4919   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4920   SDValue Mask = MLD->getMask();
4921   SDLoc DL(N);
4922
4923   // If the MLOAD result requires splitting and the mask is provided by a
4924   // SETCC, then split both nodes and its operands before legalization. This
4925   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4926   // and enables future optimizations (e.g. min/max pattern matching on X86).
4927
4928   if (Mask.getOpcode() == ISD::SETCC) {
4929     EVT VT = N->getValueType(0);
4930
4931     // Check if any splitting is required.
4932     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4933         TargetLowering::TypeSplitVector)
4934       return SDValue();
4935
4936     SDValue MaskLo, MaskHi, Lo, Hi;
4937     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4938
4939     SDValue Src0 = MLD->getSrc0();
4940     SDValue Src0Lo, Src0Hi;
4941     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4942
4943     EVT LoVT, HiVT;
4944     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4945
4946     SDValue Chain = MLD->getChain();
4947     SDValue Ptr   = MLD->getBasePtr();
4948     EVT MemoryVT = MLD->getMemoryVT();
4949     unsigned Alignment = MLD->getOriginalAlignment();
4950
4951     // if Alignment is equal to the vector size,
4952     // take the half of it for the second part
4953     unsigned SecondHalfAlignment =
4954       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4955          Alignment/2 : Alignment;
4956
4957     EVT LoMemVT, HiMemVT;
4958     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4959
4960     MachineMemOperand *MMO = DAG.getMachineFunction().
4961     getMachineMemOperand(MLD->getPointerInfo(), 
4962                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4963                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4964
4965     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4966
4967     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4968     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4969                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4970
4971     MMO = DAG.getMachineFunction().
4972     getMachineMemOperand(MLD->getPointerInfo(), 
4973                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4974                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4975
4976     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4977
4978     AddToWorklist(Lo.getNode());
4979     AddToWorklist(Hi.getNode());
4980
4981     // Build a factor node to remember that this load is independent of the
4982     // other one.
4983     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4984                         Hi.getValue(1));
4985
4986     // Legalized the chain result - switch anything that used the old chain to
4987     // use the new one.
4988     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4989
4990     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4991
4992     SDValue RetOps[] = { LoadRes, Chain };
4993     return DAG.getMergeValues(RetOps, DL);
4994   }
4995   return SDValue();
4996 }
4997
4998 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4999   SDValue N0 = N->getOperand(0);
5000   SDValue N1 = N->getOperand(1);
5001   SDValue N2 = N->getOperand(2);
5002   SDLoc DL(N);
5003
5004   // Canonicalize integer abs.
5005   // vselect (setg[te] X,  0),  X, -X ->
5006   // vselect (setgt    X, -1),  X, -X ->
5007   // vselect (setl[te] X,  0), -X,  X ->
5008   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
5009   if (N0.getOpcode() == ISD::SETCC) {
5010     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
5011     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5012     bool isAbs = false;
5013     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
5014
5015     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
5016          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
5017         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
5018       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
5019     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
5020              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
5021       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
5022
5023     if (isAbs) {
5024       EVT VT = LHS.getValueType();
5025       SDValue Shift = DAG.getNode(
5026           ISD::SRA, DL, VT, LHS,
5027           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
5028       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
5029       AddToWorklist(Shift.getNode());
5030       AddToWorklist(Add.getNode());
5031       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
5032     }
5033   }
5034
5035   // If the VSELECT result requires splitting and the mask is provided by a
5036   // SETCC, then split both nodes and its operands before legalization. This
5037   // prevents the type legalizer from unrolling SETCC into scalar comparisons
5038   // and enables future optimizations (e.g. min/max pattern matching on X86).
5039   if (N0.getOpcode() == ISD::SETCC) {
5040     EVT VT = N->getValueType(0);
5041
5042     // Check if any splitting is required.
5043     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
5044         TargetLowering::TypeSplitVector)
5045       return SDValue();
5046
5047     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
5048     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
5049     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
5050     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
5051
5052     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
5053     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
5054
5055     // Add the new VSELECT nodes to the work list in case they need to be split
5056     // again.
5057     AddToWorklist(Lo.getNode());
5058     AddToWorklist(Hi.getNode());
5059
5060     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
5061   }
5062
5063   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5064   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5065     return N1;
5066   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5067   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5068     return N2;
5069
5070   // The ConvertSelectToConcatVector function is assuming both the above
5071   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5072   // and addressed.
5073   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5074       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5075       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5076     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5077     if (CV.getNode())
5078       return CV;
5079   }
5080
5081   return SDValue();
5082 }
5083
5084 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5085   SDValue N0 = N->getOperand(0);
5086   SDValue N1 = N->getOperand(1);
5087   SDValue N2 = N->getOperand(2);
5088   SDValue N3 = N->getOperand(3);
5089   SDValue N4 = N->getOperand(4);
5090   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5091
5092   // fold select_cc lhs, rhs, x, x, cc -> x
5093   if (N2 == N3)
5094     return N2;
5095
5096   // Determine if the condition we're dealing with is constant
5097   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5098                               N0, N1, CC, SDLoc(N), false);
5099   if (SCC.getNode()) {
5100     AddToWorklist(SCC.getNode());
5101
5102     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5103       if (!SCCC->isNullValue())
5104         return N2;    // cond always true -> true val
5105       else
5106         return N3;    // cond always false -> false val
5107     }
5108
5109     // Fold to a simpler select_cc
5110     if (SCC.getOpcode() == ISD::SETCC)
5111       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5112                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5113                          SCC.getOperand(2));
5114   }
5115
5116   // If we can fold this based on the true/false value, do so.
5117   if (SimplifySelectOps(N, N2, N3))
5118     return SDValue(N, 0);  // Don't revisit N.
5119
5120   // fold select_cc into other things, such as min/max/abs
5121   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5122 }
5123
5124 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5125   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5126                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5127                        SDLoc(N));
5128 }
5129
5130 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5131 // dag node into a ConstantSDNode or a build_vector of constants.
5132 // This function is called by the DAGCombiner when visiting sext/zext/aext
5133 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5134 // Vector extends are not folded if operations are legal; this is to
5135 // avoid introducing illegal build_vector dag nodes.
5136 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5137                                          SelectionDAG &DAG, bool LegalTypes,
5138                                          bool LegalOperations) {
5139   unsigned Opcode = N->getOpcode();
5140   SDValue N0 = N->getOperand(0);
5141   EVT VT = N->getValueType(0);
5142
5143   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5144          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5145
5146   // fold (sext c1) -> c1
5147   // fold (zext c1) -> c1
5148   // fold (aext c1) -> c1
5149   if (isa<ConstantSDNode>(N0))
5150     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5151
5152   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5153   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5154   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5155   EVT SVT = VT.getScalarType();
5156   if (!(VT.isVector() &&
5157       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5158       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5159     return nullptr;
5160
5161   // We can fold this node into a build_vector.
5162   unsigned VTBits = SVT.getSizeInBits();
5163   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5164   unsigned ShAmt = VTBits - EVTBits;
5165   SmallVector<SDValue, 8> Elts;
5166   unsigned NumElts = N0->getNumOperands();
5167   SDLoc DL(N);
5168
5169   for (unsigned i=0; i != NumElts; ++i) {
5170     SDValue Op = N0->getOperand(i);
5171     if (Op->getOpcode() == ISD::UNDEF) {
5172       Elts.push_back(DAG.getUNDEF(SVT));
5173       continue;
5174     }
5175
5176     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5177     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5178     if (Opcode == ISD::SIGN_EXTEND)
5179       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5180                                      SVT));
5181     else
5182       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5183                                      SVT));
5184   }
5185
5186   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5187 }
5188
5189 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5190 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5191 // transformation. Returns true if extension are possible and the above
5192 // mentioned transformation is profitable.
5193 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5194                                     unsigned ExtOpc,
5195                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5196                                     const TargetLowering &TLI) {
5197   bool HasCopyToRegUses = false;
5198   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5199   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5200                             UE = N0.getNode()->use_end();
5201        UI != UE; ++UI) {
5202     SDNode *User = *UI;
5203     if (User == N)
5204       continue;
5205     if (UI.getUse().getResNo() != N0.getResNo())
5206       continue;
5207     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5208     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5209       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5210       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5211         // Sign bits will be lost after a zext.
5212         return false;
5213       bool Add = false;
5214       for (unsigned i = 0; i != 2; ++i) {
5215         SDValue UseOp = User->getOperand(i);
5216         if (UseOp == N0)
5217           continue;
5218         if (!isa<ConstantSDNode>(UseOp))
5219           return false;
5220         Add = true;
5221       }
5222       if (Add)
5223         ExtendNodes.push_back(User);
5224       continue;
5225     }
5226     // If truncates aren't free and there are users we can't
5227     // extend, it isn't worthwhile.
5228     if (!isTruncFree)
5229       return false;
5230     // Remember if this value is live-out.
5231     if (User->getOpcode() == ISD::CopyToReg)
5232       HasCopyToRegUses = true;
5233   }
5234
5235   if (HasCopyToRegUses) {
5236     bool BothLiveOut = false;
5237     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5238          UI != UE; ++UI) {
5239       SDUse &Use = UI.getUse();
5240       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5241         BothLiveOut = true;
5242         break;
5243       }
5244     }
5245     if (BothLiveOut)
5246       // Both unextended and extended values are live out. There had better be
5247       // a good reason for the transformation.
5248       return ExtendNodes.size();
5249   }
5250   return true;
5251 }
5252
5253 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5254                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5255                                   ISD::NodeType ExtType) {
5256   // Extend SetCC uses if necessary.
5257   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5258     SDNode *SetCC = SetCCs[i];
5259     SmallVector<SDValue, 4> Ops;
5260
5261     for (unsigned j = 0; j != 2; ++j) {
5262       SDValue SOp = SetCC->getOperand(j);
5263       if (SOp == Trunc)
5264         Ops.push_back(ExtLoad);
5265       else
5266         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5267     }
5268
5269     Ops.push_back(SetCC->getOperand(2));
5270     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5271   }
5272 }
5273
5274 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5275   SDValue N0 = N->getOperand(0);
5276   EVT VT = N->getValueType(0);
5277
5278   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5279                                               LegalOperations))
5280     return SDValue(Res, 0);
5281
5282   // fold (sext (sext x)) -> (sext x)
5283   // fold (sext (aext x)) -> (sext x)
5284   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5285     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5286                        N0.getOperand(0));
5287
5288   if (N0.getOpcode() == ISD::TRUNCATE) {
5289     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5290     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5291     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5292     if (NarrowLoad.getNode()) {
5293       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5294       if (NarrowLoad.getNode() != N0.getNode()) {
5295         CombineTo(N0.getNode(), NarrowLoad);
5296         // CombineTo deleted the truncate, if needed, but not what's under it.
5297         AddToWorklist(oye);
5298       }
5299       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5300     }
5301
5302     // See if the value being truncated is already sign extended.  If so, just
5303     // eliminate the trunc/sext pair.
5304     SDValue Op = N0.getOperand(0);
5305     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5306     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5307     unsigned DestBits = VT.getScalarType().getSizeInBits();
5308     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5309
5310     if (OpBits == DestBits) {
5311       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5312       // bits, it is already ready.
5313       if (NumSignBits > DestBits-MidBits)
5314         return Op;
5315     } else if (OpBits < DestBits) {
5316       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5317       // bits, just sext from i32.
5318       if (NumSignBits > OpBits-MidBits)
5319         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5320     } else {
5321       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5322       // bits, just truncate to i32.
5323       if (NumSignBits > OpBits-MidBits)
5324         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5325     }
5326
5327     // fold (sext (truncate x)) -> (sextinreg x).
5328     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5329                                                  N0.getValueType())) {
5330       if (OpBits < DestBits)
5331         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5332       else if (OpBits > DestBits)
5333         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5334       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5335                          DAG.getValueType(N0.getValueType()));
5336     }
5337   }
5338
5339   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5340   // None of the supported targets knows how to perform load and sign extend
5341   // on vectors in one instruction.  We only perform this transformation on
5342   // scalars.
5343   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5344       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5345       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5346        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()))) {
5347     bool DoXform = true;
5348     SmallVector<SDNode*, 4> SetCCs;
5349     if (!N0.hasOneUse())
5350       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5351     if (DoXform) {
5352       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5353       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5354                                        LN0->getChain(),
5355                                        LN0->getBasePtr(), N0.getValueType(),
5356                                        LN0->getMemOperand());
5357       CombineTo(N, ExtLoad);
5358       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5359                                   N0.getValueType(), ExtLoad);
5360       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5361       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5362                       ISD::SIGN_EXTEND);
5363       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5364     }
5365   }
5366
5367   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5368   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5369   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5370       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5371     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5372     EVT MemVT = LN0->getMemoryVT();
5373     if ((!LegalOperations && !LN0->isVolatile()) ||
5374         TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT)) {
5375       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5376                                        LN0->getChain(),
5377                                        LN0->getBasePtr(), MemVT,
5378                                        LN0->getMemOperand());
5379       CombineTo(N, ExtLoad);
5380       CombineTo(N0.getNode(),
5381                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5382                             N0.getValueType(), ExtLoad),
5383                 ExtLoad.getValue(1));
5384       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5385     }
5386   }
5387
5388   // fold (sext (and/or/xor (load x), cst)) ->
5389   //      (and/or/xor (sextload x), (sext cst))
5390   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5391        N0.getOpcode() == ISD::XOR) &&
5392       isa<LoadSDNode>(N0.getOperand(0)) &&
5393       N0.getOperand(1).getOpcode() == ISD::Constant &&
5394       TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, N0.getValueType()) &&
5395       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5396     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5397     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5398       bool DoXform = true;
5399       SmallVector<SDNode*, 4> SetCCs;
5400       if (!N0.hasOneUse())
5401         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5402                                           SetCCs, TLI);
5403       if (DoXform) {
5404         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5405                                          LN0->getChain(), LN0->getBasePtr(),
5406                                          LN0->getMemoryVT(),
5407                                          LN0->getMemOperand());
5408         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5409         Mask = Mask.sext(VT.getSizeInBits());
5410         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5411                                   ExtLoad, DAG.getConstant(Mask, VT));
5412         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5413                                     SDLoc(N0.getOperand(0)),
5414                                     N0.getOperand(0).getValueType(), ExtLoad);
5415         CombineTo(N, And);
5416         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5417         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5418                         ISD::SIGN_EXTEND);
5419         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5420       }
5421     }
5422   }
5423
5424   if (N0.getOpcode() == ISD::SETCC) {
5425     EVT N0VT = N0.getOperand(0).getValueType();
5426     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5427     // Only do this before legalize for now.
5428     if (VT.isVector() && !LegalOperations &&
5429         TLI.getBooleanContents(N0VT) ==
5430             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5431       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5432       // of the same size as the compared operands. Only optimize sext(setcc())
5433       // if this is the case.
5434       EVT SVT = getSetCCResultType(N0VT);
5435
5436       // We know that the # elements of the results is the same as the
5437       // # elements of the compare (and the # elements of the compare result
5438       // for that matter).  Check to see that they are the same size.  If so,
5439       // we know that the element size of the sext'd result matches the
5440       // element size of the compare operands.
5441       if (VT.getSizeInBits() == SVT.getSizeInBits())
5442         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5443                              N0.getOperand(1),
5444                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5445
5446       // If the desired elements are smaller or larger than the source
5447       // elements we can use a matching integer vector type and then
5448       // truncate/sign extend
5449       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5450       if (SVT == MatchingVectorType) {
5451         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5452                                N0.getOperand(0), N0.getOperand(1),
5453                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5454         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5455       }
5456     }
5457
5458     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5459     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5460     SDValue NegOne =
5461       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5462     SDValue SCC =
5463       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5464                        NegOne, DAG.getConstant(0, VT),
5465                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5466     if (SCC.getNode()) return SCC;
5467
5468     if (!VT.isVector()) {
5469       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5470       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5471         SDLoc DL(N);
5472         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5473         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5474                                      N0.getOperand(0), N0.getOperand(1), CC);
5475         return DAG.getSelect(DL, VT, SetCC,
5476                              NegOne, DAG.getConstant(0, VT));
5477       }
5478     }
5479   }
5480
5481   // fold (sext x) -> (zext x) if the sign bit is known zero.
5482   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5483       DAG.SignBitIsZero(N0))
5484     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5485
5486   return SDValue();
5487 }
5488
5489 // isTruncateOf - If N is a truncate of some other value, return true, record
5490 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5491 // This function computes KnownZero to avoid a duplicated call to
5492 // computeKnownBits in the caller.
5493 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5494                          APInt &KnownZero) {
5495   APInt KnownOne;
5496   if (N->getOpcode() == ISD::TRUNCATE) {
5497     Op = N->getOperand(0);
5498     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5499     return true;
5500   }
5501
5502   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5503       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5504     return false;
5505
5506   SDValue Op0 = N->getOperand(0);
5507   SDValue Op1 = N->getOperand(1);
5508   assert(Op0.getValueType() == Op1.getValueType());
5509
5510   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5511   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5512   if (COp0 && COp0->isNullValue())
5513     Op = Op1;
5514   else if (COp1 && COp1->isNullValue())
5515     Op = Op0;
5516   else
5517     return false;
5518
5519   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5520
5521   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5522     return false;
5523
5524   return true;
5525 }
5526
5527 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5528   SDValue N0 = N->getOperand(0);
5529   EVT VT = N->getValueType(0);
5530
5531   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5532                                               LegalOperations))
5533     return SDValue(Res, 0);
5534
5535   // fold (zext (zext x)) -> (zext x)
5536   // fold (zext (aext x)) -> (zext x)
5537   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5538     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5539                        N0.getOperand(0));
5540
5541   // fold (zext (truncate x)) -> (zext x) or
5542   //      (zext (truncate x)) -> (truncate x)
5543   // This is valid when the truncated bits of x are already zero.
5544   // FIXME: We should extend this to work for vectors too.
5545   SDValue Op;
5546   APInt KnownZero;
5547   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5548     APInt TruncatedBits =
5549       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5550       APInt(Op.getValueSizeInBits(), 0) :
5551       APInt::getBitsSet(Op.getValueSizeInBits(),
5552                         N0.getValueSizeInBits(),
5553                         std::min(Op.getValueSizeInBits(),
5554                                  VT.getSizeInBits()));
5555     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5556       if (VT.bitsGT(Op.getValueType()))
5557         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5558       if (VT.bitsLT(Op.getValueType()))
5559         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5560
5561       return Op;
5562     }
5563   }
5564
5565   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5566   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5567   if (N0.getOpcode() == ISD::TRUNCATE) {
5568     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5569     if (NarrowLoad.getNode()) {
5570       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5571       if (NarrowLoad.getNode() != N0.getNode()) {
5572         CombineTo(N0.getNode(), NarrowLoad);
5573         // CombineTo deleted the truncate, if needed, but not what's under it.
5574         AddToWorklist(oye);
5575       }
5576       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5577     }
5578   }
5579
5580   // fold (zext (truncate x)) -> (and x, mask)
5581   if (N0.getOpcode() == ISD::TRUNCATE &&
5582       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5583
5584     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5585     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5586     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5587     if (NarrowLoad.getNode()) {
5588       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5589       if (NarrowLoad.getNode() != N0.getNode()) {
5590         CombineTo(N0.getNode(), NarrowLoad);
5591         // CombineTo deleted the truncate, if needed, but not what's under it.
5592         AddToWorklist(oye);
5593       }
5594       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5595     }
5596
5597     SDValue Op = N0.getOperand(0);
5598     if (Op.getValueType().bitsLT(VT)) {
5599       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5600       AddToWorklist(Op.getNode());
5601     } else if (Op.getValueType().bitsGT(VT)) {
5602       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5603       AddToWorklist(Op.getNode());
5604     }
5605     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5606                                   N0.getValueType().getScalarType());
5607   }
5608
5609   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5610   // if either of the casts is not free.
5611   if (N0.getOpcode() == ISD::AND &&
5612       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5613       N0.getOperand(1).getOpcode() == ISD::Constant &&
5614       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5615                            N0.getValueType()) ||
5616        !TLI.isZExtFree(N0.getValueType(), VT))) {
5617     SDValue X = N0.getOperand(0).getOperand(0);
5618     if (X.getValueType().bitsLT(VT)) {
5619       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5620     } else if (X.getValueType().bitsGT(VT)) {
5621       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5622     }
5623     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5624     Mask = Mask.zext(VT.getSizeInBits());
5625     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5626                        X, DAG.getConstant(Mask, VT));
5627   }
5628
5629   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5630   // None of the supported targets knows how to perform load and vector_zext
5631   // on vectors in one instruction.  We only perform this transformation on
5632   // scalars.
5633   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5634       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5635       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5636        TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()))) {
5637     bool DoXform = true;
5638     SmallVector<SDNode*, 4> SetCCs;
5639     if (!N0.hasOneUse())
5640       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5641     if (DoXform) {
5642       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5643       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5644                                        LN0->getChain(),
5645                                        LN0->getBasePtr(), N0.getValueType(),
5646                                        LN0->getMemOperand());
5647       CombineTo(N, ExtLoad);
5648       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5649                                   N0.getValueType(), ExtLoad);
5650       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5651
5652       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5653                       ISD::ZERO_EXTEND);
5654       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5655     }
5656   }
5657
5658   // fold (zext (and/or/xor (load x), cst)) ->
5659   //      (and/or/xor (zextload x), (zext cst))
5660   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5661        N0.getOpcode() == ISD::XOR) &&
5662       isa<LoadSDNode>(N0.getOperand(0)) &&
5663       N0.getOperand(1).getOpcode() == ISD::Constant &&
5664       TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, N0.getValueType()) &&
5665       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5666     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5667     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5668       bool DoXform = true;
5669       SmallVector<SDNode*, 4> SetCCs;
5670       if (!N0.hasOneUse())
5671         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5672                                           SetCCs, TLI);
5673       if (DoXform) {
5674         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5675                                          LN0->getChain(), LN0->getBasePtr(),
5676                                          LN0->getMemoryVT(),
5677                                          LN0->getMemOperand());
5678         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5679         Mask = Mask.zext(VT.getSizeInBits());
5680         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5681                                   ExtLoad, DAG.getConstant(Mask, VT));
5682         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5683                                     SDLoc(N0.getOperand(0)),
5684                                     N0.getOperand(0).getValueType(), ExtLoad);
5685         CombineTo(N, And);
5686         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5687         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5688                         ISD::ZERO_EXTEND);
5689         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5690       }
5691     }
5692   }
5693
5694   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5695   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5696   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5697       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5698     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5699     EVT MemVT = LN0->getMemoryVT();
5700     if ((!LegalOperations && !LN0->isVolatile()) ||
5701         TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT)) {
5702       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5703                                        LN0->getChain(),
5704                                        LN0->getBasePtr(), MemVT,
5705                                        LN0->getMemOperand());
5706       CombineTo(N, ExtLoad);
5707       CombineTo(N0.getNode(),
5708                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5709                             ExtLoad),
5710                 ExtLoad.getValue(1));
5711       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5712     }
5713   }
5714
5715   if (N0.getOpcode() == ISD::SETCC) {
5716     if (!LegalOperations && VT.isVector() &&
5717         N0.getValueType().getVectorElementType() == MVT::i1) {
5718       EVT N0VT = N0.getOperand(0).getValueType();
5719       if (getSetCCResultType(N0VT) == N0.getValueType())
5720         return SDValue();
5721
5722       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5723       // Only do this before legalize for now.
5724       EVT EltVT = VT.getVectorElementType();
5725       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5726                                     DAG.getConstant(1, EltVT));
5727       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5728         // We know that the # elements of the results is the same as the
5729         // # elements of the compare (and the # elements of the compare result
5730         // for that matter).  Check to see that they are the same size.  If so,
5731         // we know that the element size of the sext'd result matches the
5732         // element size of the compare operands.
5733         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5734                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5735                                          N0.getOperand(1),
5736                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5737                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5738                                        OneOps));
5739
5740       // If the desired elements are smaller or larger than the source
5741       // elements we can use a matching integer vector type and then
5742       // truncate/sign extend
5743       EVT MatchingElementType =
5744         EVT::getIntegerVT(*DAG.getContext(),
5745                           N0VT.getScalarType().getSizeInBits());
5746       EVT MatchingVectorType =
5747         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5748                          N0VT.getVectorNumElements());
5749       SDValue VsetCC =
5750         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5751                       N0.getOperand(1),
5752                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5753       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5754                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5755                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5756     }
5757
5758     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5759     SDValue SCC =
5760       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5761                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5762                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5763     if (SCC.getNode()) return SCC;
5764   }
5765
5766   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5767   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5768       isa<ConstantSDNode>(N0.getOperand(1)) &&
5769       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5770       N0.hasOneUse()) {
5771     SDValue ShAmt = N0.getOperand(1);
5772     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5773     if (N0.getOpcode() == ISD::SHL) {
5774       SDValue InnerZExt = N0.getOperand(0);
5775       // If the original shl may be shifting out bits, do not perform this
5776       // transformation.
5777       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5778         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5779       if (ShAmtVal > KnownZeroBits)
5780         return SDValue();
5781     }
5782
5783     SDLoc DL(N);
5784
5785     // Ensure that the shift amount is wide enough for the shifted value.
5786     if (VT.getSizeInBits() >= 256)
5787       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5788
5789     return DAG.getNode(N0.getOpcode(), DL, VT,
5790                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5791                        ShAmt);
5792   }
5793
5794   return SDValue();
5795 }
5796
5797 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5798   SDValue N0 = N->getOperand(0);
5799   EVT VT = N->getValueType(0);
5800
5801   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5802                                               LegalOperations))
5803     return SDValue(Res, 0);
5804
5805   // fold (aext (aext x)) -> (aext x)
5806   // fold (aext (zext x)) -> (zext x)
5807   // fold (aext (sext x)) -> (sext x)
5808   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5809       N0.getOpcode() == ISD::ZERO_EXTEND ||
5810       N0.getOpcode() == ISD::SIGN_EXTEND)
5811     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5812
5813   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5814   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5815   if (N0.getOpcode() == ISD::TRUNCATE) {
5816     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5817     if (NarrowLoad.getNode()) {
5818       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5819       if (NarrowLoad.getNode() != N0.getNode()) {
5820         CombineTo(N0.getNode(), NarrowLoad);
5821         // CombineTo deleted the truncate, if needed, but not what's under it.
5822         AddToWorklist(oye);
5823       }
5824       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5825     }
5826   }
5827
5828   // fold (aext (truncate x))
5829   if (N0.getOpcode() == ISD::TRUNCATE) {
5830     SDValue TruncOp = N0.getOperand(0);
5831     if (TruncOp.getValueType() == VT)
5832       return TruncOp; // x iff x size == zext size.
5833     if (TruncOp.getValueType().bitsGT(VT))
5834       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5835     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5836   }
5837
5838   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5839   // if the trunc is not free.
5840   if (N0.getOpcode() == ISD::AND &&
5841       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5842       N0.getOperand(1).getOpcode() == ISD::Constant &&
5843       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5844                           N0.getValueType())) {
5845     SDValue X = N0.getOperand(0).getOperand(0);
5846     if (X.getValueType().bitsLT(VT)) {
5847       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5848     } else if (X.getValueType().bitsGT(VT)) {
5849       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5850     }
5851     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5852     Mask = Mask.zext(VT.getSizeInBits());
5853     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5854                        X, DAG.getConstant(Mask, VT));
5855   }
5856
5857   // fold (aext (load x)) -> (aext (truncate (extload x)))
5858   // None of the supported targets knows how to perform load and any_ext
5859   // on vectors in one instruction.  We only perform this transformation on
5860   // scalars.
5861   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5862       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5863       TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
5864     bool DoXform = true;
5865     SmallVector<SDNode*, 4> SetCCs;
5866     if (!N0.hasOneUse())
5867       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5868     if (DoXform) {
5869       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5870       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5871                                        LN0->getChain(),
5872                                        LN0->getBasePtr(), N0.getValueType(),
5873                                        LN0->getMemOperand());
5874       CombineTo(N, ExtLoad);
5875       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5876                                   N0.getValueType(), ExtLoad);
5877       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5878       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5879                       ISD::ANY_EXTEND);
5880       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5881     }
5882   }
5883
5884   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5885   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5886   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5887   if (N0.getOpcode() == ISD::LOAD &&
5888       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5889       N0.hasOneUse()) {
5890     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5891     ISD::LoadExtType ExtType = LN0->getExtensionType();
5892     EVT MemVT = LN0->getMemoryVT();
5893     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
5894       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5895                                        VT, LN0->getChain(), LN0->getBasePtr(),
5896                                        MemVT, LN0->getMemOperand());
5897       CombineTo(N, ExtLoad);
5898       CombineTo(N0.getNode(),
5899                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5900                             N0.getValueType(), ExtLoad),
5901                 ExtLoad.getValue(1));
5902       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5903     }
5904   }
5905
5906   if (N0.getOpcode() == ISD::SETCC) {
5907     // For vectors:
5908     // aext(setcc) -> vsetcc
5909     // aext(setcc) -> truncate(vsetcc)
5910     // aext(setcc) -> aext(vsetcc)
5911     // Only do this before legalize for now.
5912     if (VT.isVector() && !LegalOperations) {
5913       EVT N0VT = N0.getOperand(0).getValueType();
5914         // We know that the # elements of the results is the same as the
5915         // # elements of the compare (and the # elements of the compare result
5916         // for that matter).  Check to see that they are the same size.  If so,
5917         // we know that the element size of the sext'd result matches the
5918         // element size of the compare operands.
5919       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5920         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5921                              N0.getOperand(1),
5922                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5923       // If the desired elements are smaller or larger than the source
5924       // elements we can use a matching integer vector type and then
5925       // truncate/any extend
5926       else {
5927         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5928         SDValue VsetCC =
5929           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5930                         N0.getOperand(1),
5931                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5932         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5933       }
5934     }
5935
5936     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5937     SDValue SCC =
5938       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5939                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5940                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5941     if (SCC.getNode())
5942       return SCC;
5943   }
5944
5945   return SDValue();
5946 }
5947
5948 /// See if the specified operand can be simplified with the knowledge that only
5949 /// the bits specified by Mask are used.  If so, return the simpler operand,
5950 /// otherwise return a null SDValue.
5951 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5952   switch (V.getOpcode()) {
5953   default: break;
5954   case ISD::Constant: {
5955     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5956     assert(CV && "Const value should be ConstSDNode.");
5957     const APInt &CVal = CV->getAPIntValue();
5958     APInt NewVal = CVal & Mask;
5959     if (NewVal != CVal)
5960       return DAG.getConstant(NewVal, V.getValueType());
5961     break;
5962   }
5963   case ISD::OR:
5964   case ISD::XOR:
5965     // If the LHS or RHS don't contribute bits to the or, drop them.
5966     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5967       return V.getOperand(1);
5968     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5969       return V.getOperand(0);
5970     break;
5971   case ISD::SRL:
5972     // Only look at single-use SRLs.
5973     if (!V.getNode()->hasOneUse())
5974       break;
5975     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5976       // See if we can recursively simplify the LHS.
5977       unsigned Amt = RHSC->getZExtValue();
5978
5979       // Watch out for shift count overflow though.
5980       if (Amt >= Mask.getBitWidth()) break;
5981       APInt NewMask = Mask << Amt;
5982       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5983       if (SimplifyLHS.getNode())
5984         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5985                            SimplifyLHS, V.getOperand(1));
5986     }
5987   }
5988   return SDValue();
5989 }
5990
5991 /// If the result of a wider load is shifted to right of N  bits and then
5992 /// truncated to a narrower type and where N is a multiple of number of bits of
5993 /// the narrower type, transform it to a narrower load from address + N / num of
5994 /// bits of new type. If the result is to be extended, also fold the extension
5995 /// to form a extending load.
5996 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5997   unsigned Opc = N->getOpcode();
5998
5999   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
6000   SDValue N0 = N->getOperand(0);
6001   EVT VT = N->getValueType(0);
6002   EVT ExtVT = VT;
6003
6004   // This transformation isn't valid for vector loads.
6005   if (VT.isVector())
6006     return SDValue();
6007
6008   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
6009   // extended to VT.
6010   if (Opc == ISD::SIGN_EXTEND_INREG) {
6011     ExtType = ISD::SEXTLOAD;
6012     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
6013   } else if (Opc == ISD::SRL) {
6014     // Another special-case: SRL is basically zero-extending a narrower value.
6015     ExtType = ISD::ZEXTLOAD;
6016     N0 = SDValue(N, 0);
6017     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
6018     if (!N01) return SDValue();
6019     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
6020                               VT.getSizeInBits() - N01->getZExtValue());
6021   }
6022   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, VT, ExtVT))
6023     return SDValue();
6024
6025   unsigned EVTBits = ExtVT.getSizeInBits();
6026
6027   // Do not generate loads of non-round integer types since these can
6028   // be expensive (and would be wrong if the type is not byte sized).
6029   if (!ExtVT.isRound())
6030     return SDValue();
6031
6032   unsigned ShAmt = 0;
6033   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
6034     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6035       ShAmt = N01->getZExtValue();
6036       // Is the shift amount a multiple of size of VT?
6037       if ((ShAmt & (EVTBits-1)) == 0) {
6038         N0 = N0.getOperand(0);
6039         // Is the load width a multiple of size of VT?
6040         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
6041           return SDValue();
6042       }
6043
6044       // At this point, we must have a load or else we can't do the transform.
6045       if (!isa<LoadSDNode>(N0)) return SDValue();
6046
6047       // Because a SRL must be assumed to *need* to zero-extend the high bits
6048       // (as opposed to anyext the high bits), we can't combine the zextload
6049       // lowering of SRL and an sextload.
6050       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
6051         return SDValue();
6052
6053       // If the shift amount is larger than the input type then we're not
6054       // accessing any of the loaded bytes.  If the load was a zextload/extload
6055       // then the result of the shift+trunc is zero/undef (handled elsewhere).
6056       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
6057         return SDValue();
6058     }
6059   }
6060
6061   // If the load is shifted left (and the result isn't shifted back right),
6062   // we can fold the truncate through the shift.
6063   unsigned ShLeftAmt = 0;
6064   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6065       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6066     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6067       ShLeftAmt = N01->getZExtValue();
6068       N0 = N0.getOperand(0);
6069     }
6070   }
6071
6072   // If we haven't found a load, we can't narrow it.  Don't transform one with
6073   // multiple uses, this would require adding a new load.
6074   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6075     return SDValue();
6076
6077   // Don't change the width of a volatile load.
6078   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6079   if (LN0->isVolatile())
6080     return SDValue();
6081
6082   // Verify that we are actually reducing a load width here.
6083   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6084     return SDValue();
6085
6086   // For the transform to be legal, the load must produce only two values
6087   // (the value loaded and the chain).  Don't transform a pre-increment
6088   // load, for example, which produces an extra value.  Otherwise the
6089   // transformation is not equivalent, and the downstream logic to replace
6090   // uses gets things wrong.
6091   if (LN0->getNumValues() > 2)
6092     return SDValue();
6093
6094   // If the load that we're shrinking is an extload and we're not just
6095   // discarding the extension we can't simply shrink the load. Bail.
6096   // TODO: It would be possible to merge the extensions in some cases.
6097   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6098       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6099     return SDValue();
6100
6101   if (!TLI.shouldReduceLoadWidth(LN0, ExtType, ExtVT))
6102     return SDValue();
6103
6104   EVT PtrType = N0.getOperand(1).getValueType();
6105
6106   if (PtrType == MVT::Untyped || PtrType.isExtended())
6107     // It's not possible to generate a constant of extended or untyped type.
6108     return SDValue();
6109
6110   // For big endian targets, we need to adjust the offset to the pointer to
6111   // load the correct bytes.
6112   if (TLI.isBigEndian()) {
6113     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6114     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6115     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6116   }
6117
6118   uint64_t PtrOff = ShAmt / 8;
6119   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6120   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6121                                PtrType, LN0->getBasePtr(),
6122                                DAG.getConstant(PtrOff, PtrType));
6123   AddToWorklist(NewPtr.getNode());
6124
6125   SDValue Load;
6126   if (ExtType == ISD::NON_EXTLOAD)
6127     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6128                         LN0->getPointerInfo().getWithOffset(PtrOff),
6129                         LN0->isVolatile(), LN0->isNonTemporal(),
6130                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6131   else
6132     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6133                           LN0->getPointerInfo().getWithOffset(PtrOff),
6134                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6135                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6136
6137   // Replace the old load's chain with the new load's chain.
6138   WorklistRemover DeadNodes(*this);
6139   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6140
6141   // Shift the result left, if we've swallowed a left shift.
6142   SDValue Result = Load;
6143   if (ShLeftAmt != 0) {
6144     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6145     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6146       ShImmTy = VT;
6147     // If the shift amount is as large as the result size (but, presumably,
6148     // no larger than the source) then the useful bits of the result are
6149     // zero; we can't simply return the shortened shift, because the result
6150     // of that operation is undefined.
6151     if (ShLeftAmt >= VT.getSizeInBits())
6152       Result = DAG.getConstant(0, VT);
6153     else
6154       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6155                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6156   }
6157
6158   // Return the new loaded value.
6159   return Result;
6160 }
6161
6162 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6163   SDValue N0 = N->getOperand(0);
6164   SDValue N1 = N->getOperand(1);
6165   EVT VT = N->getValueType(0);
6166   EVT EVT = cast<VTSDNode>(N1)->getVT();
6167   unsigned VTBits = VT.getScalarType().getSizeInBits();
6168   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6169
6170   // fold (sext_in_reg c1) -> c1
6171   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6172     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6173
6174   // If the input is already sign extended, just drop the extension.
6175   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6176     return N0;
6177
6178   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6179   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6180       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6181     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6182                        N0.getOperand(0), N1);
6183
6184   // fold (sext_in_reg (sext x)) -> (sext x)
6185   // fold (sext_in_reg (aext x)) -> (sext x)
6186   // if x is small enough.
6187   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6188     SDValue N00 = N0.getOperand(0);
6189     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6190         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6191       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6192   }
6193
6194   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6195   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6196     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6197
6198   // fold operands of sext_in_reg based on knowledge that the top bits are not
6199   // demanded.
6200   if (SimplifyDemandedBits(SDValue(N, 0)))
6201     return SDValue(N, 0);
6202
6203   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6204   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6205   SDValue NarrowLoad = ReduceLoadWidth(N);
6206   if (NarrowLoad.getNode())
6207     return NarrowLoad;
6208
6209   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6210   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6211   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6212   if (N0.getOpcode() == ISD::SRL) {
6213     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6214       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6215         // We can turn this into an SRA iff the input to the SRL is already sign
6216         // extended enough.
6217         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6218         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6219           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6220                              N0.getOperand(0), N0.getOperand(1));
6221       }
6222   }
6223
6224   // fold (sext_inreg (extload x)) -> (sextload x)
6225   if (ISD::isEXTLoad(N0.getNode()) &&
6226       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6227       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6228       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6229        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6230     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6231     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6232                                      LN0->getChain(),
6233                                      LN0->getBasePtr(), EVT,
6234                                      LN0->getMemOperand());
6235     CombineTo(N, ExtLoad);
6236     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6237     AddToWorklist(ExtLoad.getNode());
6238     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6239   }
6240   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6241   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6242       N0.hasOneUse() &&
6243       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6244       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6245        TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, EVT))) {
6246     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6247     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6248                                      LN0->getChain(),
6249                                      LN0->getBasePtr(), EVT,
6250                                      LN0->getMemOperand());
6251     CombineTo(N, ExtLoad);
6252     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6253     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6254   }
6255
6256   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6257   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6258     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6259                                        N0.getOperand(1), false);
6260     if (BSwap.getNode())
6261       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6262                          BSwap, N1);
6263   }
6264
6265   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6266   // into a build_vector.
6267   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6268     SmallVector<SDValue, 8> Elts;
6269     unsigned NumElts = N0->getNumOperands();
6270     unsigned ShAmt = VTBits - EVTBits;
6271
6272     for (unsigned i = 0; i != NumElts; ++i) {
6273       SDValue Op = N0->getOperand(i);
6274       if (Op->getOpcode() == ISD::UNDEF) {
6275         Elts.push_back(Op);
6276         continue;
6277       }
6278
6279       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6280       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6281       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6282                                      Op.getValueType()));
6283     }
6284
6285     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6286   }
6287
6288   return SDValue();
6289 }
6290
6291 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6292   SDValue N0 = N->getOperand(0);
6293   EVT VT = N->getValueType(0);
6294   bool isLE = TLI.isLittleEndian();
6295
6296   // noop truncate
6297   if (N0.getValueType() == N->getValueType(0))
6298     return N0;
6299   // fold (truncate c1) -> c1
6300   if (isa<ConstantSDNode>(N0))
6301     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6302   // fold (truncate (truncate x)) -> (truncate x)
6303   if (N0.getOpcode() == ISD::TRUNCATE)
6304     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6305   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6306   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6307       N0.getOpcode() == ISD::SIGN_EXTEND ||
6308       N0.getOpcode() == ISD::ANY_EXTEND) {
6309     if (N0.getOperand(0).getValueType().bitsLT(VT))
6310       // if the source is smaller than the dest, we still need an extend
6311       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6312                          N0.getOperand(0));
6313     if (N0.getOperand(0).getValueType().bitsGT(VT))
6314       // if the source is larger than the dest, than we just need the truncate
6315       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6316     // if the source and dest are the same type, we can drop both the extend
6317     // and the truncate.
6318     return N0.getOperand(0);
6319   }
6320
6321   // Fold extract-and-trunc into a narrow extract. For example:
6322   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6323   //   i32 y = TRUNCATE(i64 x)
6324   //        -- becomes --
6325   //   v16i8 b = BITCAST (v2i64 val)
6326   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6327   //
6328   // Note: We only run this optimization after type legalization (which often
6329   // creates this pattern) and before operation legalization after which
6330   // we need to be more careful about the vector instructions that we generate.
6331   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6332       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6333
6334     EVT VecTy = N0.getOperand(0).getValueType();
6335     EVT ExTy = N0.getValueType();
6336     EVT TrTy = N->getValueType(0);
6337
6338     unsigned NumElem = VecTy.getVectorNumElements();
6339     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6340
6341     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6342     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6343
6344     SDValue EltNo = N0->getOperand(1);
6345     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6346       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6347       EVT IndexTy = TLI.getVectorIdxTy();
6348       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6349
6350       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6351                               NVT, N0.getOperand(0));
6352
6353       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6354                          SDLoc(N), TrTy, V,
6355                          DAG.getConstant(Index, IndexTy));
6356     }
6357   }
6358
6359   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6360   if (N0.getOpcode() == ISD::SELECT) {
6361     EVT SrcVT = N0.getValueType();
6362     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6363         TLI.isTruncateFree(SrcVT, VT)) {
6364       SDLoc SL(N0);
6365       SDValue Cond = N0.getOperand(0);
6366       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6367       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6368       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6369     }
6370   }
6371
6372   // Fold a series of buildvector, bitcast, and truncate if possible.
6373   // For example fold
6374   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6375   //   (2xi32 (buildvector x, y)).
6376   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6377       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6378       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6379       N0.getOperand(0).hasOneUse()) {
6380
6381     SDValue BuildVect = N0.getOperand(0);
6382     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6383     EVT TruncVecEltTy = VT.getVectorElementType();
6384
6385     // Check that the element types match.
6386     if (BuildVectEltTy == TruncVecEltTy) {
6387       // Now we only need to compute the offset of the truncated elements.
6388       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6389       unsigned TruncVecNumElts = VT.getVectorNumElements();
6390       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6391
6392       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6393              "Invalid number of elements");
6394
6395       SmallVector<SDValue, 8> Opnds;
6396       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6397         Opnds.push_back(BuildVect.getOperand(i));
6398
6399       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6400     }
6401   }
6402
6403   // See if we can simplify the input to this truncate through knowledge that
6404   // only the low bits are being used.
6405   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6406   // Currently we only perform this optimization on scalars because vectors
6407   // may have different active low bits.
6408   if (!VT.isVector()) {
6409     SDValue Shorter =
6410       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6411                                                VT.getSizeInBits()));
6412     if (Shorter.getNode())
6413       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6414   }
6415   // fold (truncate (load x)) -> (smaller load x)
6416   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6417   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6418     SDValue Reduced = ReduceLoadWidth(N);
6419     if (Reduced.getNode())
6420       return Reduced;
6421     // Handle the case where the load remains an extending load even
6422     // after truncation.
6423     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6424       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6425       if (!LN0->isVolatile() &&
6426           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6427         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6428                                          VT, LN0->getChain(), LN0->getBasePtr(),
6429                                          LN0->getMemoryVT(),
6430                                          LN0->getMemOperand());
6431         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6432         return NewLoad;
6433       }
6434     }
6435   }
6436   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6437   // where ... are all 'undef'.
6438   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6439     SmallVector<EVT, 8> VTs;
6440     SDValue V;
6441     unsigned Idx = 0;
6442     unsigned NumDefs = 0;
6443
6444     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6445       SDValue X = N0.getOperand(i);
6446       if (X.getOpcode() != ISD::UNDEF) {
6447         V = X;
6448         Idx = i;
6449         NumDefs++;
6450       }
6451       // Stop if more than one members are non-undef.
6452       if (NumDefs > 1)
6453         break;
6454       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6455                                      VT.getVectorElementType(),
6456                                      X.getValueType().getVectorNumElements()));
6457     }
6458
6459     if (NumDefs == 0)
6460       return DAG.getUNDEF(VT);
6461
6462     if (NumDefs == 1) {
6463       assert(V.getNode() && "The single defined operand is empty!");
6464       SmallVector<SDValue, 8> Opnds;
6465       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6466         if (i != Idx) {
6467           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6468           continue;
6469         }
6470         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6471         AddToWorklist(NV.getNode());
6472         Opnds.push_back(NV);
6473       }
6474       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6475     }
6476   }
6477
6478   // Simplify the operands using demanded-bits information.
6479   if (!VT.isVector() &&
6480       SimplifyDemandedBits(SDValue(N, 0)))
6481     return SDValue(N, 0);
6482
6483   return SDValue();
6484 }
6485
6486 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6487   SDValue Elt = N->getOperand(i);
6488   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6489     return Elt.getNode();
6490   return Elt.getOperand(Elt.getResNo()).getNode();
6491 }
6492
6493 /// build_pair (load, load) -> load
6494 /// if load locations are consecutive.
6495 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6496   assert(N->getOpcode() == ISD::BUILD_PAIR);
6497
6498   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6499   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6500   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6501       LD1->getAddressSpace() != LD2->getAddressSpace())
6502     return SDValue();
6503   EVT LD1VT = LD1->getValueType(0);
6504
6505   if (ISD::isNON_EXTLoad(LD2) &&
6506       LD2->hasOneUse() &&
6507       // If both are volatile this would reduce the number of volatile loads.
6508       // If one is volatile it might be ok, but play conservative and bail out.
6509       !LD1->isVolatile() &&
6510       !LD2->isVolatile() &&
6511       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6512     unsigned Align = LD1->getAlignment();
6513     unsigned NewAlign = TLI.getDataLayout()->
6514       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6515
6516     if (NewAlign <= Align &&
6517         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6518       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6519                          LD1->getBasePtr(), LD1->getPointerInfo(),
6520                          false, false, false, Align);
6521   }
6522
6523   return SDValue();
6524 }
6525
6526 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6527   SDValue N0 = N->getOperand(0);
6528   EVT VT = N->getValueType(0);
6529
6530   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6531   // Only do this before legalize, since afterward the target may be depending
6532   // on the bitconvert.
6533   // First check to see if this is all constant.
6534   if (!LegalTypes &&
6535       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6536       VT.isVector()) {
6537     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6538
6539     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6540     assert(!DestEltVT.isVector() &&
6541            "Element type of vector ValueType must not be vector!");
6542     if (isSimple)
6543       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6544   }
6545
6546   // If the input is a constant, let getNode fold it.
6547   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6548     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6549     if (Res.getNode() != N) {
6550       if (!LegalOperations ||
6551           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6552         return Res;
6553
6554       // Folding it resulted in an illegal node, and it's too late to
6555       // do that. Clean up the old node and forego the transformation.
6556       // Ideally this won't happen very often, because instcombine
6557       // and the earlier dagcombine runs (where illegal nodes are
6558       // permitted) should have folded most of them already.
6559       deleteAndRecombine(Res.getNode());
6560     }
6561   }
6562
6563   // (conv (conv x, t1), t2) -> (conv x, t2)
6564   if (N0.getOpcode() == ISD::BITCAST)
6565     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6566                        N0.getOperand(0));
6567
6568   // fold (conv (load x)) -> (load (conv*)x)
6569   // If the resultant load doesn't need a higher alignment than the original!
6570   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6571       // Do not change the width of a volatile load.
6572       !cast<LoadSDNode>(N0)->isVolatile() &&
6573       // Do not remove the cast if the types differ in endian layout.
6574       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6575       TLI.hasBigEndianPartOrdering(VT) &&
6576       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6577       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6578     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6579     unsigned Align = TLI.getDataLayout()->
6580       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6581     unsigned OrigAlign = LN0->getAlignment();
6582
6583     if (Align <= OrigAlign) {
6584       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6585                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6586                                  LN0->isVolatile(), LN0->isNonTemporal(),
6587                                  LN0->isInvariant(), OrigAlign,
6588                                  LN0->getAAInfo());
6589       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6590       return Load;
6591     }
6592   }
6593
6594   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6595   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6596   // This often reduces constant pool loads.
6597   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6598        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6599       N0.getNode()->hasOneUse() && VT.isInteger() &&
6600       !VT.isVector() && !N0.getValueType().isVector()) {
6601     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6602                                   N0.getOperand(0));
6603     AddToWorklist(NewConv.getNode());
6604
6605     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6606     if (N0.getOpcode() == ISD::FNEG)
6607       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6608                          NewConv, DAG.getConstant(SignBit, VT));
6609     assert(N0.getOpcode() == ISD::FABS);
6610     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6611                        NewConv, DAG.getConstant(~SignBit, VT));
6612   }
6613
6614   // fold (bitconvert (fcopysign cst, x)) ->
6615   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6616   // Note that we don't handle (copysign x, cst) because this can always be
6617   // folded to an fneg or fabs.
6618   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6619       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6620       VT.isInteger() && !VT.isVector()) {
6621     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6622     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6623     if (isTypeLegal(IntXVT)) {
6624       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6625                               IntXVT, N0.getOperand(1));
6626       AddToWorklist(X.getNode());
6627
6628       // If X has a different width than the result/lhs, sext it or truncate it.
6629       unsigned VTWidth = VT.getSizeInBits();
6630       if (OrigXWidth < VTWidth) {
6631         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6632         AddToWorklist(X.getNode());
6633       } else if (OrigXWidth > VTWidth) {
6634         // To get the sign bit in the right place, we have to shift it right
6635         // before truncating.
6636         X = DAG.getNode(ISD::SRL, SDLoc(X),
6637                         X.getValueType(), X,
6638                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6639         AddToWorklist(X.getNode());
6640         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6641         AddToWorklist(X.getNode());
6642       }
6643
6644       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6645       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6646                       X, DAG.getConstant(SignBit, VT));
6647       AddToWorklist(X.getNode());
6648
6649       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6650                                 VT, N0.getOperand(0));
6651       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6652                         Cst, DAG.getConstant(~SignBit, VT));
6653       AddToWorklist(Cst.getNode());
6654
6655       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6656     }
6657   }
6658
6659   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6660   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6661     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6662     if (CombineLD.getNode())
6663       return CombineLD;
6664   }
6665
6666   return SDValue();
6667 }
6668
6669 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6670   EVT VT = N->getValueType(0);
6671   return CombineConsecutiveLoads(N, VT);
6672 }
6673
6674 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6675 /// operands. DstEltVT indicates the destination element value type.
6676 SDValue DAGCombiner::
6677 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6678   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6679
6680   // If this is already the right type, we're done.
6681   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6682
6683   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6684   unsigned DstBitSize = DstEltVT.getSizeInBits();
6685
6686   // If this is a conversion of N elements of one type to N elements of another
6687   // type, convert each element.  This handles FP<->INT cases.
6688   if (SrcBitSize == DstBitSize) {
6689     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6690                               BV->getValueType(0).getVectorNumElements());
6691
6692     // Due to the FP element handling below calling this routine recursively,
6693     // we can end up with a scalar-to-vector node here.
6694     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6695       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6696                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6697                                      DstEltVT, BV->getOperand(0)));
6698
6699     SmallVector<SDValue, 8> Ops;
6700     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6701       SDValue Op = BV->getOperand(i);
6702       // If the vector element type is not legal, the BUILD_VECTOR operands
6703       // are promoted and implicitly truncated.  Make that explicit here.
6704       if (Op.getValueType() != SrcEltVT)
6705         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6706       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6707                                 DstEltVT, Op));
6708       AddToWorklist(Ops.back().getNode());
6709     }
6710     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6711   }
6712
6713   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6714   // handle annoying details of growing/shrinking FP values, we convert them to
6715   // int first.
6716   if (SrcEltVT.isFloatingPoint()) {
6717     // Convert the input float vector to a int vector where the elements are the
6718     // same sizes.
6719     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6720     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6721     SrcEltVT = IntVT;
6722   }
6723
6724   // Now we know the input is an integer vector.  If the output is a FP type,
6725   // convert to integer first, then to FP of the right size.
6726   if (DstEltVT.isFloatingPoint()) {
6727     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6728     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6729
6730     // Next, convert to FP elements of the same size.
6731     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6732   }
6733
6734   // Okay, we know the src/dst types are both integers of differing types.
6735   // Handling growing first.
6736   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6737   if (SrcBitSize < DstBitSize) {
6738     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6739
6740     SmallVector<SDValue, 8> Ops;
6741     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6742          i += NumInputsPerOutput) {
6743       bool isLE = TLI.isLittleEndian();
6744       APInt NewBits = APInt(DstBitSize, 0);
6745       bool EltIsUndef = true;
6746       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6747         // Shift the previously computed bits over.
6748         NewBits <<= SrcBitSize;
6749         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6750         if (Op.getOpcode() == ISD::UNDEF) continue;
6751         EltIsUndef = false;
6752
6753         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6754                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6755       }
6756
6757       if (EltIsUndef)
6758         Ops.push_back(DAG.getUNDEF(DstEltVT));
6759       else
6760         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6761     }
6762
6763     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6764     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6765   }
6766
6767   // Finally, this must be the case where we are shrinking elements: each input
6768   // turns into multiple outputs.
6769   bool isS2V = ISD::isScalarToVector(BV);
6770   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6771   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6772                             NumOutputsPerInput*BV->getNumOperands());
6773   SmallVector<SDValue, 8> Ops;
6774
6775   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6776     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6777       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6778         Ops.push_back(DAG.getUNDEF(DstEltVT));
6779       continue;
6780     }
6781
6782     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6783                   getAPIntValue().zextOrTrunc(SrcBitSize);
6784
6785     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6786       APInt ThisVal = OpVal.trunc(DstBitSize);
6787       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6788       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6789         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6790         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6791                            Ops[0]);
6792       OpVal = OpVal.lshr(DstBitSize);
6793     }
6794
6795     // For big endian targets, swap the order of the pieces of each element.
6796     if (TLI.isBigEndian())
6797       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6798   }
6799
6800   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6801 }
6802
6803 SDValue DAGCombiner::visitFADD(SDNode *N) {
6804   SDValue N0 = N->getOperand(0);
6805   SDValue N1 = N->getOperand(1);
6806   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6807   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6808   EVT VT = N->getValueType(0);
6809   const TargetOptions &Options = DAG.getTarget().Options;
6810
6811   // fold vector ops
6812   if (VT.isVector()) {
6813     SDValue FoldedVOp = SimplifyVBinOp(N);
6814     if (FoldedVOp.getNode()) return FoldedVOp;
6815   }
6816
6817   // fold (fadd c1, c2) -> c1 + c2
6818   if (N0CFP && N1CFP)
6819     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6820
6821   // canonicalize constant to RHS
6822   if (N0CFP && !N1CFP)
6823     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6824
6825   // fold (fadd A, (fneg B)) -> (fsub A, B)
6826   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6827       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6828     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6829                        GetNegatedExpression(N1, DAG, LegalOperations));
6830
6831   // fold (fadd (fneg A), B) -> (fsub B, A)
6832   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6833       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6834     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6835                        GetNegatedExpression(N0, DAG, LegalOperations));
6836
6837   // If 'unsafe math' is enabled, fold lots of things.
6838   if (Options.UnsafeFPMath) {
6839     // No FP constant should be created after legalization as Instruction
6840     // Selection pass has a hard time dealing with FP constants.
6841     bool AllowNewConst = (Level < AfterLegalizeDAG);
6842
6843     // fold (fadd A, 0) -> A
6844     if (N1CFP && N1CFP->getValueAPF().isZero())
6845       return N0;
6846
6847     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6848     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6849         isa<ConstantFPSDNode>(N0.getOperand(1)))
6850       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6851                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6852                                      N0.getOperand(1), N1));
6853
6854     // If allowed, fold (fadd (fneg x), x) -> 0.0
6855     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6856       return DAG.getConstantFP(0.0, VT);
6857
6858     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6859     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6860       return DAG.getConstantFP(0.0, VT);
6861
6862     // We can fold chains of FADD's of the same value into multiplications.
6863     // This transform is not safe in general because we are reducing the number
6864     // of rounding steps.
6865     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6866       if (N0.getOpcode() == ISD::FMUL) {
6867         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6868         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6869
6870         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6871         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6872           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6873                                        SDValue(CFP01, 0),
6874                                        DAG.getConstantFP(1.0, VT));
6875           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6876         }
6877
6878         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6879         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6880             N1.getOperand(0) == N1.getOperand(1) &&
6881             N0.getOperand(0) == N1.getOperand(0)) {
6882           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6883                                        SDValue(CFP01, 0),
6884                                        DAG.getConstantFP(2.0, VT));
6885           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6886                              N0.getOperand(0), NewCFP);
6887         }
6888       }
6889
6890       if (N1.getOpcode() == ISD::FMUL) {
6891         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6892         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6893
6894         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6895         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6896           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6897                                        SDValue(CFP11, 0),
6898                                        DAG.getConstantFP(1.0, VT));
6899           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6900         }
6901
6902         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6903         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6904             N0.getOperand(0) == N0.getOperand(1) &&
6905             N1.getOperand(0) == N0.getOperand(0)) {
6906           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6907                                        SDValue(CFP11, 0),
6908                                        DAG.getConstantFP(2.0, VT));
6909           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6910         }
6911       }
6912
6913       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6914         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6915         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6916         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6917             (N0.getOperand(0) == N1))
6918           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6919                              N1, DAG.getConstantFP(3.0, VT));
6920       }
6921
6922       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6923         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6924         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6925         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6926             N1.getOperand(0) == N0)
6927           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6928                              N0, DAG.getConstantFP(3.0, VT));
6929       }
6930
6931       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6932       if (AllowNewConst &&
6933           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6934           N0.getOperand(0) == N0.getOperand(1) &&
6935           N1.getOperand(0) == N1.getOperand(1) &&
6936           N0.getOperand(0) == N1.getOperand(0))
6937         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6938                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6939     }
6940   } // enable-unsafe-fp-math
6941
6942   // FADD -> FMA combines:
6943   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6944       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6945       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6946
6947     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6948     if (N0.getOpcode() == ISD::FMUL &&
6949         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6950       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6951                          N0.getOperand(0), N0.getOperand(1), N1);
6952
6953     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6954     // Note: Commutes FADD operands.
6955     if (N1.getOpcode() == ISD::FMUL &&
6956         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6957       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6958                          N1.getOperand(0), N1.getOperand(1), N0);
6959
6960     // More folding opportunities when target permits.
6961     if (TLI.enableAggressiveFMAFusion(VT)) {
6962       // fold (fadd (fma x, y, (fmul u, v)), z) -> (fma x, y (fma u, v, z))
6963       if (N0.getOpcode() == ISD::FMA &&
6964           N0.getOperand(2).getOpcode() == ISD::FMUL)
6965         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6966                            N0.getOperand(0), N0.getOperand(1),
6967                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
6968                                        N0.getOperand(2).getOperand(0),
6969                                        N0.getOperand(2).getOperand(1),
6970                                        N1));
6971
6972       // fold (fadd x, (fma y, z, (fmul u, v)) -> (fma y, z (fma u, v, x))
6973       if (N1->getOpcode() == ISD::FMA &&
6974           N1.getOperand(2).getOpcode() == ISD::FMUL)
6975         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6976                            N1.getOperand(0), N1.getOperand(1),
6977                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
6978                                        N1.getOperand(2).getOperand(0),
6979                                        N1.getOperand(2).getOperand(1),
6980                                        N0));
6981
6982       // Remove FP_EXTEND when there is an opportunity to combine. This is
6983       // legal here since extra precision is allowed.
6984
6985       // fold (fadd (fpext (fmul x, y)), z) -> (fma x, y, z)
6986       if (N0.getOpcode() == ISD::FP_EXTEND) {
6987         SDValue N00 = N0.getOperand(0);
6988         if (N00.getOpcode() == ISD::FMUL)
6989           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6990                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6991                                          N00.getOperand(0)),
6992                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
6993                                          N00.getOperand(1)), N1);
6994       }
6995
6996       // fold (fadd x, (fpext (fmul y, z)), z) -> (fma y, z, x)
6997       // Note: Commutes FADD operands.
6998       if (N1.getOpcode() == ISD::FP_EXTEND) {
6999         SDValue N10 = N1.getOperand(0);
7000         if (N10.getOpcode() == ISD::FMUL)
7001           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7002                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7003                                          N10.getOperand(0)),
7004                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7005                                          N10.getOperand(1)), N0);
7006       }
7007     }
7008   }
7009
7010   return SDValue();
7011 }
7012
7013 SDValue DAGCombiner::visitFSUB(SDNode *N) {
7014   SDValue N0 = N->getOperand(0);
7015   SDValue N1 = N->getOperand(1);
7016   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7017   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7018   EVT VT = N->getValueType(0);
7019   SDLoc dl(N);
7020   const TargetOptions &Options = DAG.getTarget().Options;
7021
7022   // fold vector ops
7023   if (VT.isVector()) {
7024     SDValue FoldedVOp = SimplifyVBinOp(N);
7025     if (FoldedVOp.getNode()) return FoldedVOp;
7026   }
7027
7028   // fold (fsub c1, c2) -> c1-c2
7029   if (N0CFP && N1CFP)
7030     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
7031
7032   // fold (fsub A, (fneg B)) -> (fadd A, B)
7033   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7034     return DAG.getNode(ISD::FADD, dl, VT, N0,
7035                        GetNegatedExpression(N1, DAG, LegalOperations));
7036
7037   // If 'unsafe math' is enabled, fold lots of things.
7038   if (Options.UnsafeFPMath) {
7039     // (fsub A, 0) -> A
7040     if (N1CFP && N1CFP->getValueAPF().isZero())
7041       return N0;
7042
7043     // (fsub 0, B) -> -B
7044     if (N0CFP && N0CFP->getValueAPF().isZero()) {
7045       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
7046         return GetNegatedExpression(N1, DAG, LegalOperations);
7047       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7048         return DAG.getNode(ISD::FNEG, dl, VT, N1);
7049     }
7050
7051     // (fsub x, x) -> 0.0
7052     if (N0 == N1)
7053       return DAG.getConstantFP(0.0f, VT);
7054
7055     // (fsub x, (fadd x, y)) -> (fneg y)
7056     // (fsub x, (fadd y, x)) -> (fneg y)
7057     if (N1.getOpcode() == ISD::FADD) {
7058       SDValue N10 = N1->getOperand(0);
7059       SDValue N11 = N1->getOperand(1);
7060
7061       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
7062         return GetNegatedExpression(N11, DAG, LegalOperations);
7063
7064       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
7065         return GetNegatedExpression(N10, DAG, LegalOperations);
7066     }
7067   }
7068
7069   // FSUB -> FMA combines:
7070   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
7071       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
7072       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
7073
7074     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
7075     if (N0.getOpcode() == ISD::FMUL &&
7076         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7077       return DAG.getNode(ISD::FMA, dl, VT,
7078                          N0.getOperand(0), N0.getOperand(1),
7079                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7080
7081     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
7082     // Note: Commutes FSUB operands.
7083     if (N1.getOpcode() == ISD::FMUL &&
7084         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
7085       return DAG.getNode(ISD::FMA, dl, VT,
7086                          DAG.getNode(ISD::FNEG, dl, VT,
7087                          N1.getOperand(0)),
7088                          N1.getOperand(1), N0);
7089
7090     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
7091     if (N0.getOpcode() == ISD::FNEG &&
7092         N0.getOperand(0).getOpcode() == ISD::FMUL &&
7093         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
7094             TLI.enableAggressiveFMAFusion(VT))) {
7095       SDValue N00 = N0.getOperand(0).getOperand(0);
7096       SDValue N01 = N0.getOperand(0).getOperand(1);
7097       return DAG.getNode(ISD::FMA, dl, VT,
7098                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
7099                          DAG.getNode(ISD::FNEG, dl, VT, N1));
7100     }
7101
7102     // More folding opportunities when target permits.
7103     if (TLI.enableAggressiveFMAFusion(VT)) {
7104
7105       // fold (fsub (fma x, y, (fmul u, v)), z)
7106       //   -> (fma x, y (fma u, v, (fneg z)))
7107       if (N0.getOpcode() == ISD::FMA &&
7108           N0.getOperand(2).getOpcode() == ISD::FMUL)
7109         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7110                            N0.getOperand(0), N0.getOperand(1),
7111                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7112                                        N0.getOperand(2).getOperand(0),
7113                                        N0.getOperand(2).getOperand(1),
7114                                        DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7115                                                    N1)));
7116
7117       // fold (fsub x, (fma y, z, (fmul u, v)))
7118       //   -> (fma (fneg y), z, (fma (fneg u), v, x))
7119       if (N1.getOpcode() == ISD::FMA &&
7120           N1.getOperand(2).getOpcode() == ISD::FMUL) {
7121         SDValue N20 = N1.getOperand(2).getOperand(0);
7122         SDValue N21 = N1.getOperand(2).getOperand(1);
7123         return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7124                            DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7125                                        N1.getOperand(0)),
7126                            N1.getOperand(1),
7127                            DAG.getNode(ISD::FMA, SDLoc(N), VT,
7128                                        DAG.getNode(ISD::FNEG, SDLoc(N),  VT,
7129                                                    N20),
7130                                        N21, N0));
7131       }
7132
7133       // Remove FP_EXTEND when there is an opportunity to combine. This is
7134       // legal here since extra precision is allowed.
7135
7136       // fold (fsub (fpext (fmul x, y)), z) -> (fma x, y, (fneg z))
7137       if (N0.getOpcode() == ISD::FP_EXTEND) {
7138         SDValue N00 = N0.getOperand(0);
7139         if (N00.getOpcode() == ISD::FMUL)
7140           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7141                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7142                                          N00.getOperand(0)),
7143                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7144                                          N00.getOperand(1)),
7145                              DAG.getNode(ISD::FNEG, SDLoc(N), VT, N1));
7146       }
7147
7148       // fold (fsub x, (fpext (fmul y, z))) -> (fma (fneg y), z, x)
7149       // Note: Commutes FSUB operands.
7150       if (N1.getOpcode() == ISD::FP_EXTEND) {
7151         SDValue N10 = N1.getOperand(0);
7152         if (N10.getOpcode() == ISD::FMUL)
7153           return DAG.getNode(ISD::FMA, SDLoc(N), VT,
7154                              DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7155                                          DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7156                                                      VT, N10.getOperand(0))),
7157                              DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7158                                          N10.getOperand(1)),
7159                              N0);
7160       }
7161
7162       // fold (fsub (fpext (fneg (fmul, x, y))), z)
7163       //   -> (fma (fneg x), y, (fneg z))
7164       if (N0.getOpcode() == ISD::FP_EXTEND) {
7165         SDValue N00 = N0.getOperand(0);
7166         if (N00.getOpcode() == ISD::FNEG) {
7167           SDValue N000 = N00.getOperand(0);
7168           if (N000.getOpcode() == ISD::FMUL) {
7169             return DAG.getNode(ISD::FMA, dl, VT,
7170                                DAG.getNode(ISD::FNEG, dl, VT,
7171                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7172                                                        VT, N000.getOperand(0))),
7173                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7174                                            N000.getOperand(1)),
7175                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7176           }
7177         }
7178       }
7179
7180       // fold (fsub (fneg (fpext (fmul, x, y))), z)
7181       //   -> (fma (fneg x), y, (fneg z))
7182       if (N0.getOpcode() == ISD::FNEG) {
7183         SDValue N00 = N0.getOperand(0);
7184         if (N00.getOpcode() == ISD::FP_EXTEND) {
7185           SDValue N000 = N00.getOperand(0);
7186           if (N000.getOpcode() == ISD::FMUL) {
7187             return DAG.getNode(ISD::FMA, dl, VT,
7188                                DAG.getNode(ISD::FNEG, dl, VT,
7189                                            DAG.getNode(ISD::FP_EXTEND, SDLoc(N),
7190                                            VT, N000.getOperand(0))),
7191                                DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT,
7192                                            N000.getOperand(1)),
7193                                DAG.getNode(ISD::FNEG, dl, VT, N1));
7194           }
7195         }
7196       }
7197     }
7198   }
7199
7200   return SDValue();
7201 }
7202
7203 SDValue DAGCombiner::visitFMUL(SDNode *N) {
7204   SDValue N0 = N->getOperand(0);
7205   SDValue N1 = N->getOperand(1);
7206   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
7207   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
7208   EVT VT = N->getValueType(0);
7209   const TargetOptions &Options = DAG.getTarget().Options;
7210
7211   // fold vector ops
7212   if (VT.isVector()) {
7213     // This just handles C1 * C2 for vectors. Other vector folds are below.
7214     SDValue FoldedVOp = SimplifyVBinOp(N);
7215     if (FoldedVOp.getNode())
7216       return FoldedVOp;
7217     // Canonicalize vector constant to RHS.
7218     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7219         N1.getOpcode() != ISD::BUILD_VECTOR)
7220       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7221         if (BV0->isConstant())
7222           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7223   }
7224
7225   // fold (fmul c1, c2) -> c1*c2
7226   if (N0CFP && N1CFP)
7227     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7228
7229   // canonicalize constant to RHS
7230   if (N0CFP && !N1CFP)
7231     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7232
7233   // fold (fmul A, 1.0) -> A
7234   if (N1CFP && N1CFP->isExactlyValue(1.0))
7235     return N0;
7236
7237   if (Options.UnsafeFPMath) {
7238     // fold (fmul A, 0) -> 0
7239     if (N1CFP && N1CFP->getValueAPF().isZero())
7240       return N1;
7241
7242     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7243     if (N0.getOpcode() == ISD::FMUL) {
7244       // Fold scalars or any vector constants (not just splats).
7245       // This fold is done in general by InstCombine, but extra fmul insts
7246       // may have been generated during lowering.
7247       SDValue N01 = N0.getOperand(1);
7248       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7249       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7250       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7251           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7252         SDLoc SL(N);
7253         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7254         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7255       }
7256     }
7257
7258     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7259     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7260     // during an early run of DAGCombiner can prevent folding with fmuls
7261     // inserted during lowering.
7262     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7263       SDLoc SL(N);
7264       const SDValue Two = DAG.getConstantFP(2.0, VT);
7265       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7266       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7267     }
7268   }
7269
7270   // fold (fmul X, 2.0) -> (fadd X, X)
7271   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7272     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7273
7274   // fold (fmul X, -1.0) -> (fneg X)
7275   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7276     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7277       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7278
7279   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7280   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7281     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7282       // Both can be negated for free, check to see if at least one is cheaper
7283       // negated.
7284       if (LHSNeg == 2 || RHSNeg == 2)
7285         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7286                            GetNegatedExpression(N0, DAG, LegalOperations),
7287                            GetNegatedExpression(N1, DAG, LegalOperations));
7288     }
7289   }
7290
7291   return SDValue();
7292 }
7293
7294 SDValue DAGCombiner::visitFMA(SDNode *N) {
7295   SDValue N0 = N->getOperand(0);
7296   SDValue N1 = N->getOperand(1);
7297   SDValue N2 = N->getOperand(2);
7298   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7299   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7300   EVT VT = N->getValueType(0);
7301   SDLoc dl(N);
7302   const TargetOptions &Options = DAG.getTarget().Options;
7303
7304   // Constant fold FMA.
7305   if (isa<ConstantFPSDNode>(N0) &&
7306       isa<ConstantFPSDNode>(N1) &&
7307       isa<ConstantFPSDNode>(N2)) {
7308     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7309   }
7310
7311   if (Options.UnsafeFPMath) {
7312     if (N0CFP && N0CFP->isZero())
7313       return N2;
7314     if (N1CFP && N1CFP->isZero())
7315       return N2;
7316   }
7317   if (N0CFP && N0CFP->isExactlyValue(1.0))
7318     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7319   if (N1CFP && N1CFP->isExactlyValue(1.0))
7320     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7321
7322   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7323   if (N0CFP && !N1CFP)
7324     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7325
7326   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7327   if (Options.UnsafeFPMath && N1CFP &&
7328       N2.getOpcode() == ISD::FMUL &&
7329       N0 == N2.getOperand(0) &&
7330       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7331     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7332                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7333   }
7334
7335
7336   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7337   if (Options.UnsafeFPMath &&
7338       N0.getOpcode() == ISD::FMUL && N1CFP &&
7339       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7340     return DAG.getNode(ISD::FMA, dl, VT,
7341                        N0.getOperand(0),
7342                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7343                        N2);
7344   }
7345
7346   // (fma x, 1, y) -> (fadd x, y)
7347   // (fma x, -1, y) -> (fadd (fneg x), y)
7348   if (N1CFP) {
7349     if (N1CFP->isExactlyValue(1.0))
7350       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7351
7352     if (N1CFP->isExactlyValue(-1.0) &&
7353         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7354       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7355       AddToWorklist(RHSNeg.getNode());
7356       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7357     }
7358   }
7359
7360   // (fma x, c, x) -> (fmul x, (c+1))
7361   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7362     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7363                        DAG.getNode(ISD::FADD, dl, VT,
7364                                    N1, DAG.getConstantFP(1.0, VT)));
7365
7366   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7367   if (Options.UnsafeFPMath && N1CFP &&
7368       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7369     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7370                        DAG.getNode(ISD::FADD, dl, VT,
7371                                    N1, DAG.getConstantFP(-1.0, VT)));
7372
7373
7374   return SDValue();
7375 }
7376
7377 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7378   SDValue N0 = N->getOperand(0);
7379   SDValue N1 = N->getOperand(1);
7380   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7381   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7382   EVT VT = N->getValueType(0);
7383   SDLoc DL(N);
7384   const TargetOptions &Options = DAG.getTarget().Options;
7385
7386   // fold vector ops
7387   if (VT.isVector()) {
7388     SDValue FoldedVOp = SimplifyVBinOp(N);
7389     if (FoldedVOp.getNode()) return FoldedVOp;
7390   }
7391
7392   // fold (fdiv c1, c2) -> c1/c2
7393   if (N0CFP && N1CFP)
7394     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7395
7396   if (Options.UnsafeFPMath) {
7397     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7398     if (N1CFP) {
7399       // Compute the reciprocal 1.0 / c2.
7400       APFloat N1APF = N1CFP->getValueAPF();
7401       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7402       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7403       // Only do the transform if the reciprocal is a legal fp immediate that
7404       // isn't too nasty (eg NaN, denormal, ...).
7405       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7406           (!LegalOperations ||
7407            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7408            // backend)... we should handle this gracefully after Legalize.
7409            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7410            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7411            TLI.isFPImmLegal(Recip, VT)))
7412         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7413                            DAG.getConstantFP(Recip, VT));
7414     }
7415
7416     // If this FDIV is part of a reciprocal square root, it may be folded
7417     // into a target-specific square root estimate instruction.
7418     if (N1.getOpcode() == ISD::FSQRT) {
7419       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7420         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7421       }
7422     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7423                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7424       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7425         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7426         AddToWorklist(RV.getNode());
7427         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7428       }
7429     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7430                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7431       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7432         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7433         AddToWorklist(RV.getNode());
7434         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7435       }
7436     } else if (N1.getOpcode() == ISD::FMUL) {
7437       // Look through an FMUL. Even though this won't remove the FDIV directly,
7438       // it's still worthwhile to get rid of the FSQRT if possible.
7439       SDValue SqrtOp;
7440       SDValue OtherOp;
7441       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7442         SqrtOp = N1.getOperand(0);
7443         OtherOp = N1.getOperand(1);
7444       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7445         SqrtOp = N1.getOperand(1);
7446         OtherOp = N1.getOperand(0);
7447       }
7448       if (SqrtOp.getNode()) {
7449         // We found a FSQRT, so try to make this fold:
7450         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7451         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7452           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7453           AddToWorklist(RV.getNode());
7454           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7455         }
7456       }
7457     }
7458
7459     // Fold into a reciprocal estimate and multiply instead of a real divide.
7460     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7461       AddToWorklist(RV.getNode());
7462       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7463     }
7464   }
7465
7466   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7467   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7468     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7469       // Both can be negated for free, check to see if at least one is cheaper
7470       // negated.
7471       if (LHSNeg == 2 || RHSNeg == 2)
7472         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7473                            GetNegatedExpression(N0, DAG, LegalOperations),
7474                            GetNegatedExpression(N1, DAG, LegalOperations));
7475     }
7476   }
7477
7478   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7479   // reciprocal.
7480   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7481   // Notice that this is not always beneficial. One reason is different target
7482   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7483   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7484   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7485   if (Options.UnsafeFPMath) {
7486     // Skip if current node is a reciprocal.
7487     if (N0CFP && N0CFP->isExactlyValue(1.0))
7488       return SDValue();
7489
7490     SmallVector<SDNode *, 4> Users;
7491     // Find all FDIV users of the same divisor.
7492     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7493                               UE = N1.getNode()->use_end();
7494          UI != UE; ++UI) {
7495       SDNode *User = UI.getUse().getUser();
7496       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7497         Users.push_back(User);
7498     }
7499
7500     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7501       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7502       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7503
7504       // Dividend / Divisor -> Dividend * Reciprocal
7505       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7506         if ((*I)->getOperand(0) != FPOne) {
7507           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7508                                         (*I)->getOperand(0), Reciprocal);
7509           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7510         }
7511       }
7512       return SDValue();
7513     }
7514   }
7515
7516   return SDValue();
7517 }
7518
7519 SDValue DAGCombiner::visitFREM(SDNode *N) {
7520   SDValue N0 = N->getOperand(0);
7521   SDValue N1 = N->getOperand(1);
7522   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7523   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7524   EVT VT = N->getValueType(0);
7525
7526   // fold (frem c1, c2) -> fmod(c1,c2)
7527   if (N0CFP && N1CFP)
7528     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7529
7530   return SDValue();
7531 }
7532
7533 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7534   if (DAG.getTarget().Options.UnsafeFPMath) {
7535     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7536     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7537       EVT VT = RV.getValueType();
7538       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7539       AddToWorklist(RV.getNode());
7540
7541       // Unfortunately, RV is now NaN if the input was exactly 0.
7542       // Select out this case and force the answer to 0.
7543       SDValue Zero = DAG.getConstantFP(0.0, VT);
7544       SDValue ZeroCmp =
7545         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7546                      N->getOperand(0), Zero, ISD::SETEQ);
7547       AddToWorklist(ZeroCmp.getNode());
7548       AddToWorklist(RV.getNode());
7549
7550       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7551                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7552       return RV;
7553     }
7554   }
7555   return SDValue();
7556 }
7557
7558 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7559   SDValue N0 = N->getOperand(0);
7560   SDValue N1 = N->getOperand(1);
7561   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7562   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7563   EVT VT = N->getValueType(0);
7564
7565   if (N0CFP && N1CFP)  // Constant fold
7566     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7567
7568   if (N1CFP) {
7569     const APFloat& V = N1CFP->getValueAPF();
7570     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7571     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7572     if (!V.isNegative()) {
7573       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7574         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7575     } else {
7576       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7577         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7578                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7579     }
7580   }
7581
7582   // copysign(fabs(x), y) -> copysign(x, y)
7583   // copysign(fneg(x), y) -> copysign(x, y)
7584   // copysign(copysign(x,z), y) -> copysign(x, y)
7585   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7586       N0.getOpcode() == ISD::FCOPYSIGN)
7587     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7588                        N0.getOperand(0), N1);
7589
7590   // copysign(x, abs(y)) -> abs(x)
7591   if (N1.getOpcode() == ISD::FABS)
7592     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7593
7594   // copysign(x, copysign(y,z)) -> copysign(x, z)
7595   if (N1.getOpcode() == ISD::FCOPYSIGN)
7596     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7597                        N0, N1.getOperand(1));
7598
7599   // copysign(x, fp_extend(y)) -> copysign(x, y)
7600   // copysign(x, fp_round(y)) -> copysign(x, y)
7601   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7602     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7603                        N0, N1.getOperand(0));
7604
7605   return SDValue();
7606 }
7607
7608 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7609   SDValue N0 = N->getOperand(0);
7610   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7611   EVT VT = N->getValueType(0);
7612   EVT OpVT = N0.getValueType();
7613
7614   // fold (sint_to_fp c1) -> c1fp
7615   if (N0C &&
7616       // ...but only if the target supports immediate floating-point values
7617       (!LegalOperations ||
7618        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7619     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7620
7621   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7622   // but UINT_TO_FP is legal on this target, try to convert.
7623   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7624       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7625     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7626     if (DAG.SignBitIsZero(N0))
7627       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7628   }
7629
7630   // The next optimizations are desirable only if SELECT_CC can be lowered.
7631   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7632     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7633     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7634         !VT.isVector() &&
7635         (!LegalOperations ||
7636          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7637       SDValue Ops[] =
7638         { N0.getOperand(0), N0.getOperand(1),
7639           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7640           N0.getOperand(2) };
7641       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7642     }
7643
7644     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7645     //      (select_cc x, y, 1.0, 0.0,, cc)
7646     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7647         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7648         (!LegalOperations ||
7649          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7650       SDValue Ops[] =
7651         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7652           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7653           N0.getOperand(0).getOperand(2) };
7654       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7655     }
7656   }
7657
7658   return SDValue();
7659 }
7660
7661 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7662   SDValue N0 = N->getOperand(0);
7663   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7664   EVT VT = N->getValueType(0);
7665   EVT OpVT = N0.getValueType();
7666
7667   // fold (uint_to_fp c1) -> c1fp
7668   if (N0C &&
7669       // ...but only if the target supports immediate floating-point values
7670       (!LegalOperations ||
7671        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7672     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7673
7674   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7675   // but SINT_TO_FP is legal on this target, try to convert.
7676   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7677       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7678     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7679     if (DAG.SignBitIsZero(N0))
7680       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7681   }
7682
7683   // The next optimizations are desirable only if SELECT_CC can be lowered.
7684   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7685     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7686
7687     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7688         (!LegalOperations ||
7689          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7690       SDValue Ops[] =
7691         { N0.getOperand(0), N0.getOperand(1),
7692           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7693           N0.getOperand(2) };
7694       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7695     }
7696   }
7697
7698   return SDValue();
7699 }
7700
7701 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7702   SDValue N0 = N->getOperand(0);
7703   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7704   EVT VT = N->getValueType(0);
7705
7706   // fold (fp_to_sint c1fp) -> c1
7707   if (N0CFP)
7708     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7709
7710   return SDValue();
7711 }
7712
7713 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7714   SDValue N0 = N->getOperand(0);
7715   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7716   EVT VT = N->getValueType(0);
7717
7718   // fold (fp_to_uint c1fp) -> c1
7719   if (N0CFP)
7720     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7721
7722   return SDValue();
7723 }
7724
7725 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7726   SDValue N0 = N->getOperand(0);
7727   SDValue N1 = N->getOperand(1);
7728   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7729   EVT VT = N->getValueType(0);
7730
7731   // fold (fp_round c1fp) -> c1fp
7732   if (N0CFP)
7733     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7734
7735   // fold (fp_round (fp_extend x)) -> x
7736   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7737     return N0.getOperand(0);
7738
7739   // fold (fp_round (fp_round x)) -> (fp_round x)
7740   if (N0.getOpcode() == ISD::FP_ROUND) {
7741     // This is a value preserving truncation if both round's are.
7742     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7743                    N0.getNode()->getConstantOperandVal(1) == 1;
7744     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7745                        DAG.getIntPtrConstant(IsTrunc));
7746   }
7747
7748   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7749   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7750     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7751                               N0.getOperand(0), N1);
7752     AddToWorklist(Tmp.getNode());
7753     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7754                        Tmp, N0.getOperand(1));
7755   }
7756
7757   return SDValue();
7758 }
7759
7760 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7761   SDValue N0 = N->getOperand(0);
7762   EVT VT = N->getValueType(0);
7763   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7764   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7765
7766   // fold (fp_round_inreg c1fp) -> c1fp
7767   if (N0CFP && isTypeLegal(EVT)) {
7768     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7769     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7770   }
7771
7772   return SDValue();
7773 }
7774
7775 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7776   SDValue N0 = N->getOperand(0);
7777   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7778   EVT VT = N->getValueType(0);
7779
7780   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7781   if (N->hasOneUse() &&
7782       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7783     return SDValue();
7784
7785   // fold (fp_extend c1fp) -> c1fp
7786   if (N0CFP)
7787     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7788
7789   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7790   // value of X.
7791   if (N0.getOpcode() == ISD::FP_ROUND
7792       && N0.getNode()->getConstantOperandVal(1) == 1) {
7793     SDValue In = N0.getOperand(0);
7794     if (In.getValueType() == VT) return In;
7795     if (VT.bitsLT(In.getValueType()))
7796       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7797                          In, N0.getOperand(1));
7798     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7799   }
7800
7801   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7802   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7803        TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
7804     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7805     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7806                                      LN0->getChain(),
7807                                      LN0->getBasePtr(), N0.getValueType(),
7808                                      LN0->getMemOperand());
7809     CombineTo(N, ExtLoad);
7810     CombineTo(N0.getNode(),
7811               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7812                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7813               ExtLoad.getValue(1));
7814     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7815   }
7816
7817   return SDValue();
7818 }
7819
7820 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7821   SDValue N0 = N->getOperand(0);
7822   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7823   EVT VT = N->getValueType(0);
7824
7825   // fold (fceil c1) -> fceil(c1)
7826   if (N0CFP)
7827     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7828
7829   return SDValue();
7830 }
7831
7832 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7833   SDValue N0 = N->getOperand(0);
7834   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7835   EVT VT = N->getValueType(0);
7836
7837   // fold (ftrunc c1) -> ftrunc(c1)
7838   if (N0CFP)
7839     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7840
7841   return SDValue();
7842 }
7843
7844 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7845   SDValue N0 = N->getOperand(0);
7846   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7847   EVT VT = N->getValueType(0);
7848
7849   // fold (ffloor c1) -> ffloor(c1)
7850   if (N0CFP)
7851     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7852
7853   return SDValue();
7854 }
7855
7856 // FIXME: FNEG and FABS have a lot in common; refactor.
7857 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7858   SDValue N0 = N->getOperand(0);
7859   EVT VT = N->getValueType(0);
7860
7861   if (VT.isVector()) {
7862     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7863     if (FoldedVOp.getNode()) return FoldedVOp;
7864   }
7865
7866   // Constant fold FNEG.
7867   if (isa<ConstantFPSDNode>(N0))
7868     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7869
7870   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7871                          &DAG.getTarget().Options))
7872     return GetNegatedExpression(N0, DAG, LegalOperations);
7873
7874   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7875   // constant pool values.
7876   if (!TLI.isFNegFree(VT) &&
7877       N0.getOpcode() == ISD::BITCAST &&
7878       N0.getNode()->hasOneUse()) {
7879     SDValue Int = N0.getOperand(0);
7880     EVT IntVT = Int.getValueType();
7881     if (IntVT.isInteger() && !IntVT.isVector()) {
7882       APInt SignMask;
7883       if (N0.getValueType().isVector()) {
7884         // For a vector, get a mask such as 0x80... per scalar element
7885         // and splat it.
7886         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7887         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7888       } else {
7889         // For a scalar, just generate 0x80...
7890         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7891       }
7892       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7893                         DAG.getConstant(SignMask, IntVT));
7894       AddToWorklist(Int.getNode());
7895       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7896     }
7897   }
7898
7899   // (fneg (fmul c, x)) -> (fmul -c, x)
7900   if (N0.getOpcode() == ISD::FMUL) {
7901     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7902     if (CFP1) {
7903       APFloat CVal = CFP1->getValueAPF();
7904       CVal.changeSign();
7905       if (Level >= AfterLegalizeDAG &&
7906           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7907            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7908         return DAG.getNode(
7909             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7910             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7911     }
7912   }
7913
7914   return SDValue();
7915 }
7916
7917 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7918   SDValue N0 = N->getOperand(0);
7919   SDValue N1 = N->getOperand(1);
7920   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7921   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7922
7923   if (N0CFP && N1CFP) {
7924     const APFloat &C0 = N0CFP->getValueAPF();
7925     const APFloat &C1 = N1CFP->getValueAPF();
7926     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7927   }
7928
7929   if (N0CFP) {
7930     EVT VT = N->getValueType(0);
7931     // Canonicalize to constant on RHS.
7932     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7933   }
7934
7935   return SDValue();
7936 }
7937
7938 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7939   SDValue N0 = N->getOperand(0);
7940   SDValue N1 = N->getOperand(1);
7941   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7942   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7943
7944   if (N0CFP && N1CFP) {
7945     const APFloat &C0 = N0CFP->getValueAPF();
7946     const APFloat &C1 = N1CFP->getValueAPF();
7947     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7948   }
7949
7950   if (N0CFP) {
7951     EVT VT = N->getValueType(0);
7952     // Canonicalize to constant on RHS.
7953     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7954   }
7955
7956   return SDValue();
7957 }
7958
7959 SDValue DAGCombiner::visitFABS(SDNode *N) {
7960   SDValue N0 = N->getOperand(0);
7961   EVT VT = N->getValueType(0);
7962
7963   if (VT.isVector()) {
7964     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7965     if (FoldedVOp.getNode()) return FoldedVOp;
7966   }
7967
7968   // fold (fabs c1) -> fabs(c1)
7969   if (isa<ConstantFPSDNode>(N0))
7970     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7971
7972   // fold (fabs (fabs x)) -> (fabs x)
7973   if (N0.getOpcode() == ISD::FABS)
7974     return N->getOperand(0);
7975
7976   // fold (fabs (fneg x)) -> (fabs x)
7977   // fold (fabs (fcopysign x, y)) -> (fabs x)
7978   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7979     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7980
7981   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7982   // constant pool values.
7983   if (!TLI.isFAbsFree(VT) &&
7984       N0.getOpcode() == ISD::BITCAST &&
7985       N0.getNode()->hasOneUse()) {
7986     SDValue Int = N0.getOperand(0);
7987     EVT IntVT = Int.getValueType();
7988     if (IntVT.isInteger() && !IntVT.isVector()) {
7989       APInt SignMask;
7990       if (N0.getValueType().isVector()) {
7991         // For a vector, get a mask such as 0x7f... per scalar element
7992         // and splat it.
7993         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7994         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7995       } else {
7996         // For a scalar, just generate 0x7f...
7997         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7998       }
7999       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
8000                         DAG.getConstant(SignMask, IntVT));
8001       AddToWorklist(Int.getNode());
8002       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
8003     }
8004   }
8005
8006   return SDValue();
8007 }
8008
8009 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
8010   SDValue Chain = N->getOperand(0);
8011   SDValue N1 = N->getOperand(1);
8012   SDValue N2 = N->getOperand(2);
8013
8014   // If N is a constant we could fold this into a fallthrough or unconditional
8015   // branch. However that doesn't happen very often in normal code, because
8016   // Instcombine/SimplifyCFG should have handled the available opportunities.
8017   // If we did this folding here, it would be necessary to update the
8018   // MachineBasicBlock CFG, which is awkward.
8019
8020   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
8021   // on the target.
8022   if (N1.getOpcode() == ISD::SETCC &&
8023       TLI.isOperationLegalOrCustom(ISD::BR_CC,
8024                                    N1.getOperand(0).getValueType())) {
8025     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8026                        Chain, N1.getOperand(2),
8027                        N1.getOperand(0), N1.getOperand(1), N2);
8028   }
8029
8030   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
8031       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
8032        (N1.getOperand(0).hasOneUse() &&
8033         N1.getOperand(0).getOpcode() == ISD::SRL))) {
8034     SDNode *Trunc = nullptr;
8035     if (N1.getOpcode() == ISD::TRUNCATE) {
8036       // Look pass the truncate.
8037       Trunc = N1.getNode();
8038       N1 = N1.getOperand(0);
8039     }
8040
8041     // Match this pattern so that we can generate simpler code:
8042     //
8043     //   %a = ...
8044     //   %b = and i32 %a, 2
8045     //   %c = srl i32 %b, 1
8046     //   brcond i32 %c ...
8047     //
8048     // into
8049     //
8050     //   %a = ...
8051     //   %b = and i32 %a, 2
8052     //   %c = setcc eq %b, 0
8053     //   brcond %c ...
8054     //
8055     // This applies only when the AND constant value has one bit set and the
8056     // SRL constant is equal to the log2 of the AND constant. The back-end is
8057     // smart enough to convert the result into a TEST/JMP sequence.
8058     SDValue Op0 = N1.getOperand(0);
8059     SDValue Op1 = N1.getOperand(1);
8060
8061     if (Op0.getOpcode() == ISD::AND &&
8062         Op1.getOpcode() == ISD::Constant) {
8063       SDValue AndOp1 = Op0.getOperand(1);
8064
8065       if (AndOp1.getOpcode() == ISD::Constant) {
8066         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
8067
8068         if (AndConst.isPowerOf2() &&
8069             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
8070           SDValue SetCC =
8071             DAG.getSetCC(SDLoc(N),
8072                          getSetCCResultType(Op0.getValueType()),
8073                          Op0, DAG.getConstant(0, Op0.getValueType()),
8074                          ISD::SETNE);
8075
8076           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
8077                                           MVT::Other, Chain, SetCC, N2);
8078           // Don't add the new BRCond into the worklist or else SimplifySelectCC
8079           // will convert it back to (X & C1) >> C2.
8080           CombineTo(N, NewBRCond, false);
8081           // Truncate is dead.
8082           if (Trunc)
8083             deleteAndRecombine(Trunc);
8084           // Replace the uses of SRL with SETCC
8085           WorklistRemover DeadNodes(*this);
8086           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8087           deleteAndRecombine(N1.getNode());
8088           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8089         }
8090       }
8091     }
8092
8093     if (Trunc)
8094       // Restore N1 if the above transformation doesn't match.
8095       N1 = N->getOperand(1);
8096   }
8097
8098   // Transform br(xor(x, y)) -> br(x != y)
8099   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
8100   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
8101     SDNode *TheXor = N1.getNode();
8102     SDValue Op0 = TheXor->getOperand(0);
8103     SDValue Op1 = TheXor->getOperand(1);
8104     if (Op0.getOpcode() == Op1.getOpcode()) {
8105       // Avoid missing important xor optimizations.
8106       SDValue Tmp = visitXOR(TheXor);
8107       if (Tmp.getNode()) {
8108         if (Tmp.getNode() != TheXor) {
8109           DEBUG(dbgs() << "\nReplacing.8 ";
8110                 TheXor->dump(&DAG);
8111                 dbgs() << "\nWith: ";
8112                 Tmp.getNode()->dump(&DAG);
8113                 dbgs() << '\n');
8114           WorklistRemover DeadNodes(*this);
8115           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
8116           deleteAndRecombine(TheXor);
8117           return DAG.getNode(ISD::BRCOND, SDLoc(N),
8118                              MVT::Other, Chain, Tmp, N2);
8119         }
8120
8121         // visitXOR has changed XOR's operands or replaced the XOR completely,
8122         // bail out.
8123         return SDValue(N, 0);
8124       }
8125     }
8126
8127     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
8128       bool Equal = false;
8129       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
8130         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
8131             Op0.getOpcode() == ISD::XOR) {
8132           TheXor = Op0.getNode();
8133           Equal = true;
8134         }
8135
8136       EVT SetCCVT = N1.getValueType();
8137       if (LegalTypes)
8138         SetCCVT = getSetCCResultType(SetCCVT);
8139       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
8140                                    SetCCVT,
8141                                    Op0, Op1,
8142                                    Equal ? ISD::SETEQ : ISD::SETNE);
8143       // Replace the uses of XOR with SETCC
8144       WorklistRemover DeadNodes(*this);
8145       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
8146       deleteAndRecombine(N1.getNode());
8147       return DAG.getNode(ISD::BRCOND, SDLoc(N),
8148                          MVT::Other, Chain, SetCC, N2);
8149     }
8150   }
8151
8152   return SDValue();
8153 }
8154
8155 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
8156 //
8157 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
8158   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
8159   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
8160
8161   // If N is a constant we could fold this into a fallthrough or unconditional
8162   // branch. However that doesn't happen very often in normal code, because
8163   // Instcombine/SimplifyCFG should have handled the available opportunities.
8164   // If we did this folding here, it would be necessary to update the
8165   // MachineBasicBlock CFG, which is awkward.
8166
8167   // Use SimplifySetCC to simplify SETCC's.
8168   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
8169                                CondLHS, CondRHS, CC->get(), SDLoc(N),
8170                                false);
8171   if (Simp.getNode()) AddToWorklist(Simp.getNode());
8172
8173   // fold to a simpler setcc
8174   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
8175     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
8176                        N->getOperand(0), Simp.getOperand(2),
8177                        Simp.getOperand(0), Simp.getOperand(1),
8178                        N->getOperand(4));
8179
8180   return SDValue();
8181 }
8182
8183 /// Return true if 'Use' is a load or a store that uses N as its base pointer
8184 /// and that N may be folded in the load / store addressing mode.
8185 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
8186                                     SelectionDAG &DAG,
8187                                     const TargetLowering &TLI) {
8188   EVT VT;
8189   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
8190     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
8191       return false;
8192     VT = Use->getValueType(0);
8193   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
8194     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
8195       return false;
8196     VT = ST->getValue().getValueType();
8197   } else
8198     return false;
8199
8200   TargetLowering::AddrMode AM;
8201   if (N->getOpcode() == ISD::ADD) {
8202     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8203     if (Offset)
8204       // [reg +/- imm]
8205       AM.BaseOffs = Offset->getSExtValue();
8206     else
8207       // [reg +/- reg]
8208       AM.Scale = 1;
8209   } else if (N->getOpcode() == ISD::SUB) {
8210     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8211     if (Offset)
8212       // [reg +/- imm]
8213       AM.BaseOffs = -Offset->getSExtValue();
8214     else
8215       // [reg +/- reg]
8216       AM.Scale = 1;
8217   } else
8218     return false;
8219
8220   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8221 }
8222
8223 /// Try turning a load/store into a pre-indexed load/store when the base
8224 /// pointer is an add or subtract and it has other uses besides the load/store.
8225 /// After the transformation, the new indexed load/store has effectively folded
8226 /// the add/subtract in and all of its other uses are redirected to the
8227 /// new load/store.
8228 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8229   if (Level < AfterLegalizeDAG)
8230     return false;
8231
8232   bool isLoad = true;
8233   SDValue Ptr;
8234   EVT VT;
8235   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8236     if (LD->isIndexed())
8237       return false;
8238     VT = LD->getMemoryVT();
8239     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8240         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8241       return false;
8242     Ptr = LD->getBasePtr();
8243   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8244     if (ST->isIndexed())
8245       return false;
8246     VT = ST->getMemoryVT();
8247     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8248         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8249       return false;
8250     Ptr = ST->getBasePtr();
8251     isLoad = false;
8252   } else {
8253     return false;
8254   }
8255
8256   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8257   // out.  There is no reason to make this a preinc/predec.
8258   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8259       Ptr.getNode()->hasOneUse())
8260     return false;
8261
8262   // Ask the target to do addressing mode selection.
8263   SDValue BasePtr;
8264   SDValue Offset;
8265   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8266   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8267     return false;
8268
8269   // Backends without true r+i pre-indexed forms may need to pass a
8270   // constant base with a variable offset so that constant coercion
8271   // will work with the patterns in canonical form.
8272   bool Swapped = false;
8273   if (isa<ConstantSDNode>(BasePtr)) {
8274     std::swap(BasePtr, Offset);
8275     Swapped = true;
8276   }
8277
8278   // Don't create a indexed load / store with zero offset.
8279   if (isa<ConstantSDNode>(Offset) &&
8280       cast<ConstantSDNode>(Offset)->isNullValue())
8281     return false;
8282
8283   // Try turning it into a pre-indexed load / store except when:
8284   // 1) The new base ptr is a frame index.
8285   // 2) If N is a store and the new base ptr is either the same as or is a
8286   //    predecessor of the value being stored.
8287   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8288   //    that would create a cycle.
8289   // 4) All uses are load / store ops that use it as old base ptr.
8290
8291   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8292   // (plus the implicit offset) to a register to preinc anyway.
8293   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8294     return false;
8295
8296   // Check #2.
8297   if (!isLoad) {
8298     SDValue Val = cast<StoreSDNode>(N)->getValue();
8299     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8300       return false;
8301   }
8302
8303   // If the offset is a constant, there may be other adds of constants that
8304   // can be folded with this one. We should do this to avoid having to keep
8305   // a copy of the original base pointer.
8306   SmallVector<SDNode *, 16> OtherUses;
8307   if (isa<ConstantSDNode>(Offset))
8308     for (SDNode *Use : BasePtr.getNode()->uses()) {
8309       if (Use == Ptr.getNode())
8310         continue;
8311
8312       if (Use->isPredecessorOf(N))
8313         continue;
8314
8315       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8316         OtherUses.clear();
8317         break;
8318       }
8319
8320       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8321       if (Op1.getNode() == BasePtr.getNode())
8322         std::swap(Op0, Op1);
8323       assert(Op0.getNode() == BasePtr.getNode() &&
8324              "Use of ADD/SUB but not an operand");
8325
8326       if (!isa<ConstantSDNode>(Op1)) {
8327         OtherUses.clear();
8328         break;
8329       }
8330
8331       // FIXME: In some cases, we can be smarter about this.
8332       if (Op1.getValueType() != Offset.getValueType()) {
8333         OtherUses.clear();
8334         break;
8335       }
8336
8337       OtherUses.push_back(Use);
8338     }
8339
8340   if (Swapped)
8341     std::swap(BasePtr, Offset);
8342
8343   // Now check for #3 and #4.
8344   bool RealUse = false;
8345
8346   // Caches for hasPredecessorHelper
8347   SmallPtrSet<const SDNode *, 32> Visited;
8348   SmallVector<const SDNode *, 16> Worklist;
8349
8350   for (SDNode *Use : Ptr.getNode()->uses()) {
8351     if (Use == N)
8352       continue;
8353     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8354       return false;
8355
8356     // If Ptr may be folded in addressing mode of other use, then it's
8357     // not profitable to do this transformation.
8358     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8359       RealUse = true;
8360   }
8361
8362   if (!RealUse)
8363     return false;
8364
8365   SDValue Result;
8366   if (isLoad)
8367     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8368                                 BasePtr, Offset, AM);
8369   else
8370     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8371                                  BasePtr, Offset, AM);
8372   ++PreIndexedNodes;
8373   ++NodesCombined;
8374   DEBUG(dbgs() << "\nReplacing.4 ";
8375         N->dump(&DAG);
8376         dbgs() << "\nWith: ";
8377         Result.getNode()->dump(&DAG);
8378         dbgs() << '\n');
8379   WorklistRemover DeadNodes(*this);
8380   if (isLoad) {
8381     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8382     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8383   } else {
8384     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8385   }
8386
8387   // Finally, since the node is now dead, remove it from the graph.
8388   deleteAndRecombine(N);
8389
8390   if (Swapped)
8391     std::swap(BasePtr, Offset);
8392
8393   // Replace other uses of BasePtr that can be updated to use Ptr
8394   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8395     unsigned OffsetIdx = 1;
8396     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8397       OffsetIdx = 0;
8398     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8399            BasePtr.getNode() && "Expected BasePtr operand");
8400
8401     // We need to replace ptr0 in the following expression:
8402     //   x0 * offset0 + y0 * ptr0 = t0
8403     // knowing that
8404     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8405     //
8406     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8407     // indexed load/store and the expresion that needs to be re-written.
8408     //
8409     // Therefore, we have:
8410     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8411
8412     ConstantSDNode *CN =
8413       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8414     int X0, X1, Y0, Y1;
8415     APInt Offset0 = CN->getAPIntValue();
8416     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8417
8418     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8419     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8420     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8421     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8422
8423     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8424
8425     APInt CNV = Offset0;
8426     if (X0 < 0) CNV = -CNV;
8427     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8428     else CNV = CNV - Offset1;
8429
8430     // We can now generate the new expression.
8431     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8432     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8433
8434     SDValue NewUse = DAG.getNode(Opcode,
8435                                  SDLoc(OtherUses[i]),
8436                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8437     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8438     deleteAndRecombine(OtherUses[i]);
8439   }
8440
8441   // Replace the uses of Ptr with uses of the updated base value.
8442   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8443   deleteAndRecombine(Ptr.getNode());
8444
8445   return true;
8446 }
8447
8448 /// Try to combine a load/store with a add/sub of the base pointer node into a
8449 /// post-indexed load/store. The transformation folded the add/subtract into the
8450 /// new indexed load/store effectively and all of its uses are redirected to the
8451 /// new load/store.
8452 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8453   if (Level < AfterLegalizeDAG)
8454     return false;
8455
8456   bool isLoad = true;
8457   SDValue Ptr;
8458   EVT VT;
8459   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8460     if (LD->isIndexed())
8461       return false;
8462     VT = LD->getMemoryVT();
8463     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8464         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8465       return false;
8466     Ptr = LD->getBasePtr();
8467   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8468     if (ST->isIndexed())
8469       return false;
8470     VT = ST->getMemoryVT();
8471     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8472         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8473       return false;
8474     Ptr = ST->getBasePtr();
8475     isLoad = false;
8476   } else {
8477     return false;
8478   }
8479
8480   if (Ptr.getNode()->hasOneUse())
8481     return false;
8482
8483   for (SDNode *Op : Ptr.getNode()->uses()) {
8484     if (Op == N ||
8485         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8486       continue;
8487
8488     SDValue BasePtr;
8489     SDValue Offset;
8490     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8491     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8492       // Don't create a indexed load / store with zero offset.
8493       if (isa<ConstantSDNode>(Offset) &&
8494           cast<ConstantSDNode>(Offset)->isNullValue())
8495         continue;
8496
8497       // Try turning it into a post-indexed load / store except when
8498       // 1) All uses are load / store ops that use it as base ptr (and
8499       //    it may be folded as addressing mmode).
8500       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8501       //    nor a successor of N. Otherwise, if Op is folded that would
8502       //    create a cycle.
8503
8504       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8505         continue;
8506
8507       // Check for #1.
8508       bool TryNext = false;
8509       for (SDNode *Use : BasePtr.getNode()->uses()) {
8510         if (Use == Ptr.getNode())
8511           continue;
8512
8513         // If all the uses are load / store addresses, then don't do the
8514         // transformation.
8515         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8516           bool RealUse = false;
8517           for (SDNode *UseUse : Use->uses()) {
8518             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8519               RealUse = true;
8520           }
8521
8522           if (!RealUse) {
8523             TryNext = true;
8524             break;
8525           }
8526         }
8527       }
8528
8529       if (TryNext)
8530         continue;
8531
8532       // Check for #2
8533       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8534         SDValue Result = isLoad
8535           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8536                                BasePtr, Offset, AM)
8537           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8538                                 BasePtr, Offset, AM);
8539         ++PostIndexedNodes;
8540         ++NodesCombined;
8541         DEBUG(dbgs() << "\nReplacing.5 ";
8542               N->dump(&DAG);
8543               dbgs() << "\nWith: ";
8544               Result.getNode()->dump(&DAG);
8545               dbgs() << '\n');
8546         WorklistRemover DeadNodes(*this);
8547         if (isLoad) {
8548           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8549           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8550         } else {
8551           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8552         }
8553
8554         // Finally, since the node is now dead, remove it from the graph.
8555         deleteAndRecombine(N);
8556
8557         // Replace the uses of Use with uses of the updated base value.
8558         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8559                                       Result.getValue(isLoad ? 1 : 0));
8560         deleteAndRecombine(Op);
8561         return true;
8562       }
8563     }
8564   }
8565
8566   return false;
8567 }
8568
8569 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8570 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8571   ISD::MemIndexedMode AM = LD->getAddressingMode();
8572   assert(AM != ISD::UNINDEXED);
8573   SDValue BP = LD->getOperand(1);
8574   SDValue Inc = LD->getOperand(2);
8575
8576   // Some backends use TargetConstants for load offsets, but don't expect
8577   // TargetConstants in general ADD nodes. We can convert these constants into
8578   // regular Constants (if the constant is not opaque).
8579   assert((Inc.getOpcode() != ISD::TargetConstant ||
8580           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8581          "Cannot split out indexing using opaque target constants");
8582   if (Inc.getOpcode() == ISD::TargetConstant) {
8583     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8584     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8585                           ConstInc->getValueType(0));
8586   }
8587
8588   unsigned Opc =
8589       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8590   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8591 }
8592
8593 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8594   LoadSDNode *LD  = cast<LoadSDNode>(N);
8595   SDValue Chain = LD->getChain();
8596   SDValue Ptr   = LD->getBasePtr();
8597
8598   // If load is not volatile and there are no uses of the loaded value (and
8599   // the updated indexed value in case of indexed loads), change uses of the
8600   // chain value into uses of the chain input (i.e. delete the dead load).
8601   if (!LD->isVolatile()) {
8602     if (N->getValueType(1) == MVT::Other) {
8603       // Unindexed loads.
8604       if (!N->hasAnyUseOfValue(0)) {
8605         // It's not safe to use the two value CombineTo variant here. e.g.
8606         // v1, chain2 = load chain1, loc
8607         // v2, chain3 = load chain2, loc
8608         // v3         = add v2, c
8609         // Now we replace use of chain2 with chain1.  This makes the second load
8610         // isomorphic to the one we are deleting, and thus makes this load live.
8611         DEBUG(dbgs() << "\nReplacing.6 ";
8612               N->dump(&DAG);
8613               dbgs() << "\nWith chain: ";
8614               Chain.getNode()->dump(&DAG);
8615               dbgs() << "\n");
8616         WorklistRemover DeadNodes(*this);
8617         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8618
8619         if (N->use_empty())
8620           deleteAndRecombine(N);
8621
8622         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8623       }
8624     } else {
8625       // Indexed loads.
8626       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8627
8628       // If this load has an opaque TargetConstant offset, then we cannot split
8629       // the indexing into an add/sub directly (that TargetConstant may not be
8630       // valid for a different type of node, and we cannot convert an opaque
8631       // target constant into a regular constant).
8632       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8633                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8634
8635       if (!N->hasAnyUseOfValue(0) &&
8636           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8637         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8638         SDValue Index;
8639         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8640           Index = SplitIndexingFromLoad(LD);
8641           // Try to fold the base pointer arithmetic into subsequent loads and
8642           // stores.
8643           AddUsersToWorklist(N);
8644         } else
8645           Index = DAG.getUNDEF(N->getValueType(1));
8646         DEBUG(dbgs() << "\nReplacing.7 ";
8647               N->dump(&DAG);
8648               dbgs() << "\nWith: ";
8649               Undef.getNode()->dump(&DAG);
8650               dbgs() << " and 2 other values\n");
8651         WorklistRemover DeadNodes(*this);
8652         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8653         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8654         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8655         deleteAndRecombine(N);
8656         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8657       }
8658     }
8659   }
8660
8661   // If this load is directly stored, replace the load value with the stored
8662   // value.
8663   // TODO: Handle store large -> read small portion.
8664   // TODO: Handle TRUNCSTORE/LOADEXT
8665   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8666     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8667       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8668       if (PrevST->getBasePtr() == Ptr &&
8669           PrevST->getValue().getValueType() == N->getValueType(0))
8670       return CombineTo(N, Chain.getOperand(1), Chain);
8671     }
8672   }
8673
8674   // Try to infer better alignment information than the load already has.
8675   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8676     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8677       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8678         SDValue NewLoad =
8679                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8680                               LD->getValueType(0),
8681                               Chain, Ptr, LD->getPointerInfo(),
8682                               LD->getMemoryVT(),
8683                               LD->isVolatile(), LD->isNonTemporal(),
8684                               LD->isInvariant(), Align, LD->getAAInfo());
8685         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8686       }
8687     }
8688   }
8689
8690   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8691                                                   : DAG.getSubtarget().useAA();
8692 #ifndef NDEBUG
8693   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8694       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8695     UseAA = false;
8696 #endif
8697   if (UseAA && LD->isUnindexed()) {
8698     // Walk up chain skipping non-aliasing memory nodes.
8699     SDValue BetterChain = FindBetterChain(N, Chain);
8700
8701     // If there is a better chain.
8702     if (Chain != BetterChain) {
8703       SDValue ReplLoad;
8704
8705       // Replace the chain to void dependency.
8706       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8707         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8708                                BetterChain, Ptr, LD->getMemOperand());
8709       } else {
8710         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8711                                   LD->getValueType(0),
8712                                   BetterChain, Ptr, LD->getMemoryVT(),
8713                                   LD->getMemOperand());
8714       }
8715
8716       // Create token factor to keep old chain connected.
8717       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8718                                   MVT::Other, Chain, ReplLoad.getValue(1));
8719
8720       // Make sure the new and old chains are cleaned up.
8721       AddToWorklist(Token.getNode());
8722
8723       // Replace uses with load result and token factor. Don't add users
8724       // to work list.
8725       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8726     }
8727   }
8728
8729   // Try transforming N to an indexed load.
8730   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8731     return SDValue(N, 0);
8732
8733   // Try to slice up N to more direct loads if the slices are mapped to
8734   // different register banks or pairing can take place.
8735   if (SliceUpLoad(N))
8736     return SDValue(N, 0);
8737
8738   return SDValue();
8739 }
8740
8741 namespace {
8742 /// \brief Helper structure used to slice a load in smaller loads.
8743 /// Basically a slice is obtained from the following sequence:
8744 /// Origin = load Ty1, Base
8745 /// Shift = srl Ty1 Origin, CstTy Amount
8746 /// Inst = trunc Shift to Ty2
8747 ///
8748 /// Then, it will be rewriten into:
8749 /// Slice = load SliceTy, Base + SliceOffset
8750 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8751 ///
8752 /// SliceTy is deduced from the number of bits that are actually used to
8753 /// build Inst.
8754 struct LoadedSlice {
8755   /// \brief Helper structure used to compute the cost of a slice.
8756   struct Cost {
8757     /// Are we optimizing for code size.
8758     bool ForCodeSize;
8759     /// Various cost.
8760     unsigned Loads;
8761     unsigned Truncates;
8762     unsigned CrossRegisterBanksCopies;
8763     unsigned ZExts;
8764     unsigned Shift;
8765
8766     Cost(bool ForCodeSize = false)
8767         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8768           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8769
8770     /// \brief Get the cost of one isolated slice.
8771     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8772         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8773           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8774       EVT TruncType = LS.Inst->getValueType(0);
8775       EVT LoadedType = LS.getLoadedType();
8776       if (TruncType != LoadedType &&
8777           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8778         ZExts = 1;
8779     }
8780
8781     /// \brief Account for slicing gain in the current cost.
8782     /// Slicing provide a few gains like removing a shift or a
8783     /// truncate. This method allows to grow the cost of the original
8784     /// load with the gain from this slice.
8785     void addSliceGain(const LoadedSlice &LS) {
8786       // Each slice saves a truncate.
8787       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8788       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8789                               LS.Inst->getOperand(0).getValueType()))
8790         ++Truncates;
8791       // If there is a shift amount, this slice gets rid of it.
8792       if (LS.Shift)
8793         ++Shift;
8794       // If this slice can merge a cross register bank copy, account for it.
8795       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8796         ++CrossRegisterBanksCopies;
8797     }
8798
8799     Cost &operator+=(const Cost &RHS) {
8800       Loads += RHS.Loads;
8801       Truncates += RHS.Truncates;
8802       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8803       ZExts += RHS.ZExts;
8804       Shift += RHS.Shift;
8805       return *this;
8806     }
8807
8808     bool operator==(const Cost &RHS) const {
8809       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8810              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8811              ZExts == RHS.ZExts && Shift == RHS.Shift;
8812     }
8813
8814     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8815
8816     bool operator<(const Cost &RHS) const {
8817       // Assume cross register banks copies are as expensive as loads.
8818       // FIXME: Do we want some more target hooks?
8819       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8820       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8821       // Unless we are optimizing for code size, consider the
8822       // expensive operation first.
8823       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8824         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8825       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8826              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8827     }
8828
8829     bool operator>(const Cost &RHS) const { return RHS < *this; }
8830
8831     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8832
8833     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8834   };
8835   // The last instruction that represent the slice. This should be a
8836   // truncate instruction.
8837   SDNode *Inst;
8838   // The original load instruction.
8839   LoadSDNode *Origin;
8840   // The right shift amount in bits from the original load.
8841   unsigned Shift;
8842   // The DAG from which Origin came from.
8843   // This is used to get some contextual information about legal types, etc.
8844   SelectionDAG *DAG;
8845
8846   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8847               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8848       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8849
8850   LoadedSlice(const LoadedSlice &LS)
8851       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8852
8853   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8854   /// \return Result is \p BitWidth and has used bits set to 1 and
8855   ///         not used bits set to 0.
8856   APInt getUsedBits() const {
8857     // Reproduce the trunc(lshr) sequence:
8858     // - Start from the truncated value.
8859     // - Zero extend to the desired bit width.
8860     // - Shift left.
8861     assert(Origin && "No original load to compare against.");
8862     unsigned BitWidth = Origin->getValueSizeInBits(0);
8863     assert(Inst && "This slice is not bound to an instruction");
8864     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8865            "Extracted slice is bigger than the whole type!");
8866     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8867     UsedBits.setAllBits();
8868     UsedBits = UsedBits.zext(BitWidth);
8869     UsedBits <<= Shift;
8870     return UsedBits;
8871   }
8872
8873   /// \brief Get the size of the slice to be loaded in bytes.
8874   unsigned getLoadedSize() const {
8875     unsigned SliceSize = getUsedBits().countPopulation();
8876     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8877     return SliceSize / 8;
8878   }
8879
8880   /// \brief Get the type that will be loaded for this slice.
8881   /// Note: This may not be the final type for the slice.
8882   EVT getLoadedType() const {
8883     assert(DAG && "Missing context");
8884     LLVMContext &Ctxt = *DAG->getContext();
8885     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8886   }
8887
8888   /// \brief Get the alignment of the load used for this slice.
8889   unsigned getAlignment() const {
8890     unsigned Alignment = Origin->getAlignment();
8891     unsigned Offset = getOffsetFromBase();
8892     if (Offset != 0)
8893       Alignment = MinAlign(Alignment, Alignment + Offset);
8894     return Alignment;
8895   }
8896
8897   /// \brief Check if this slice can be rewritten with legal operations.
8898   bool isLegal() const {
8899     // An invalid slice is not legal.
8900     if (!Origin || !Inst || !DAG)
8901       return false;
8902
8903     // Offsets are for indexed load only, we do not handle that.
8904     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8905       return false;
8906
8907     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8908
8909     // Check that the type is legal.
8910     EVT SliceType = getLoadedType();
8911     if (!TLI.isTypeLegal(SliceType))
8912       return false;
8913
8914     // Check that the load is legal for this type.
8915     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8916       return false;
8917
8918     // Check that the offset can be computed.
8919     // 1. Check its type.
8920     EVT PtrType = Origin->getBasePtr().getValueType();
8921     if (PtrType == MVT::Untyped || PtrType.isExtended())
8922       return false;
8923
8924     // 2. Check that it fits in the immediate.
8925     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8926       return false;
8927
8928     // 3. Check that the computation is legal.
8929     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8930       return false;
8931
8932     // Check that the zext is legal if it needs one.
8933     EVT TruncateType = Inst->getValueType(0);
8934     if (TruncateType != SliceType &&
8935         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8936       return false;
8937
8938     return true;
8939   }
8940
8941   /// \brief Get the offset in bytes of this slice in the original chunk of
8942   /// bits.
8943   /// \pre DAG != nullptr.
8944   uint64_t getOffsetFromBase() const {
8945     assert(DAG && "Missing context.");
8946     bool IsBigEndian =
8947         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8948     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8949     uint64_t Offset = Shift / 8;
8950     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8951     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8952            "The size of the original loaded type is not a multiple of a"
8953            " byte.");
8954     // If Offset is bigger than TySizeInBytes, it means we are loading all
8955     // zeros. This should have been optimized before in the process.
8956     assert(TySizeInBytes > Offset &&
8957            "Invalid shift amount for given loaded size");
8958     if (IsBigEndian)
8959       Offset = TySizeInBytes - Offset - getLoadedSize();
8960     return Offset;
8961   }
8962
8963   /// \brief Generate the sequence of instructions to load the slice
8964   /// represented by this object and redirect the uses of this slice to
8965   /// this new sequence of instructions.
8966   /// \pre this->Inst && this->Origin are valid Instructions and this
8967   /// object passed the legal check: LoadedSlice::isLegal returned true.
8968   /// \return The last instruction of the sequence used to load the slice.
8969   SDValue loadSlice() const {
8970     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8971     const SDValue &OldBaseAddr = Origin->getBasePtr();
8972     SDValue BaseAddr = OldBaseAddr;
8973     // Get the offset in that chunk of bytes w.r.t. the endianess.
8974     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8975     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8976     if (Offset) {
8977       // BaseAddr = BaseAddr + Offset.
8978       EVT ArithType = BaseAddr.getValueType();
8979       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8980                               DAG->getConstant(Offset, ArithType));
8981     }
8982
8983     // Create the type of the loaded slice according to its size.
8984     EVT SliceType = getLoadedType();
8985
8986     // Create the load for the slice.
8987     SDValue LastInst = DAG->getLoad(
8988         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8989         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8990         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8991     // If the final type is not the same as the loaded type, this means that
8992     // we have to pad with zero. Create a zero extend for that.
8993     EVT FinalType = Inst->getValueType(0);
8994     if (SliceType != FinalType)
8995       LastInst =
8996           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8997     return LastInst;
8998   }
8999
9000   /// \brief Check if this slice can be merged with an expensive cross register
9001   /// bank copy. E.g.,
9002   /// i = load i32
9003   /// f = bitcast i32 i to float
9004   bool canMergeExpensiveCrossRegisterBankCopy() const {
9005     if (!Inst || !Inst->hasOneUse())
9006       return false;
9007     SDNode *Use = *Inst->use_begin();
9008     if (Use->getOpcode() != ISD::BITCAST)
9009       return false;
9010     assert(DAG && "Missing context");
9011     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
9012     EVT ResVT = Use->getValueType(0);
9013     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
9014     const TargetRegisterClass *ArgRC =
9015         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
9016     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
9017       return false;
9018
9019     // At this point, we know that we perform a cross-register-bank copy.
9020     // Check if it is expensive.
9021     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
9022     // Assume bitcasts are cheap, unless both register classes do not
9023     // explicitly share a common sub class.
9024     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
9025       return false;
9026
9027     // Check if it will be merged with the load.
9028     // 1. Check the alignment constraint.
9029     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
9030         ResVT.getTypeForEVT(*DAG->getContext()));
9031
9032     if (RequiredAlignment > getAlignment())
9033       return false;
9034
9035     // 2. Check that the load is a legal operation for that type.
9036     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
9037       return false;
9038
9039     // 3. Check that we do not have a zext in the way.
9040     if (Inst->getValueType(0) != getLoadedType())
9041       return false;
9042
9043     return true;
9044   }
9045 };
9046 }
9047
9048 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
9049 /// \p UsedBits looks like 0..0 1..1 0..0.
9050 static bool areUsedBitsDense(const APInt &UsedBits) {
9051   // If all the bits are one, this is dense!
9052   if (UsedBits.isAllOnesValue())
9053     return true;
9054
9055   // Get rid of the unused bits on the right.
9056   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
9057   // Get rid of the unused bits on the left.
9058   if (NarrowedUsedBits.countLeadingZeros())
9059     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
9060   // Check that the chunk of bits is completely used.
9061   return NarrowedUsedBits.isAllOnesValue();
9062 }
9063
9064 /// \brief Check whether or not \p First and \p Second are next to each other
9065 /// in memory. This means that there is no hole between the bits loaded
9066 /// by \p First and the bits loaded by \p Second.
9067 static bool areSlicesNextToEachOther(const LoadedSlice &First,
9068                                      const LoadedSlice &Second) {
9069   assert(First.Origin == Second.Origin && First.Origin &&
9070          "Unable to match different memory origins.");
9071   APInt UsedBits = First.getUsedBits();
9072   assert((UsedBits & Second.getUsedBits()) == 0 &&
9073          "Slices are not supposed to overlap.");
9074   UsedBits |= Second.getUsedBits();
9075   return areUsedBitsDense(UsedBits);
9076 }
9077
9078 /// \brief Adjust the \p GlobalLSCost according to the target
9079 /// paring capabilities and the layout of the slices.
9080 /// \pre \p GlobalLSCost should account for at least as many loads as
9081 /// there is in the slices in \p LoadedSlices.
9082 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9083                                  LoadedSlice::Cost &GlobalLSCost) {
9084   unsigned NumberOfSlices = LoadedSlices.size();
9085   // If there is less than 2 elements, no pairing is possible.
9086   if (NumberOfSlices < 2)
9087     return;
9088
9089   // Sort the slices so that elements that are likely to be next to each
9090   // other in memory are next to each other in the list.
9091   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
9092             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
9093     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
9094     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
9095   });
9096   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
9097   // First (resp. Second) is the first (resp. Second) potentially candidate
9098   // to be placed in a paired load.
9099   const LoadedSlice *First = nullptr;
9100   const LoadedSlice *Second = nullptr;
9101   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
9102                 // Set the beginning of the pair.
9103                                                            First = Second) {
9104
9105     Second = &LoadedSlices[CurrSlice];
9106
9107     // If First is NULL, it means we start a new pair.
9108     // Get to the next slice.
9109     if (!First)
9110       continue;
9111
9112     EVT LoadedType = First->getLoadedType();
9113
9114     // If the types of the slices are different, we cannot pair them.
9115     if (LoadedType != Second->getLoadedType())
9116       continue;
9117
9118     // Check if the target supplies paired loads for this type.
9119     unsigned RequiredAlignment = 0;
9120     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
9121       // move to the next pair, this type is hopeless.
9122       Second = nullptr;
9123       continue;
9124     }
9125     // Check if we meet the alignment requirement.
9126     if (RequiredAlignment > First->getAlignment())
9127       continue;
9128
9129     // Check that both loads are next to each other in memory.
9130     if (!areSlicesNextToEachOther(*First, *Second))
9131       continue;
9132
9133     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
9134     --GlobalLSCost.Loads;
9135     // Move to the next pair.
9136     Second = nullptr;
9137   }
9138 }
9139
9140 /// \brief Check the profitability of all involved LoadedSlice.
9141 /// Currently, it is considered profitable if there is exactly two
9142 /// involved slices (1) which are (2) next to each other in memory, and
9143 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
9144 ///
9145 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
9146 /// the elements themselves.
9147 ///
9148 /// FIXME: When the cost model will be mature enough, we can relax
9149 /// constraints (1) and (2).
9150 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
9151                                 const APInt &UsedBits, bool ForCodeSize) {
9152   unsigned NumberOfSlices = LoadedSlices.size();
9153   if (StressLoadSlicing)
9154     return NumberOfSlices > 1;
9155
9156   // Check (1).
9157   if (NumberOfSlices != 2)
9158     return false;
9159
9160   // Check (2).
9161   if (!areUsedBitsDense(UsedBits))
9162     return false;
9163
9164   // Check (3).
9165   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
9166   // The original code has one big load.
9167   OrigCost.Loads = 1;
9168   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
9169     const LoadedSlice &LS = LoadedSlices[CurrSlice];
9170     // Accumulate the cost of all the slices.
9171     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
9172     GlobalSlicingCost += SliceCost;
9173
9174     // Account as cost in the original configuration the gain obtained
9175     // with the current slices.
9176     OrigCost.addSliceGain(LS);
9177   }
9178
9179   // If the target supports paired load, adjust the cost accordingly.
9180   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
9181   return OrigCost > GlobalSlicingCost;
9182 }
9183
9184 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
9185 /// operations, split it in the various pieces being extracted.
9186 ///
9187 /// This sort of thing is introduced by SROA.
9188 /// This slicing takes care not to insert overlapping loads.
9189 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
9190 bool DAGCombiner::SliceUpLoad(SDNode *N) {
9191   if (Level < AfterLegalizeDAG)
9192     return false;
9193
9194   LoadSDNode *LD = cast<LoadSDNode>(N);
9195   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
9196       !LD->getValueType(0).isInteger())
9197     return false;
9198
9199   // Keep track of already used bits to detect overlapping values.
9200   // In that case, we will just abort the transformation.
9201   APInt UsedBits(LD->getValueSizeInBits(0), 0);
9202
9203   SmallVector<LoadedSlice, 4> LoadedSlices;
9204
9205   // Check if this load is used as several smaller chunks of bits.
9206   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
9207   // of computation for each trunc.
9208   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9209        UI != UIEnd; ++UI) {
9210     // Skip the uses of the chain.
9211     if (UI.getUse().getResNo() != 0)
9212       continue;
9213
9214     SDNode *User = *UI;
9215     unsigned Shift = 0;
9216
9217     // Check if this is a trunc(lshr).
9218     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9219         isa<ConstantSDNode>(User->getOperand(1))) {
9220       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9221       User = *User->use_begin();
9222     }
9223
9224     // At this point, User is a Truncate, iff we encountered, trunc or
9225     // trunc(lshr).
9226     if (User->getOpcode() != ISD::TRUNCATE)
9227       return false;
9228
9229     // The width of the type must be a power of 2 and greater than 8-bits.
9230     // Otherwise the load cannot be represented in LLVM IR.
9231     // Moreover, if we shifted with a non-8-bits multiple, the slice
9232     // will be across several bytes. We do not support that.
9233     unsigned Width = User->getValueSizeInBits(0);
9234     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9235       return 0;
9236
9237     // Build the slice for this chain of computations.
9238     LoadedSlice LS(User, LD, Shift, &DAG);
9239     APInt CurrentUsedBits = LS.getUsedBits();
9240
9241     // Check if this slice overlaps with another.
9242     if ((CurrentUsedBits & UsedBits) != 0)
9243       return false;
9244     // Update the bits used globally.
9245     UsedBits |= CurrentUsedBits;
9246
9247     // Check if the new slice would be legal.
9248     if (!LS.isLegal())
9249       return false;
9250
9251     // Record the slice.
9252     LoadedSlices.push_back(LS);
9253   }
9254
9255   // Abort slicing if it does not seem to be profitable.
9256   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9257     return false;
9258
9259   ++SlicedLoads;
9260
9261   // Rewrite each chain to use an independent load.
9262   // By construction, each chain can be represented by a unique load.
9263
9264   // Prepare the argument for the new token factor for all the slices.
9265   SmallVector<SDValue, 8> ArgChains;
9266   for (SmallVectorImpl<LoadedSlice>::const_iterator
9267            LSIt = LoadedSlices.begin(),
9268            LSItEnd = LoadedSlices.end();
9269        LSIt != LSItEnd; ++LSIt) {
9270     SDValue SliceInst = LSIt->loadSlice();
9271     CombineTo(LSIt->Inst, SliceInst, true);
9272     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9273       SliceInst = SliceInst.getOperand(0);
9274     assert(SliceInst->getOpcode() == ISD::LOAD &&
9275            "It takes more than a zext to get to the loaded slice!!");
9276     ArgChains.push_back(SliceInst.getValue(1));
9277   }
9278
9279   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9280                               ArgChains);
9281   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9282   return true;
9283 }
9284
9285 /// Check to see if V is (and load (ptr), imm), where the load is having
9286 /// specific bytes cleared out.  If so, return the byte size being masked out
9287 /// and the shift amount.
9288 static std::pair<unsigned, unsigned>
9289 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9290   std::pair<unsigned, unsigned> Result(0, 0);
9291
9292   // Check for the structure we're looking for.
9293   if (V->getOpcode() != ISD::AND ||
9294       !isa<ConstantSDNode>(V->getOperand(1)) ||
9295       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9296     return Result;
9297
9298   // Check the chain and pointer.
9299   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9300   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9301
9302   // The store should be chained directly to the load or be an operand of a
9303   // tokenfactor.
9304   if (LD == Chain.getNode())
9305     ; // ok.
9306   else if (Chain->getOpcode() != ISD::TokenFactor)
9307     return Result; // Fail.
9308   else {
9309     bool isOk = false;
9310     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9311       if (Chain->getOperand(i).getNode() == LD) {
9312         isOk = true;
9313         break;
9314       }
9315     if (!isOk) return Result;
9316   }
9317
9318   // This only handles simple types.
9319   if (V.getValueType() != MVT::i16 &&
9320       V.getValueType() != MVT::i32 &&
9321       V.getValueType() != MVT::i64)
9322     return Result;
9323
9324   // Check the constant mask.  Invert it so that the bits being masked out are
9325   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9326   // follow the sign bit for uniformity.
9327   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9328   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9329   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9330   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9331   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9332   if (NotMaskLZ == 64) return Result;  // All zero mask.
9333
9334   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9335   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9336     return Result;
9337
9338   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9339   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9340     NotMaskLZ -= 64-V.getValueSizeInBits();
9341
9342   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9343   switch (MaskedBytes) {
9344   case 1:
9345   case 2:
9346   case 4: break;
9347   default: return Result; // All one mask, or 5-byte mask.
9348   }
9349
9350   // Verify that the first bit starts at a multiple of mask so that the access
9351   // is aligned the same as the access width.
9352   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9353
9354   Result.first = MaskedBytes;
9355   Result.second = NotMaskTZ/8;
9356   return Result;
9357 }
9358
9359
9360 /// Check to see if IVal is something that provides a value as specified by
9361 /// MaskInfo. If so, replace the specified store with a narrower store of
9362 /// truncated IVal.
9363 static SDNode *
9364 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9365                                 SDValue IVal, StoreSDNode *St,
9366                                 DAGCombiner *DC) {
9367   unsigned NumBytes = MaskInfo.first;
9368   unsigned ByteShift = MaskInfo.second;
9369   SelectionDAG &DAG = DC->getDAG();
9370
9371   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9372   // that uses this.  If not, this is not a replacement.
9373   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9374                                   ByteShift*8, (ByteShift+NumBytes)*8);
9375   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9376
9377   // Check that it is legal on the target to do this.  It is legal if the new
9378   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9379   // legalization.
9380   MVT VT = MVT::getIntegerVT(NumBytes*8);
9381   if (!DC->isTypeLegal(VT))
9382     return nullptr;
9383
9384   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9385   // shifted by ByteShift and truncated down to NumBytes.
9386   if (ByteShift)
9387     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9388                        DAG.getConstant(ByteShift*8,
9389                                     DC->getShiftAmountTy(IVal.getValueType())));
9390
9391   // Figure out the offset for the store and the alignment of the access.
9392   unsigned StOffset;
9393   unsigned NewAlign = St->getAlignment();
9394
9395   if (DAG.getTargetLoweringInfo().isLittleEndian())
9396     StOffset = ByteShift;
9397   else
9398     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9399
9400   SDValue Ptr = St->getBasePtr();
9401   if (StOffset) {
9402     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9403                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9404     NewAlign = MinAlign(NewAlign, StOffset);
9405   }
9406
9407   // Truncate down to the new size.
9408   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9409
9410   ++OpsNarrowed;
9411   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9412                       St->getPointerInfo().getWithOffset(StOffset),
9413                       false, false, NewAlign).getNode();
9414 }
9415
9416
9417 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9418 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9419 /// narrowing the load and store if it would end up being a win for performance
9420 /// or code size.
9421 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9422   StoreSDNode *ST  = cast<StoreSDNode>(N);
9423   if (ST->isVolatile())
9424     return SDValue();
9425
9426   SDValue Chain = ST->getChain();
9427   SDValue Value = ST->getValue();
9428   SDValue Ptr   = ST->getBasePtr();
9429   EVT VT = Value.getValueType();
9430
9431   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9432     return SDValue();
9433
9434   unsigned Opc = Value.getOpcode();
9435
9436   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9437   // is a byte mask indicating a consecutive number of bytes, check to see if
9438   // Y is known to provide just those bytes.  If so, we try to replace the
9439   // load + replace + store sequence with a single (narrower) store, which makes
9440   // the load dead.
9441   if (Opc == ISD::OR) {
9442     std::pair<unsigned, unsigned> MaskedLoad;
9443     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9444     if (MaskedLoad.first)
9445       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9446                                                   Value.getOperand(1), ST,this))
9447         return SDValue(NewST, 0);
9448
9449     // Or is commutative, so try swapping X and Y.
9450     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9451     if (MaskedLoad.first)
9452       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9453                                                   Value.getOperand(0), ST,this))
9454         return SDValue(NewST, 0);
9455   }
9456
9457   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9458       Value.getOperand(1).getOpcode() != ISD::Constant)
9459     return SDValue();
9460
9461   SDValue N0 = Value.getOperand(0);
9462   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9463       Chain == SDValue(N0.getNode(), 1)) {
9464     LoadSDNode *LD = cast<LoadSDNode>(N0);
9465     if (LD->getBasePtr() != Ptr ||
9466         LD->getPointerInfo().getAddrSpace() !=
9467         ST->getPointerInfo().getAddrSpace())
9468       return SDValue();
9469
9470     // Find the type to narrow it the load / op / store to.
9471     SDValue N1 = Value.getOperand(1);
9472     unsigned BitWidth = N1.getValueSizeInBits();
9473     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9474     if (Opc == ISD::AND)
9475       Imm ^= APInt::getAllOnesValue(BitWidth);
9476     if (Imm == 0 || Imm.isAllOnesValue())
9477       return SDValue();
9478     unsigned ShAmt = Imm.countTrailingZeros();
9479     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9480     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9481     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9482     while (NewBW < BitWidth &&
9483            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9484              TLI.isNarrowingProfitable(VT, NewVT))) {
9485       NewBW = NextPowerOf2(NewBW);
9486       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9487     }
9488     if (NewBW >= BitWidth)
9489       return SDValue();
9490
9491     // If the lsb changed does not start at the type bitwidth boundary,
9492     // start at the previous one.
9493     if (ShAmt % NewBW)
9494       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9495     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9496                                    std::min(BitWidth, ShAmt + NewBW));
9497     if ((Imm & Mask) == Imm) {
9498       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9499       if (Opc == ISD::AND)
9500         NewImm ^= APInt::getAllOnesValue(NewBW);
9501       uint64_t PtrOff = ShAmt / 8;
9502       // For big endian targets, we need to adjust the offset to the pointer to
9503       // load the correct bytes.
9504       if (TLI.isBigEndian())
9505         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9506
9507       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9508       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9509       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9510         return SDValue();
9511
9512       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9513                                    Ptr.getValueType(), Ptr,
9514                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9515       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9516                                   LD->getChain(), NewPtr,
9517                                   LD->getPointerInfo().getWithOffset(PtrOff),
9518                                   LD->isVolatile(), LD->isNonTemporal(),
9519                                   LD->isInvariant(), NewAlign,
9520                                   LD->getAAInfo());
9521       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9522                                    DAG.getConstant(NewImm, NewVT));
9523       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9524                                    NewVal, NewPtr,
9525                                    ST->getPointerInfo().getWithOffset(PtrOff),
9526                                    false, false, NewAlign);
9527
9528       AddToWorklist(NewPtr.getNode());
9529       AddToWorklist(NewLD.getNode());
9530       AddToWorklist(NewVal.getNode());
9531       WorklistRemover DeadNodes(*this);
9532       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9533       ++OpsNarrowed;
9534       return NewST;
9535     }
9536   }
9537
9538   return SDValue();
9539 }
9540
9541 /// For a given floating point load / store pair, if the load value isn't used
9542 /// by any other operations, then consider transforming the pair to integer
9543 /// load / store operations if the target deems the transformation profitable.
9544 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9545   StoreSDNode *ST  = cast<StoreSDNode>(N);
9546   SDValue Chain = ST->getChain();
9547   SDValue Value = ST->getValue();
9548   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9549       Value.hasOneUse() &&
9550       Chain == SDValue(Value.getNode(), 1)) {
9551     LoadSDNode *LD = cast<LoadSDNode>(Value);
9552     EVT VT = LD->getMemoryVT();
9553     if (!VT.isFloatingPoint() ||
9554         VT != ST->getMemoryVT() ||
9555         LD->isNonTemporal() ||
9556         ST->isNonTemporal() ||
9557         LD->getPointerInfo().getAddrSpace() != 0 ||
9558         ST->getPointerInfo().getAddrSpace() != 0)
9559       return SDValue();
9560
9561     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9562     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9563         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9564         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9565         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9566       return SDValue();
9567
9568     unsigned LDAlign = LD->getAlignment();
9569     unsigned STAlign = ST->getAlignment();
9570     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9571     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9572     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9573       return SDValue();
9574
9575     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9576                                 LD->getChain(), LD->getBasePtr(),
9577                                 LD->getPointerInfo(),
9578                                 false, false, false, LDAlign);
9579
9580     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9581                                  NewLD, ST->getBasePtr(),
9582                                  ST->getPointerInfo(),
9583                                  false, false, STAlign);
9584
9585     AddToWorklist(NewLD.getNode());
9586     AddToWorklist(NewST.getNode());
9587     WorklistRemover DeadNodes(*this);
9588     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9589     ++LdStFP2Int;
9590     return NewST;
9591   }
9592
9593   return SDValue();
9594 }
9595
9596 /// Helper struct to parse and store a memory address as base + index + offset.
9597 /// We ignore sign extensions when it is safe to do so.
9598 /// The following two expressions are not equivalent. To differentiate we need
9599 /// to store whether there was a sign extension involved in the index
9600 /// computation.
9601 ///  (load (i64 add (i64 copyfromreg %c)
9602 ///                 (i64 signextend (add (i8 load %index)
9603 ///                                      (i8 1))))
9604 /// vs
9605 ///
9606 /// (load (i64 add (i64 copyfromreg %c)
9607 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9608 ///                                         (i32 1)))))
9609 struct BaseIndexOffset {
9610   SDValue Base;
9611   SDValue Index;
9612   int64_t Offset;
9613   bool IsIndexSignExt;
9614
9615   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9616
9617   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9618                   bool IsIndexSignExt) :
9619     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9620
9621   bool equalBaseIndex(const BaseIndexOffset &Other) {
9622     return Other.Base == Base && Other.Index == Index &&
9623       Other.IsIndexSignExt == IsIndexSignExt;
9624   }
9625
9626   /// Parses tree in Ptr for base, index, offset addresses.
9627   static BaseIndexOffset match(SDValue Ptr) {
9628     bool IsIndexSignExt = false;
9629
9630     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9631     // instruction, then it could be just the BASE or everything else we don't
9632     // know how to handle. Just use Ptr as BASE and give up.
9633     if (Ptr->getOpcode() != ISD::ADD)
9634       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9635
9636     // We know that we have at least an ADD instruction. Try to pattern match
9637     // the simple case of BASE + OFFSET.
9638     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9639       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9640       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9641                               IsIndexSignExt);
9642     }
9643
9644     // Inside a loop the current BASE pointer is calculated using an ADD and a
9645     // MUL instruction. In this case Ptr is the actual BASE pointer.
9646     // (i64 add (i64 %array_ptr)
9647     //          (i64 mul (i64 %induction_var)
9648     //                   (i64 %element_size)))
9649     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9650       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9651
9652     // Look at Base + Index + Offset cases.
9653     SDValue Base = Ptr->getOperand(0);
9654     SDValue IndexOffset = Ptr->getOperand(1);
9655
9656     // Skip signextends.
9657     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9658       IndexOffset = IndexOffset->getOperand(0);
9659       IsIndexSignExt = true;
9660     }
9661
9662     // Either the case of Base + Index (no offset) or something else.
9663     if (IndexOffset->getOpcode() != ISD::ADD)
9664       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9665
9666     // Now we have the case of Base + Index + offset.
9667     SDValue Index = IndexOffset->getOperand(0);
9668     SDValue Offset = IndexOffset->getOperand(1);
9669
9670     if (!isa<ConstantSDNode>(Offset))
9671       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9672
9673     // Ignore signextends.
9674     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9675       Index = Index->getOperand(0);
9676       IsIndexSignExt = true;
9677     } else IsIndexSignExt = false;
9678
9679     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9680     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9681   }
9682 };
9683
9684 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9685 /// is located in a sequence of memory operations connected by a chain.
9686 struct MemOpLink {
9687   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9688     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9689   // Ptr to the mem node.
9690   LSBaseSDNode *MemNode;
9691   // Offset from the base ptr.
9692   int64_t OffsetFromBase;
9693   // What is the sequence number of this mem node.
9694   // Lowest mem operand in the DAG starts at zero.
9695   unsigned SequenceNum;
9696 };
9697
9698 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9699   EVT MemVT = St->getMemoryVT();
9700   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9701   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9702     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9703
9704   // Don't merge vectors into wider inputs.
9705   if (MemVT.isVector() || !MemVT.isSimple())
9706     return false;
9707
9708   // Perform an early exit check. Do not bother looking at stored values that
9709   // are not constants or loads.
9710   SDValue StoredVal = St->getValue();
9711   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9712   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9713       !IsLoadSrc)
9714     return false;
9715
9716   // Only look at ends of store sequences.
9717   SDValue Chain = SDValue(St, 0);
9718   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9719     return false;
9720
9721   // This holds the base pointer, index, and the offset in bytes from the base
9722   // pointer.
9723   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9724
9725   // We must have a base and an offset.
9726   if (!BasePtr.Base.getNode())
9727     return false;
9728
9729   // Do not handle stores to undef base pointers.
9730   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9731     return false;
9732
9733   // Save the LoadSDNodes that we find in the chain.
9734   // We need to make sure that these nodes do not interfere with
9735   // any of the store nodes.
9736   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9737
9738   // Save the StoreSDNodes that we find in the chain.
9739   SmallVector<MemOpLink, 8> StoreNodes;
9740
9741   // Walk up the chain and look for nodes with offsets from the same
9742   // base pointer. Stop when reaching an instruction with a different kind
9743   // or instruction which has a different base pointer.
9744   unsigned Seq = 0;
9745   StoreSDNode *Index = St;
9746   while (Index) {
9747     // If the chain has more than one use, then we can't reorder the mem ops.
9748     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9749       break;
9750
9751     // Find the base pointer and offset for this memory node.
9752     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9753
9754     // Check that the base pointer is the same as the original one.
9755     if (!Ptr.equalBaseIndex(BasePtr))
9756       break;
9757
9758     // Check that the alignment is the same.
9759     if (Index->getAlignment() != St->getAlignment())
9760       break;
9761
9762     // The memory operands must not be volatile.
9763     if (Index->isVolatile() || Index->isIndexed())
9764       break;
9765
9766     // No truncation.
9767     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9768       if (St->isTruncatingStore())
9769         break;
9770
9771     // The stored memory type must be the same.
9772     if (Index->getMemoryVT() != MemVT)
9773       break;
9774
9775     // We do not allow unaligned stores because we want to prevent overriding
9776     // stores.
9777     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9778       break;
9779
9780     // We found a potential memory operand to merge.
9781     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9782
9783     // Find the next memory operand in the chain. If the next operand in the
9784     // chain is a store then move up and continue the scan with the next
9785     // memory operand. If the next operand is a load save it and use alias
9786     // information to check if it interferes with anything.
9787     SDNode *NextInChain = Index->getChain().getNode();
9788     while (1) {
9789       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9790         // We found a store node. Use it for the next iteration.
9791         Index = STn;
9792         break;
9793       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9794         if (Ldn->isVolatile()) {
9795           Index = nullptr;
9796           break;
9797         }
9798
9799         // Save the load node for later. Continue the scan.
9800         AliasLoadNodes.push_back(Ldn);
9801         NextInChain = Ldn->getChain().getNode();
9802         continue;
9803       } else {
9804         Index = nullptr;
9805         break;
9806       }
9807     }
9808   }
9809
9810   // Check if there is anything to merge.
9811   if (StoreNodes.size() < 2)
9812     return false;
9813
9814   // Sort the memory operands according to their distance from the base pointer.
9815   std::sort(StoreNodes.begin(), StoreNodes.end(),
9816             [](MemOpLink LHS, MemOpLink RHS) {
9817     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9818            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9819             LHS.SequenceNum > RHS.SequenceNum);
9820   });
9821
9822   // Scan the memory operations on the chain and find the first non-consecutive
9823   // store memory address.
9824   unsigned LastConsecutiveStore = 0;
9825   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9826   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9827
9828     // Check that the addresses are consecutive starting from the second
9829     // element in the list of stores.
9830     if (i > 0) {
9831       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9832       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9833         break;
9834     }
9835
9836     bool Alias = false;
9837     // Check if this store interferes with any of the loads that we found.
9838     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9839       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9840         Alias = true;
9841         break;
9842       }
9843     // We found a load that alias with this store. Stop the sequence.
9844     if (Alias)
9845       break;
9846
9847     // Mark this node as useful.
9848     LastConsecutiveStore = i;
9849   }
9850
9851   // The node with the lowest store address.
9852   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9853
9854   // Store the constants into memory as one consecutive store.
9855   if (!IsLoadSrc) {
9856     unsigned LastLegalType = 0;
9857     unsigned LastLegalVectorType = 0;
9858     bool NonZero = false;
9859     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9860       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9861       SDValue StoredVal = St->getValue();
9862
9863       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9864         NonZero |= !C->isNullValue();
9865       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9866         NonZero |= !C->getConstantFPValue()->isNullValue();
9867       } else {
9868         // Non-constant.
9869         break;
9870       }
9871
9872       // Find a legal type for the constant store.
9873       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9874       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9875       if (TLI.isTypeLegal(StoreTy))
9876         LastLegalType = i+1;
9877       // Or check whether a truncstore is legal.
9878       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9879                TargetLowering::TypePromoteInteger) {
9880         EVT LegalizedStoredValueTy =
9881           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9882         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9883           LastLegalType = i+1;
9884       }
9885
9886       // Find a legal type for the vector store.
9887       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9888       if (TLI.isTypeLegal(Ty))
9889         LastLegalVectorType = i + 1;
9890     }
9891
9892     // We only use vectors if the constant is known to be zero and the
9893     // function is not marked with the noimplicitfloat attribute.
9894     if (NonZero || NoVectors)
9895       LastLegalVectorType = 0;
9896
9897     // Check if we found a legal integer type to store.
9898     if (LastLegalType == 0 && LastLegalVectorType == 0)
9899       return false;
9900
9901     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9902     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9903
9904     // Make sure we have something to merge.
9905     if (NumElem < 2)
9906       return false;
9907
9908     unsigned EarliestNodeUsed = 0;
9909     for (unsigned i=0; i < NumElem; ++i) {
9910       // Find a chain for the new wide-store operand. Notice that some
9911       // of the store nodes that we found may not be selected for inclusion
9912       // in the wide store. The chain we use needs to be the chain of the
9913       // earliest store node which is *used* and replaced by the wide store.
9914       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9915         EarliestNodeUsed = i;
9916     }
9917
9918     // The earliest Node in the DAG.
9919     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9920     SDLoc DL(StoreNodes[0].MemNode);
9921
9922     SDValue StoredVal;
9923     if (UseVector) {
9924       // Find a legal type for the vector store.
9925       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9926       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9927       StoredVal = DAG.getConstant(0, Ty);
9928     } else {
9929       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9930       APInt StoreInt(StoreBW, 0);
9931
9932       // Construct a single integer constant which is made of the smaller
9933       // constant inputs.
9934       bool IsLE = TLI.isLittleEndian();
9935       for (unsigned i = 0; i < NumElem ; ++i) {
9936         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9937         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9938         SDValue Val = St->getValue();
9939         StoreInt<<=ElementSizeBytes*8;
9940         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9941           StoreInt|=C->getAPIntValue().zext(StoreBW);
9942         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9943           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9944         } else {
9945           llvm_unreachable("Invalid constant element type");
9946         }
9947       }
9948
9949       // Create the new Load and Store operations.
9950       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9951       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9952     }
9953
9954     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9955                                     FirstInChain->getBasePtr(),
9956                                     FirstInChain->getPointerInfo(),
9957                                     false, false,
9958                                     FirstInChain->getAlignment());
9959
9960     // Replace the first store with the new store
9961     CombineTo(EarliestOp, NewStore);
9962     // Erase all other stores.
9963     for (unsigned i = 0; i < NumElem ; ++i) {
9964       if (StoreNodes[i].MemNode == EarliestOp)
9965         continue;
9966       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9967       // ReplaceAllUsesWith will replace all uses that existed when it was
9968       // called, but graph optimizations may cause new ones to appear. For
9969       // example, the case in pr14333 looks like
9970       //
9971       //  St's chain -> St -> another store -> X
9972       //
9973       // And the only difference from St to the other store is the chain.
9974       // When we change it's chain to be St's chain they become identical,
9975       // get CSEed and the net result is that X is now a use of St.
9976       // Since we know that St is redundant, just iterate.
9977       while (!St->use_empty())
9978         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9979       deleteAndRecombine(St);
9980     }
9981
9982     return true;
9983   }
9984
9985   // Below we handle the case of multiple consecutive stores that
9986   // come from multiple consecutive loads. We merge them into a single
9987   // wide load and a single wide store.
9988
9989   // Look for load nodes which are used by the stored values.
9990   SmallVector<MemOpLink, 8> LoadNodes;
9991
9992   // Find acceptable loads. Loads need to have the same chain (token factor),
9993   // must not be zext, volatile, indexed, and they must be consecutive.
9994   BaseIndexOffset LdBasePtr;
9995   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9996     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9997     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9998     if (!Ld) break;
9999
10000     // Loads must only have one use.
10001     if (!Ld->hasNUsesOfValue(1, 0))
10002       break;
10003
10004     // Check that the alignment is the same as the stores.
10005     if (Ld->getAlignment() != St->getAlignment())
10006       break;
10007
10008     // The memory operands must not be volatile.
10009     if (Ld->isVolatile() || Ld->isIndexed())
10010       break;
10011
10012     // We do not accept ext loads.
10013     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
10014       break;
10015
10016     // The stored memory type must be the same.
10017     if (Ld->getMemoryVT() != MemVT)
10018       break;
10019
10020     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
10021     // If this is not the first ptr that we check.
10022     if (LdBasePtr.Base.getNode()) {
10023       // The base ptr must be the same.
10024       if (!LdPtr.equalBaseIndex(LdBasePtr))
10025         break;
10026     } else {
10027       // Check that all other base pointers are the same as this one.
10028       LdBasePtr = LdPtr;
10029     }
10030
10031     // We found a potential memory operand to merge.
10032     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
10033   }
10034
10035   if (LoadNodes.size() < 2)
10036     return false;
10037
10038   // If we have load/store pair instructions and we only have two values,
10039   // don't bother.
10040   unsigned RequiredAlignment;
10041   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
10042       St->getAlignment() >= RequiredAlignment)
10043     return false;
10044
10045   // Scan the memory operations on the chain and find the first non-consecutive
10046   // load memory address. These variables hold the index in the store node
10047   // array.
10048   unsigned LastConsecutiveLoad = 0;
10049   // This variable refers to the size and not index in the array.
10050   unsigned LastLegalVectorType = 0;
10051   unsigned LastLegalIntegerType = 0;
10052   StartAddress = LoadNodes[0].OffsetFromBase;
10053   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
10054   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
10055     // All loads much share the same chain.
10056     if (LoadNodes[i].MemNode->getChain() != FirstChain)
10057       break;
10058
10059     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
10060     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
10061       break;
10062     LastConsecutiveLoad = i;
10063
10064     // Find a legal type for the vector store.
10065     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
10066     if (TLI.isTypeLegal(StoreTy))
10067       LastLegalVectorType = i + 1;
10068
10069     // Find a legal type for the integer store.
10070     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
10071     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10072     if (TLI.isTypeLegal(StoreTy))
10073       LastLegalIntegerType = i + 1;
10074     // Or check whether a truncstore and extload is legal.
10075     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
10076              TargetLowering::TypePromoteInteger) {
10077       EVT LegalizedStoredValueTy =
10078         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
10079       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
10080           TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10081           TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValueTy, StoreTy) &&
10082           TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValueTy, StoreTy))
10083         LastLegalIntegerType = i+1;
10084     }
10085   }
10086
10087   // Only use vector types if the vector type is larger than the integer type.
10088   // If they are the same, use integers.
10089   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
10090   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
10091
10092   // We add +1 here because the LastXXX variables refer to location while
10093   // the NumElem refers to array/index size.
10094   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
10095   NumElem = std::min(LastLegalType, NumElem);
10096
10097   if (NumElem < 2)
10098     return false;
10099
10100   // The earliest Node in the DAG.
10101   unsigned EarliestNodeUsed = 0;
10102   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
10103   for (unsigned i=1; i<NumElem; ++i) {
10104     // Find a chain for the new wide-store operand. Notice that some
10105     // of the store nodes that we found may not be selected for inclusion
10106     // in the wide store. The chain we use needs to be the chain of the
10107     // earliest store node which is *used* and replaced by the wide store.
10108     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
10109       EarliestNodeUsed = i;
10110   }
10111
10112   // Find if it is better to use vectors or integers to load and store
10113   // to memory.
10114   EVT JointMemOpVT;
10115   if (UseVectorTy) {
10116     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
10117   } else {
10118     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
10119     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
10120   }
10121
10122   SDLoc LoadDL(LoadNodes[0].MemNode);
10123   SDLoc StoreDL(StoreNodes[0].MemNode);
10124
10125   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
10126   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
10127                                 FirstLoad->getChain(),
10128                                 FirstLoad->getBasePtr(),
10129                                 FirstLoad->getPointerInfo(),
10130                                 false, false, false,
10131                                 FirstLoad->getAlignment());
10132
10133   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
10134                                   FirstInChain->getBasePtr(),
10135                                   FirstInChain->getPointerInfo(), false, false,
10136                                   FirstInChain->getAlignment());
10137
10138   // Replace one of the loads with the new load.
10139   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
10140   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
10141                                 SDValue(NewLoad.getNode(), 1));
10142
10143   // Remove the rest of the load chains.
10144   for (unsigned i = 1; i < NumElem ; ++i) {
10145     // Replace all chain users of the old load nodes with the chain of the new
10146     // load node.
10147     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
10148     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
10149   }
10150
10151   // Replace the first store with the new store.
10152   CombineTo(EarliestOp, NewStore);
10153   // Erase all other stores.
10154   for (unsigned i = 0; i < NumElem ; ++i) {
10155     // Remove all Store nodes.
10156     if (StoreNodes[i].MemNode == EarliestOp)
10157       continue;
10158     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
10159     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
10160     deleteAndRecombine(St);
10161   }
10162
10163   return true;
10164 }
10165
10166 SDValue DAGCombiner::visitSTORE(SDNode *N) {
10167   StoreSDNode *ST  = cast<StoreSDNode>(N);
10168   SDValue Chain = ST->getChain();
10169   SDValue Value = ST->getValue();
10170   SDValue Ptr   = ST->getBasePtr();
10171
10172   // If this is a store of a bit convert, store the input value if the
10173   // resultant store does not need a higher alignment than the original.
10174   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
10175       ST->isUnindexed()) {
10176     unsigned OrigAlign = ST->getAlignment();
10177     EVT SVT = Value.getOperand(0).getValueType();
10178     unsigned Align = TLI.getDataLayout()->
10179       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
10180     if (Align <= OrigAlign &&
10181         ((!LegalOperations && !ST->isVolatile()) ||
10182          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
10183       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
10184                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
10185                           ST->isNonTemporal(), OrigAlign,
10186                           ST->getAAInfo());
10187   }
10188
10189   // Turn 'store undef, Ptr' -> nothing.
10190   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
10191     return Chain;
10192
10193   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
10194   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
10195     // NOTE: If the original store is volatile, this transform must not increase
10196     // the number of stores.  For example, on x86-32 an f64 can be stored in one
10197     // processor operation but an i64 (which is not legal) requires two.  So the
10198     // transform should not be done in this case.
10199     if (Value.getOpcode() != ISD::TargetConstantFP) {
10200       SDValue Tmp;
10201       switch (CFP->getSimpleValueType(0).SimpleTy) {
10202       default: llvm_unreachable("Unknown FP type");
10203       case MVT::f16:    // We don't do this for these yet.
10204       case MVT::f80:
10205       case MVT::f128:
10206       case MVT::ppcf128:
10207         break;
10208       case MVT::f32:
10209         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10210             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10211           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10212                               bitcastToAPInt().getZExtValue(), MVT::i32);
10213           return DAG.getStore(Chain, SDLoc(N), Tmp,
10214                               Ptr, ST->getMemOperand());
10215         }
10216         break;
10217       case MVT::f64:
10218         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10219              !ST->isVolatile()) ||
10220             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10221           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10222                                 getZExtValue(), MVT::i64);
10223           return DAG.getStore(Chain, SDLoc(N), Tmp,
10224                               Ptr, ST->getMemOperand());
10225         }
10226
10227         if (!ST->isVolatile() &&
10228             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10229           // Many FP stores are not made apparent until after legalize, e.g. for
10230           // argument passing.  Since this is so common, custom legalize the
10231           // 64-bit integer store into two 32-bit stores.
10232           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10233           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10234           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10235           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10236
10237           unsigned Alignment = ST->getAlignment();
10238           bool isVolatile = ST->isVolatile();
10239           bool isNonTemporal = ST->isNonTemporal();
10240           AAMDNodes AAInfo = ST->getAAInfo();
10241
10242           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10243                                      Ptr, ST->getPointerInfo(),
10244                                      isVolatile, isNonTemporal,
10245                                      ST->getAlignment(), AAInfo);
10246           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10247                             DAG.getConstant(4, Ptr.getValueType()));
10248           Alignment = MinAlign(Alignment, 4U);
10249           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10250                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10251                                      isVolatile, isNonTemporal,
10252                                      Alignment, AAInfo);
10253           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10254                              St0, St1);
10255         }
10256
10257         break;
10258       }
10259     }
10260   }
10261
10262   // Try to infer better alignment information than the store already has.
10263   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10264     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10265       if (Align > ST->getAlignment())
10266         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10267                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10268                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10269                                  ST->getAAInfo());
10270     }
10271   }
10272
10273   // Try transforming a pair floating point load / store ops to integer
10274   // load / store ops.
10275   SDValue NewST = TransformFPLoadStorePair(N);
10276   if (NewST.getNode())
10277     return NewST;
10278
10279   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10280                                                   : DAG.getSubtarget().useAA();
10281 #ifndef NDEBUG
10282   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10283       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10284     UseAA = false;
10285 #endif
10286   if (UseAA && ST->isUnindexed()) {
10287     // Walk up chain skipping non-aliasing memory nodes.
10288     SDValue BetterChain = FindBetterChain(N, Chain);
10289
10290     // If there is a better chain.
10291     if (Chain != BetterChain) {
10292       SDValue ReplStore;
10293
10294       // Replace the chain to avoid dependency.
10295       if (ST->isTruncatingStore()) {
10296         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10297                                       ST->getMemoryVT(), ST->getMemOperand());
10298       } else {
10299         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10300                                  ST->getMemOperand());
10301       }
10302
10303       // Create token to keep both nodes around.
10304       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10305                                   MVT::Other, Chain, ReplStore);
10306
10307       // Make sure the new and old chains are cleaned up.
10308       AddToWorklist(Token.getNode());
10309
10310       // Don't add users to work list.
10311       return CombineTo(N, Token, false);
10312     }
10313   }
10314
10315   // Try transforming N to an indexed store.
10316   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10317     return SDValue(N, 0);
10318
10319   // FIXME: is there such a thing as a truncating indexed store?
10320   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10321       Value.getValueType().isInteger()) {
10322     // See if we can simplify the input to this truncstore with knowledge that
10323     // only the low bits are being used.  For example:
10324     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10325     SDValue Shorter =
10326       GetDemandedBits(Value,
10327                       APInt::getLowBitsSet(
10328                         Value.getValueType().getScalarType().getSizeInBits(),
10329                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10330     AddToWorklist(Value.getNode());
10331     if (Shorter.getNode())
10332       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10333                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10334
10335     // Otherwise, see if we can simplify the operation with
10336     // SimplifyDemandedBits, which only works if the value has a single use.
10337     if (SimplifyDemandedBits(Value,
10338                         APInt::getLowBitsSet(
10339                           Value.getValueType().getScalarType().getSizeInBits(),
10340                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10341       return SDValue(N, 0);
10342   }
10343
10344   // If this is a load followed by a store to the same location, then the store
10345   // is dead/noop.
10346   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10347     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10348         ST->isUnindexed() && !ST->isVolatile() &&
10349         // There can't be any side effects between the load and store, such as
10350         // a call or store.
10351         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10352       // The store is dead, remove it.
10353       return Chain;
10354     }
10355   }
10356
10357   // If this is a store followed by a store with the same value to the same
10358   // location, then the store is dead/noop.
10359   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10360     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10361         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10362         ST1->isUnindexed() && !ST1->isVolatile()) {
10363       // The store is dead, remove it.
10364       return Chain;
10365     }
10366   }
10367
10368   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10369   // truncating store.  We can do this even if this is already a truncstore.
10370   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10371       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10372       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10373                             ST->getMemoryVT())) {
10374     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10375                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10376   }
10377
10378   // Only perform this optimization before the types are legal, because we
10379   // don't want to perform this optimization on every DAGCombine invocation.
10380   if (!LegalTypes) {
10381     bool EverChanged = false;
10382
10383     do {
10384       // There can be multiple store sequences on the same chain.
10385       // Keep trying to merge store sequences until we are unable to do so
10386       // or until we merge the last store on the chain.
10387       bool Changed = MergeConsecutiveStores(ST);
10388       EverChanged |= Changed;
10389       if (!Changed) break;
10390     } while (ST->getOpcode() != ISD::DELETED_NODE);
10391
10392     if (EverChanged)
10393       return SDValue(N, 0);
10394   }
10395
10396   return ReduceLoadOpStoreWidth(N);
10397 }
10398
10399 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10400   SDValue InVec = N->getOperand(0);
10401   SDValue InVal = N->getOperand(1);
10402   SDValue EltNo = N->getOperand(2);
10403   SDLoc dl(N);
10404
10405   // If the inserted element is an UNDEF, just use the input vector.
10406   if (InVal.getOpcode() == ISD::UNDEF)
10407     return InVec;
10408
10409   EVT VT = InVec.getValueType();
10410
10411   // If we can't generate a legal BUILD_VECTOR, exit
10412   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10413     return SDValue();
10414
10415   // Check that we know which element is being inserted
10416   if (!isa<ConstantSDNode>(EltNo))
10417     return SDValue();
10418   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10419
10420   // Canonicalize insert_vector_elt dag nodes.
10421   // Example:
10422   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10423   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10424   //
10425   // Do this only if the child insert_vector node has one use; also
10426   // do this only if indices are both constants and Idx1 < Idx0.
10427   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10428       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10429     unsigned OtherElt =
10430       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10431     if (Elt < OtherElt) {
10432       // Swap nodes.
10433       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10434                                   InVec.getOperand(0), InVal, EltNo);
10435       AddToWorklist(NewOp.getNode());
10436       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10437                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10438     }
10439   }
10440
10441   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10442   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10443   // vector elements.
10444   SmallVector<SDValue, 8> Ops;
10445   // Do not combine these two vectors if the output vector will not replace
10446   // the input vector.
10447   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10448     Ops.append(InVec.getNode()->op_begin(),
10449                InVec.getNode()->op_end());
10450   } else if (InVec.getOpcode() == ISD::UNDEF) {
10451     unsigned NElts = VT.getVectorNumElements();
10452     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10453   } else {
10454     return SDValue();
10455   }
10456
10457   // Insert the element
10458   if (Elt < Ops.size()) {
10459     // All the operands of BUILD_VECTOR must have the same type;
10460     // we enforce that here.
10461     EVT OpVT = Ops[0].getValueType();
10462     if (InVal.getValueType() != OpVT)
10463       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10464                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10465                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10466     Ops[Elt] = InVal;
10467   }
10468
10469   // Return the new vector
10470   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10471 }
10472
10473 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10474     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10475   EVT ResultVT = EVE->getValueType(0);
10476   EVT VecEltVT = InVecVT.getVectorElementType();
10477   unsigned Align = OriginalLoad->getAlignment();
10478   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10479       VecEltVT.getTypeForEVT(*DAG.getContext()));
10480
10481   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10482     return SDValue();
10483
10484   Align = NewAlign;
10485
10486   SDValue NewPtr = OriginalLoad->getBasePtr();
10487   SDValue Offset;
10488   EVT PtrType = NewPtr.getValueType();
10489   MachinePointerInfo MPI;
10490   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10491     int Elt = ConstEltNo->getZExtValue();
10492     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10493     if (TLI.isBigEndian())
10494       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10495     Offset = DAG.getConstant(PtrOff, PtrType);
10496     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10497   } else {
10498     Offset = DAG.getNode(
10499         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10500         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10501     if (TLI.isBigEndian())
10502       Offset = DAG.getNode(
10503           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10504           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10505     MPI = OriginalLoad->getPointerInfo();
10506   }
10507   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10508
10509   // The replacement we need to do here is a little tricky: we need to
10510   // replace an extractelement of a load with a load.
10511   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10512   // Note that this replacement assumes that the extractvalue is the only
10513   // use of the load; that's okay because we don't want to perform this
10514   // transformation in other cases anyway.
10515   SDValue Load;
10516   SDValue Chain;
10517   if (ResultVT.bitsGT(VecEltVT)) {
10518     // If the result type of vextract is wider than the load, then issue an
10519     // extending load instead.
10520     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
10521                                                   VecEltVT)
10522                                    ? ISD::ZEXTLOAD
10523                                    : ISD::EXTLOAD;
10524     Load = DAG.getExtLoad(
10525         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10526         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10527         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10528     Chain = Load.getValue(1);
10529   } else {
10530     Load = DAG.getLoad(
10531         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10532         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10533         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10534     Chain = Load.getValue(1);
10535     if (ResultVT.bitsLT(VecEltVT))
10536       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10537     else
10538       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10539   }
10540   WorklistRemover DeadNodes(*this);
10541   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10542   SDValue To[] = { Load, Chain };
10543   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10544   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10545   // worklist explicitly as well.
10546   AddToWorklist(Load.getNode());
10547   AddUsersToWorklist(Load.getNode()); // Add users too
10548   // Make sure to revisit this node to clean it up; it will usually be dead.
10549   AddToWorklist(EVE);
10550   ++OpsNarrowed;
10551   return SDValue(EVE, 0);
10552 }
10553
10554 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10555   // (vextract (scalar_to_vector val, 0) -> val
10556   SDValue InVec = N->getOperand(0);
10557   EVT VT = InVec.getValueType();
10558   EVT NVT = N->getValueType(0);
10559
10560   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10561     // Check if the result type doesn't match the inserted element type. A
10562     // SCALAR_TO_VECTOR may truncate the inserted element and the
10563     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10564     SDValue InOp = InVec.getOperand(0);
10565     if (InOp.getValueType() != NVT) {
10566       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10567       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10568     }
10569     return InOp;
10570   }
10571
10572   SDValue EltNo = N->getOperand(1);
10573   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10574
10575   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10576   // We only perform this optimization before the op legalization phase because
10577   // we may introduce new vector instructions which are not backed by TD
10578   // patterns. For example on AVX, extracting elements from a wide vector
10579   // without using extract_subvector. However, if we can find an underlying
10580   // scalar value, then we can always use that.
10581   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10582       && ConstEltNo) {
10583     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10584     int NumElem = VT.getVectorNumElements();
10585     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10586     // Find the new index to extract from.
10587     int OrigElt = SVOp->getMaskElt(Elt);
10588
10589     // Extracting an undef index is undef.
10590     if (OrigElt == -1)
10591       return DAG.getUNDEF(NVT);
10592
10593     // Select the right vector half to extract from.
10594     SDValue SVInVec;
10595     if (OrigElt < NumElem) {
10596       SVInVec = InVec->getOperand(0);
10597     } else {
10598       SVInVec = InVec->getOperand(1);
10599       OrigElt -= NumElem;
10600     }
10601
10602     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10603       SDValue InOp = SVInVec.getOperand(OrigElt);
10604       if (InOp.getValueType() != NVT) {
10605         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10606         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10607       }
10608
10609       return InOp;
10610     }
10611
10612     // FIXME: We should handle recursing on other vector shuffles and
10613     // scalar_to_vector here as well.
10614
10615     if (!LegalOperations) {
10616       EVT IndexTy = TLI.getVectorIdxTy();
10617       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10618                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10619     }
10620   }
10621
10622   bool BCNumEltsChanged = false;
10623   EVT ExtVT = VT.getVectorElementType();
10624   EVT LVT = ExtVT;
10625
10626   // If the result of load has to be truncated, then it's not necessarily
10627   // profitable.
10628   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10629     return SDValue();
10630
10631   if (InVec.getOpcode() == ISD::BITCAST) {
10632     // Don't duplicate a load with other uses.
10633     if (!InVec.hasOneUse())
10634       return SDValue();
10635
10636     EVT BCVT = InVec.getOperand(0).getValueType();
10637     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10638       return SDValue();
10639     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10640       BCNumEltsChanged = true;
10641     InVec = InVec.getOperand(0);
10642     ExtVT = BCVT.getVectorElementType();
10643   }
10644
10645   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10646   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10647       ISD::isNormalLoad(InVec.getNode()) &&
10648       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10649     SDValue Index = N->getOperand(1);
10650     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10651       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10652                                                            OrigLoad);
10653   }
10654
10655   // Perform only after legalization to ensure build_vector / vector_shuffle
10656   // optimizations have already been done.
10657   if (!LegalOperations) return SDValue();
10658
10659   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10660   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10661   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10662
10663   if (ConstEltNo) {
10664     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10665
10666     LoadSDNode *LN0 = nullptr;
10667     const ShuffleVectorSDNode *SVN = nullptr;
10668     if (ISD::isNormalLoad(InVec.getNode())) {
10669       LN0 = cast<LoadSDNode>(InVec);
10670     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10671                InVec.getOperand(0).getValueType() == ExtVT &&
10672                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10673       // Don't duplicate a load with other uses.
10674       if (!InVec.hasOneUse())
10675         return SDValue();
10676
10677       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10678     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10679       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10680       // =>
10681       // (load $addr+1*size)
10682
10683       // Don't duplicate a load with other uses.
10684       if (!InVec.hasOneUse())
10685         return SDValue();
10686
10687       // If the bit convert changed the number of elements, it is unsafe
10688       // to examine the mask.
10689       if (BCNumEltsChanged)
10690         return SDValue();
10691
10692       // Select the input vector, guarding against out of range extract vector.
10693       unsigned NumElems = VT.getVectorNumElements();
10694       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10695       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10696
10697       if (InVec.getOpcode() == ISD::BITCAST) {
10698         // Don't duplicate a load with other uses.
10699         if (!InVec.hasOneUse())
10700           return SDValue();
10701
10702         InVec = InVec.getOperand(0);
10703       }
10704       if (ISD::isNormalLoad(InVec.getNode())) {
10705         LN0 = cast<LoadSDNode>(InVec);
10706         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10707         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10708       }
10709     }
10710
10711     // Make sure we found a non-volatile load and the extractelement is
10712     // the only use.
10713     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10714       return SDValue();
10715
10716     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10717     if (Elt == -1)
10718       return DAG.getUNDEF(LVT);
10719
10720     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10721   }
10722
10723   return SDValue();
10724 }
10725
10726 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10727 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10728   // We perform this optimization post type-legalization because
10729   // the type-legalizer often scalarizes integer-promoted vectors.
10730   // Performing this optimization before may create bit-casts which
10731   // will be type-legalized to complex code sequences.
10732   // We perform this optimization only before the operation legalizer because we
10733   // may introduce illegal operations.
10734   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10735     return SDValue();
10736
10737   unsigned NumInScalars = N->getNumOperands();
10738   SDLoc dl(N);
10739   EVT VT = N->getValueType(0);
10740
10741   // Check to see if this is a BUILD_VECTOR of a bunch of values
10742   // which come from any_extend or zero_extend nodes. If so, we can create
10743   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10744   // optimizations. We do not handle sign-extend because we can't fill the sign
10745   // using shuffles.
10746   EVT SourceType = MVT::Other;
10747   bool AllAnyExt = true;
10748
10749   for (unsigned i = 0; i != NumInScalars; ++i) {
10750     SDValue In = N->getOperand(i);
10751     // Ignore undef inputs.
10752     if (In.getOpcode() == ISD::UNDEF) continue;
10753
10754     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10755     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10756
10757     // Abort if the element is not an extension.
10758     if (!ZeroExt && !AnyExt) {
10759       SourceType = MVT::Other;
10760       break;
10761     }
10762
10763     // The input is a ZeroExt or AnyExt. Check the original type.
10764     EVT InTy = In.getOperand(0).getValueType();
10765
10766     // Check that all of the widened source types are the same.
10767     if (SourceType == MVT::Other)
10768       // First time.
10769       SourceType = InTy;
10770     else if (InTy != SourceType) {
10771       // Multiple income types. Abort.
10772       SourceType = MVT::Other;
10773       break;
10774     }
10775
10776     // Check if all of the extends are ANY_EXTENDs.
10777     AllAnyExt &= AnyExt;
10778   }
10779
10780   // In order to have valid types, all of the inputs must be extended from the
10781   // same source type and all of the inputs must be any or zero extend.
10782   // Scalar sizes must be a power of two.
10783   EVT OutScalarTy = VT.getScalarType();
10784   bool ValidTypes = SourceType != MVT::Other &&
10785                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10786                  isPowerOf2_32(SourceType.getSizeInBits());
10787
10788   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10789   // turn into a single shuffle instruction.
10790   if (!ValidTypes)
10791     return SDValue();
10792
10793   bool isLE = TLI.isLittleEndian();
10794   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10795   assert(ElemRatio > 1 && "Invalid element size ratio");
10796   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10797                                DAG.getConstant(0, SourceType);
10798
10799   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10800   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10801
10802   // Populate the new build_vector
10803   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10804     SDValue Cast = N->getOperand(i);
10805     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10806             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10807             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10808     SDValue In;
10809     if (Cast.getOpcode() == ISD::UNDEF)
10810       In = DAG.getUNDEF(SourceType);
10811     else
10812       In = Cast->getOperand(0);
10813     unsigned Index = isLE ? (i * ElemRatio) :
10814                             (i * ElemRatio + (ElemRatio - 1));
10815
10816     assert(Index < Ops.size() && "Invalid index");
10817     Ops[Index] = In;
10818   }
10819
10820   // The type of the new BUILD_VECTOR node.
10821   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10822   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10823          "Invalid vector size");
10824   // Check if the new vector type is legal.
10825   if (!isTypeLegal(VecVT)) return SDValue();
10826
10827   // Make the new BUILD_VECTOR.
10828   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10829
10830   // The new BUILD_VECTOR node has the potential to be further optimized.
10831   AddToWorklist(BV.getNode());
10832   // Bitcast to the desired type.
10833   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10834 }
10835
10836 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10837   EVT VT = N->getValueType(0);
10838
10839   unsigned NumInScalars = N->getNumOperands();
10840   SDLoc dl(N);
10841
10842   EVT SrcVT = MVT::Other;
10843   unsigned Opcode = ISD::DELETED_NODE;
10844   unsigned NumDefs = 0;
10845
10846   for (unsigned i = 0; i != NumInScalars; ++i) {
10847     SDValue In = N->getOperand(i);
10848     unsigned Opc = In.getOpcode();
10849
10850     if (Opc == ISD::UNDEF)
10851       continue;
10852
10853     // If all scalar values are floats and converted from integers.
10854     if (Opcode == ISD::DELETED_NODE &&
10855         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10856       Opcode = Opc;
10857     }
10858
10859     if (Opc != Opcode)
10860       return SDValue();
10861
10862     EVT InVT = In.getOperand(0).getValueType();
10863
10864     // If all scalar values are typed differently, bail out. It's chosen to
10865     // simplify BUILD_VECTOR of integer types.
10866     if (SrcVT == MVT::Other)
10867       SrcVT = InVT;
10868     if (SrcVT != InVT)
10869       return SDValue();
10870     NumDefs++;
10871   }
10872
10873   // If the vector has just one element defined, it's not worth to fold it into
10874   // a vectorized one.
10875   if (NumDefs < 2)
10876     return SDValue();
10877
10878   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10879          && "Should only handle conversion from integer to float.");
10880   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10881
10882   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10883
10884   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10885     return SDValue();
10886
10887   SmallVector<SDValue, 8> Opnds;
10888   for (unsigned i = 0; i != NumInScalars; ++i) {
10889     SDValue In = N->getOperand(i);
10890
10891     if (In.getOpcode() == ISD::UNDEF)
10892       Opnds.push_back(DAG.getUNDEF(SrcVT));
10893     else
10894       Opnds.push_back(In.getOperand(0));
10895   }
10896   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10897   AddToWorklist(BV.getNode());
10898
10899   return DAG.getNode(Opcode, dl, VT, BV);
10900 }
10901
10902 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10903   unsigned NumInScalars = N->getNumOperands();
10904   SDLoc dl(N);
10905   EVT VT = N->getValueType(0);
10906
10907   // A vector built entirely of undefs is undef.
10908   if (ISD::allOperandsUndef(N))
10909     return DAG.getUNDEF(VT);
10910
10911   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10912   if (V.getNode())
10913     return V;
10914
10915   V = reduceBuildVecConvertToConvertBuildVec(N);
10916   if (V.getNode())
10917     return V;
10918
10919   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10920   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10921   // at most two distinct vectors, turn this into a shuffle node.
10922
10923   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10924   if (!isTypeLegal(VT))
10925     return SDValue();
10926
10927   // May only combine to shuffle after legalize if shuffle is legal.
10928   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10929     return SDValue();
10930
10931   SDValue VecIn1, VecIn2;
10932   bool UsesZeroVector = false;
10933   for (unsigned i = 0; i != NumInScalars; ++i) {
10934     SDValue Op = N->getOperand(i);
10935     // Ignore undef inputs.
10936     if (Op.getOpcode() == ISD::UNDEF) continue;
10937
10938     // See if we can combine this build_vector into a blend with a zero vector.
10939     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10940         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10941         (Op.getOpcode() == ISD::ConstantFP &&
10942         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10943       UsesZeroVector = true;
10944       continue;
10945     }
10946
10947     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10948     // constant index, bail out.
10949     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10950         !isa<ConstantSDNode>(Op.getOperand(1))) {
10951       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10952       break;
10953     }
10954
10955     // We allow up to two distinct input vectors.
10956     SDValue ExtractedFromVec = Op.getOperand(0);
10957     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10958       continue;
10959
10960     if (!VecIn1.getNode()) {
10961       VecIn1 = ExtractedFromVec;
10962     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10963       VecIn2 = ExtractedFromVec;
10964     } else {
10965       // Too many inputs.
10966       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10967       break;
10968     }
10969   }
10970
10971   // If everything is good, we can make a shuffle operation.
10972   if (VecIn1.getNode()) {
10973     unsigned InNumElements = VecIn1.getValueType().getVectorNumElements();
10974     SmallVector<int, 8> Mask;
10975     for (unsigned i = 0; i != NumInScalars; ++i) {
10976       unsigned Opcode = N->getOperand(i).getOpcode();
10977       if (Opcode == ISD::UNDEF) {
10978         Mask.push_back(-1);
10979         continue;
10980       }
10981
10982       // Operands can also be zero.
10983       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10984         assert(UsesZeroVector &&
10985                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10986                "Unexpected node found!");
10987         Mask.push_back(NumInScalars+i);
10988         continue;
10989       }
10990
10991       // If extracting from the first vector, just use the index directly.
10992       SDValue Extract = N->getOperand(i);
10993       SDValue ExtVal = Extract.getOperand(1);
10994       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10995       if (Extract.getOperand(0) == VecIn1) {
10996         Mask.push_back(ExtIndex);
10997         continue;
10998       }
10999
11000       // Otherwise, use InIdx + InputVecSize
11001       Mask.push_back(InNumElements + ExtIndex);
11002     }
11003
11004     // Avoid introducing illegal shuffles with zero.
11005     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
11006       return SDValue();
11007
11008     // We can't generate a shuffle node with mismatched input and output types.
11009     // Attempt to transform a single input vector to the correct type.
11010     if ((VT != VecIn1.getValueType())) {
11011       // If the input vector type has a different base type to the output
11012       // vector type, bail out.
11013       EVT VTElemType = VT.getVectorElementType();
11014       if ((VecIn1.getValueType().getVectorElementType() != VTElemType) ||
11015           (VecIn2.getNode() &&
11016            (VecIn2.getValueType().getVectorElementType() != VTElemType)))
11017         return SDValue();
11018
11019       // If the input vector is too small, widen it.
11020       // We only support widening of vectors which are half the size of the
11021       // output registers. For example XMM->YMM widening on X86 with AVX.
11022       EVT VecInT = VecIn1.getValueType();
11023       if (VecInT.getSizeInBits() * 2 == VT.getSizeInBits()) {
11024         // If we only have one small input, widen it by adding undef values.
11025         if (!VecIn2.getNode())
11026           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1,
11027                                DAG.getUNDEF(VecIn1.getValueType()));
11028         else if (VecIn1.getValueType() == VecIn2.getValueType()) {
11029           // If we have two small inputs of the same type, try to concat them.
11030           VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT, VecIn1, VecIn2);
11031           VecIn2 = SDValue(nullptr, 0);
11032         } else
11033           return SDValue();
11034       } else if (VecInT.getSizeInBits() == VT.getSizeInBits() * 2) {
11035         // If the input vector is too large, try to split it.
11036         // We don't support having two input vectors that are too large.
11037         if (VecIn2.getNode())
11038           return SDValue();
11039
11040         if (!TLI.isExtractSubvectorCheap(VT, VT.getVectorNumElements()))
11041           return SDValue();
11042         
11043         // Try to replace VecIn1 with two extract_subvectors
11044         // No need to update the masks, they should still be correct.
11045         VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1, 
11046           DAG.getConstant(VT.getVectorNumElements(), TLI.getVectorIdxTy()));
11047         VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, VecIn1,
11048           DAG.getConstant(0, TLI.getVectorIdxTy()));
11049         UsesZeroVector = false;
11050       } else
11051         return SDValue();
11052     }
11053
11054     if (UsesZeroVector)
11055       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
11056                                 DAG.getConstantFP(0.0, VT);
11057     else
11058       // If VecIn2 is unused then change it to undef.
11059       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
11060
11061     // Check that we were able to transform all incoming values to the same
11062     // type.
11063     if (VecIn2.getValueType() != VecIn1.getValueType() ||
11064         VecIn1.getValueType() != VT)
11065           return SDValue();
11066
11067     // Return the new VECTOR_SHUFFLE node.
11068     SDValue Ops[2];
11069     Ops[0] = VecIn1;
11070     Ops[1] = VecIn2;
11071     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
11072   }
11073
11074   return SDValue();
11075 }
11076
11077 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
11078   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
11079   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
11080   // inputs come from at most two distinct vectors, turn this into a shuffle
11081   // node.
11082
11083   // If we only have one input vector, we don't need to do any concatenation.
11084   if (N->getNumOperands() == 1)
11085     return N->getOperand(0);
11086
11087   // Check if all of the operands are undefs.
11088   EVT VT = N->getValueType(0);
11089   if (ISD::allOperandsUndef(N))
11090     return DAG.getUNDEF(VT);
11091
11092   // Optimize concat_vectors where one of the vectors is undef.
11093   if (N->getNumOperands() == 2 &&
11094       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
11095     SDValue In = N->getOperand(0);
11096     assert(In.getValueType().isVector() && "Must concat vectors");
11097
11098     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
11099     if (In->getOpcode() == ISD::BITCAST &&
11100         !In->getOperand(0)->getValueType(0).isVector()) {
11101       SDValue Scalar = In->getOperand(0);
11102       EVT SclTy = Scalar->getValueType(0);
11103
11104       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
11105         return SDValue();
11106
11107       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
11108                                  VT.getSizeInBits() / SclTy.getSizeInBits());
11109       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
11110         return SDValue();
11111
11112       SDLoc dl = SDLoc(N);
11113       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
11114       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
11115     }
11116   }
11117
11118   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
11119   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
11120   if (N->getNumOperands() == 2 &&
11121       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
11122       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
11123     EVT VT = N->getValueType(0);
11124     SDValue N0 = N->getOperand(0);
11125     SDValue N1 = N->getOperand(1);
11126     SmallVector<SDValue, 8> Opnds;
11127     unsigned BuildVecNumElts =  N0.getNumOperands();
11128
11129     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
11130     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
11131     if (SclTy0.isFloatingPoint()) {
11132       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11133         Opnds.push_back(N0.getOperand(i));
11134       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11135         Opnds.push_back(N1.getOperand(i));
11136     } else {
11137       // If BUILD_VECTOR are from built from integer, they may have different
11138       // operand types. Get the smaller type and truncate all operands to it.
11139       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
11140       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11141         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11142                         N0.getOperand(i)));
11143       for (unsigned i = 0; i != BuildVecNumElts; ++i)
11144         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
11145                         N1.getOperand(i)));
11146     }
11147
11148     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
11149   }
11150
11151   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
11152   // nodes often generate nop CONCAT_VECTOR nodes.
11153   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
11154   // place the incoming vectors at the exact same location.
11155   SDValue SingleSource = SDValue();
11156   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
11157
11158   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
11159     SDValue Op = N->getOperand(i);
11160
11161     if (Op.getOpcode() == ISD::UNDEF)
11162       continue;
11163
11164     // Check if this is the identity extract:
11165     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
11166       return SDValue();
11167
11168     // Find the single incoming vector for the extract_subvector.
11169     if (SingleSource.getNode()) {
11170       if (Op.getOperand(0) != SingleSource)
11171         return SDValue();
11172     } else {
11173       SingleSource = Op.getOperand(0);
11174
11175       // Check the source type is the same as the type of the result.
11176       // If not, this concat may extend the vector, so we can not
11177       // optimize it away.
11178       if (SingleSource.getValueType() != N->getValueType(0))
11179         return SDValue();
11180     }
11181
11182     unsigned IdentityIndex = i * PartNumElem;
11183     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
11184     // The extract index must be constant.
11185     if (!CS)
11186       return SDValue();
11187
11188     // Check that we are reading from the identity index.
11189     if (CS->getZExtValue() != IdentityIndex)
11190       return SDValue();
11191   }
11192
11193   if (SingleSource.getNode())
11194     return SingleSource;
11195
11196   return SDValue();
11197 }
11198
11199 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
11200   EVT NVT = N->getValueType(0);
11201   SDValue V = N->getOperand(0);
11202
11203   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
11204     // Combine:
11205     //    (extract_subvec (concat V1, V2, ...), i)
11206     // Into:
11207     //    Vi if possible
11208     // Only operand 0 is checked as 'concat' assumes all inputs of the same
11209     // type.
11210     if (V->getOperand(0).getValueType() != NVT)
11211       return SDValue();
11212     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
11213     unsigned NumElems = NVT.getVectorNumElements();
11214     assert((Idx % NumElems) == 0 &&
11215            "IDX in concat is not a multiple of the result vector length.");
11216     return V->getOperand(Idx / NumElems);
11217   }
11218
11219   // Skip bitcasting
11220   if (V->getOpcode() == ISD::BITCAST)
11221     V = V.getOperand(0);
11222
11223   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
11224     SDLoc dl(N);
11225     // Handle only simple case where vector being inserted and vector
11226     // being extracted are of same type, and are half size of larger vectors.
11227     EVT BigVT = V->getOperand(0).getValueType();
11228     EVT SmallVT = V->getOperand(1).getValueType();
11229     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
11230       return SDValue();
11231
11232     // Only handle cases where both indexes are constants with the same type.
11233     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11234     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11235
11236     if (InsIdx && ExtIdx &&
11237         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11238         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11239       // Combine:
11240       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11241       // Into:
11242       //    indices are equal or bit offsets are equal => V1
11243       //    otherwise => (extract_subvec V1, ExtIdx)
11244       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11245           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11246         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11247       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11248                          DAG.getNode(ISD::BITCAST, dl,
11249                                      N->getOperand(0).getValueType(),
11250                                      V->getOperand(0)), N->getOperand(1));
11251     }
11252   }
11253
11254   return SDValue();
11255 }
11256
11257 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11258                                                  SDValue V, SelectionDAG &DAG) {
11259   SDLoc DL(V);
11260   EVT VT = V.getValueType();
11261
11262   switch (V.getOpcode()) {
11263   default:
11264     return V;
11265
11266   case ISD::CONCAT_VECTORS: {
11267     EVT OpVT = V->getOperand(0).getValueType();
11268     int OpSize = OpVT.getVectorNumElements();
11269     SmallBitVector OpUsedElements(OpSize, false);
11270     bool FoundSimplification = false;
11271     SmallVector<SDValue, 4> NewOps;
11272     NewOps.reserve(V->getNumOperands());
11273     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11274       SDValue Op = V->getOperand(i);
11275       bool OpUsed = false;
11276       for (int j = 0; j < OpSize; ++j)
11277         if (UsedElements[i * OpSize + j]) {
11278           OpUsedElements[j] = true;
11279           OpUsed = true;
11280         }
11281       NewOps.push_back(
11282           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11283                  : DAG.getUNDEF(OpVT));
11284       FoundSimplification |= Op == NewOps.back();
11285       OpUsedElements.reset();
11286     }
11287     if (FoundSimplification)
11288       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11289     return V;
11290   }
11291
11292   case ISD::INSERT_SUBVECTOR: {
11293     SDValue BaseV = V->getOperand(0);
11294     SDValue SubV = V->getOperand(1);
11295     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11296     if (!IdxN)
11297       return V;
11298
11299     int SubSize = SubV.getValueType().getVectorNumElements();
11300     int Idx = IdxN->getZExtValue();
11301     bool SubVectorUsed = false;
11302     SmallBitVector SubUsedElements(SubSize, false);
11303     for (int i = 0; i < SubSize; ++i)
11304       if (UsedElements[i + Idx]) {
11305         SubVectorUsed = true;
11306         SubUsedElements[i] = true;
11307         UsedElements[i + Idx] = false;
11308       }
11309
11310     // Now recurse on both the base and sub vectors.
11311     SDValue SimplifiedSubV =
11312         SubVectorUsed
11313             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11314             : DAG.getUNDEF(SubV.getValueType());
11315     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11316     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11317       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11318                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11319     return V;
11320   }
11321   }
11322 }
11323
11324 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11325                                        SDValue N1, SelectionDAG &DAG) {
11326   EVT VT = SVN->getValueType(0);
11327   int NumElts = VT.getVectorNumElements();
11328   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11329   for (int M : SVN->getMask())
11330     if (M >= 0 && M < NumElts)
11331       N0UsedElements[M] = true;
11332     else if (M >= NumElts)
11333       N1UsedElements[M - NumElts] = true;
11334
11335   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11336   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11337   if (S0 == N0 && S1 == N1)
11338     return SDValue();
11339
11340   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11341 }
11342
11343 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11344 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11345   EVT VT = N->getValueType(0);
11346   unsigned NumElts = VT.getVectorNumElements();
11347
11348   SDValue N0 = N->getOperand(0);
11349   SDValue N1 = N->getOperand(1);
11350   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11351
11352   SmallVector<SDValue, 4> Ops;
11353   EVT ConcatVT = N0.getOperand(0).getValueType();
11354   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11355   unsigned NumConcats = NumElts / NumElemsPerConcat;
11356
11357   // Look at every vector that's inserted. We're looking for exact
11358   // subvector-sized copies from a concatenated vector
11359   for (unsigned I = 0; I != NumConcats; ++I) {
11360     // Make sure we're dealing with a copy.
11361     unsigned Begin = I * NumElemsPerConcat;
11362     bool AllUndef = true, NoUndef = true;
11363     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11364       if (SVN->getMaskElt(J) >= 0)
11365         AllUndef = false;
11366       else
11367         NoUndef = false;
11368     }
11369
11370     if (NoUndef) {
11371       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11372         return SDValue();
11373
11374       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11375         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11376           return SDValue();
11377
11378       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11379       if (FirstElt < N0.getNumOperands())
11380         Ops.push_back(N0.getOperand(FirstElt));
11381       else
11382         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11383
11384     } else if (AllUndef) {
11385       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11386     } else { // Mixed with general masks and undefs, can't do optimization.
11387       return SDValue();
11388     }
11389   }
11390
11391   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11392 }
11393
11394 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11395   EVT VT = N->getValueType(0);
11396   unsigned NumElts = VT.getVectorNumElements();
11397
11398   SDValue N0 = N->getOperand(0);
11399   SDValue N1 = N->getOperand(1);
11400
11401   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11402
11403   // Canonicalize shuffle undef, undef -> undef
11404   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11405     return DAG.getUNDEF(VT);
11406
11407   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11408
11409   // Canonicalize shuffle v, v -> v, undef
11410   if (N0 == N1) {
11411     SmallVector<int, 8> NewMask;
11412     for (unsigned i = 0; i != NumElts; ++i) {
11413       int Idx = SVN->getMaskElt(i);
11414       if (Idx >= (int)NumElts) Idx -= NumElts;
11415       NewMask.push_back(Idx);
11416     }
11417     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11418                                 &NewMask[0]);
11419   }
11420
11421   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11422   if (N0.getOpcode() == ISD::UNDEF) {
11423     SmallVector<int, 8> NewMask;
11424     for (unsigned i = 0; i != NumElts; ++i) {
11425       int Idx = SVN->getMaskElt(i);
11426       if (Idx >= 0) {
11427         if (Idx >= (int)NumElts)
11428           Idx -= NumElts;
11429         else
11430           Idx = -1; // remove reference to lhs
11431       }
11432       NewMask.push_back(Idx);
11433     }
11434     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11435                                 &NewMask[0]);
11436   }
11437
11438   // Remove references to rhs if it is undef
11439   if (N1.getOpcode() == ISD::UNDEF) {
11440     bool Changed = false;
11441     SmallVector<int, 8> NewMask;
11442     for (unsigned i = 0; i != NumElts; ++i) {
11443       int Idx = SVN->getMaskElt(i);
11444       if (Idx >= (int)NumElts) {
11445         Idx = -1;
11446         Changed = true;
11447       }
11448       NewMask.push_back(Idx);
11449     }
11450     if (Changed)
11451       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11452   }
11453
11454   // If it is a splat, check if the argument vector is another splat or a
11455   // build_vector with all scalar elements the same.
11456   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11457     SDNode *V = N0.getNode();
11458
11459     // If this is a bit convert that changes the element type of the vector but
11460     // not the number of vector elements, look through it.  Be careful not to
11461     // look though conversions that change things like v4f32 to v2f64.
11462     if (V->getOpcode() == ISD::BITCAST) {
11463       SDValue ConvInput = V->getOperand(0);
11464       if (ConvInput.getValueType().isVector() &&
11465           ConvInput.getValueType().getVectorNumElements() == NumElts)
11466         V = ConvInput.getNode();
11467     }
11468
11469     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11470       assert(V->getNumOperands() == NumElts &&
11471              "BUILD_VECTOR has wrong number of operands");
11472       SDValue Base;
11473       bool AllSame = true;
11474       for (unsigned i = 0; i != NumElts; ++i) {
11475         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11476           Base = V->getOperand(i);
11477           break;
11478         }
11479       }
11480       // Splat of <u, u, u, u>, return <u, u, u, u>
11481       if (!Base.getNode())
11482         return N0;
11483       for (unsigned i = 0; i != NumElts; ++i) {
11484         if (V->getOperand(i) != Base) {
11485           AllSame = false;
11486           break;
11487         }
11488       }
11489       // Splat of <x, x, x, x>, return <x, x, x, x>
11490       if (AllSame)
11491         return N0;
11492     }
11493   }
11494
11495   // There are various patterns used to build up a vector from smaller vectors,
11496   // subvectors, or elements. Scan chains of these and replace unused insertions
11497   // or components with undef.
11498   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11499     return S;
11500
11501   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11502       Level < AfterLegalizeVectorOps &&
11503       (N1.getOpcode() == ISD::UNDEF ||
11504       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11505        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11506     SDValue V = partitionShuffleOfConcats(N, DAG);
11507
11508     if (V.getNode())
11509       return V;
11510   }
11511
11512   // Canonicalize shuffles according to rules:
11513   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11514   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11515   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11516   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11517       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11518       TLI.isTypeLegal(VT)) {
11519     // The incoming shuffle must be of the same type as the result of the
11520     // current shuffle.
11521     assert(N1->getOperand(0).getValueType() == VT &&
11522            "Shuffle types don't match");
11523
11524     SDValue SV0 = N1->getOperand(0);
11525     SDValue SV1 = N1->getOperand(1);
11526     bool HasSameOp0 = N0 == SV0;
11527     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11528     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11529       // Commute the operands of this shuffle so that next rule
11530       // will trigger.
11531       return DAG.getCommutedVectorShuffle(*SVN);
11532   }
11533
11534   // Try to fold according to rules:
11535   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11536   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11537   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11538   // Don't try to fold shuffles with illegal type.
11539   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11540       TLI.isTypeLegal(VT)) {
11541     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11542
11543     // The incoming shuffle must be of the same type as the result of the
11544     // current shuffle.
11545     assert(OtherSV->getOperand(0).getValueType() == VT &&
11546            "Shuffle types don't match");
11547
11548     SDValue SV0, SV1;
11549     SmallVector<int, 4> Mask;
11550     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11551     // operand, and SV1 as the second operand.
11552     for (unsigned i = 0; i != NumElts; ++i) {
11553       int Idx = SVN->getMaskElt(i);
11554       if (Idx < 0) {
11555         // Propagate Undef.
11556         Mask.push_back(Idx);
11557         continue;
11558       }
11559
11560       SDValue CurrentVec;
11561       if (Idx < (int)NumElts) {
11562         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11563         // shuffle mask to identify which vector is actually referenced.
11564         Idx = OtherSV->getMaskElt(Idx);
11565         if (Idx < 0) {
11566           // Propagate Undef.
11567           Mask.push_back(Idx);
11568           continue;
11569         }
11570
11571         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11572                                            : OtherSV->getOperand(1);
11573       } else {
11574         // This shuffle index references an element within N1.
11575         CurrentVec = N1;
11576       }
11577
11578       // Simple case where 'CurrentVec' is UNDEF.
11579       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11580         Mask.push_back(-1);
11581         continue;
11582       }
11583
11584       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11585       // will be the first or second operand of the combined shuffle.
11586       Idx = Idx % NumElts;
11587       if (!SV0.getNode() || SV0 == CurrentVec) {
11588         // Ok. CurrentVec is the left hand side.
11589         // Update the mask accordingly.
11590         SV0 = CurrentVec;
11591         Mask.push_back(Idx);
11592         continue;
11593       }
11594
11595       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11596       if (SV1.getNode() && SV1 != CurrentVec)
11597         return SDValue();
11598
11599       // Ok. CurrentVec is the right hand side.
11600       // Update the mask accordingly.
11601       SV1 = CurrentVec;
11602       Mask.push_back(Idx + NumElts);
11603     }
11604
11605     // Check if all indices in Mask are Undef. In case, propagate Undef.
11606     bool isUndefMask = true;
11607     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11608       isUndefMask &= Mask[i] < 0;
11609
11610     if (isUndefMask)
11611       return DAG.getUNDEF(VT);
11612
11613     if (!SV0.getNode())
11614       SV0 = DAG.getUNDEF(VT);
11615     if (!SV1.getNode())
11616       SV1 = DAG.getUNDEF(VT);
11617
11618     // Avoid introducing shuffles with illegal mask.
11619     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11620       // Compute the commuted shuffle mask and test again.
11621       for (unsigned i = 0; i != NumElts; ++i) {
11622         int idx = Mask[i];
11623         if (idx < 0)
11624           continue;
11625         else if (idx < (int)NumElts)
11626           Mask[i] = idx + NumElts;
11627         else
11628           Mask[i] = idx - NumElts;
11629       }
11630
11631       if (!TLI.isShuffleMaskLegal(Mask, VT))
11632         return SDValue();
11633  
11634       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11635       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11636       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11637       std::swap(SV0, SV1);
11638     }
11639
11640     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11641     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11642     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11643     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11644   }
11645
11646   return SDValue();
11647 }
11648
11649 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11650   SDValue N0 = N->getOperand(0);
11651   SDValue N2 = N->getOperand(2);
11652
11653   // If the input vector is a concatenation, and the insert replaces
11654   // one of the halves, we can optimize into a single concat_vectors.
11655   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11656       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11657     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11658     EVT VT = N->getValueType(0);
11659
11660     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11661     // (concat_vectors Z, Y)
11662     if (InsIdx == 0)
11663       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11664                          N->getOperand(1), N0.getOperand(1));
11665
11666     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11667     // (concat_vectors X, Z)
11668     if (InsIdx == VT.getVectorNumElements()/2)
11669       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11670                          N0.getOperand(0), N->getOperand(1));
11671   }
11672
11673   return SDValue();
11674 }
11675
11676 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11677 /// with the destination vector and a zero vector.
11678 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11679 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11680 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11681   EVT VT = N->getValueType(0);
11682   SDLoc dl(N);
11683   SDValue LHS = N->getOperand(0);
11684   SDValue RHS = N->getOperand(1);
11685   if (N->getOpcode() == ISD::AND) {
11686     if (RHS.getOpcode() == ISD::BITCAST)
11687       RHS = RHS.getOperand(0);
11688     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11689       SmallVector<int, 8> Indices;
11690       unsigned NumElts = RHS.getNumOperands();
11691       for (unsigned i = 0; i != NumElts; ++i) {
11692         SDValue Elt = RHS.getOperand(i);
11693         if (!isa<ConstantSDNode>(Elt))
11694           return SDValue();
11695
11696         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11697           Indices.push_back(i);
11698         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11699           Indices.push_back(NumElts+i);
11700         else
11701           return SDValue();
11702       }
11703
11704       // Let's see if the target supports this vector_shuffle.
11705       EVT RVT = RHS.getValueType();
11706       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11707         return SDValue();
11708
11709       // Return the new VECTOR_SHUFFLE node.
11710       EVT EltVT = RVT.getVectorElementType();
11711       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11712                                      DAG.getConstant(0, EltVT));
11713       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11714       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11715       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11716       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11717     }
11718   }
11719
11720   return SDValue();
11721 }
11722
11723 /// Visit a binary vector operation, like ADD.
11724 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11725   assert(N->getValueType(0).isVector() &&
11726          "SimplifyVBinOp only works on vectors!");
11727
11728   SDValue LHS = N->getOperand(0);
11729   SDValue RHS = N->getOperand(1);
11730   SDValue Shuffle = XformToShuffleWithZero(N);
11731   if (Shuffle.getNode()) return Shuffle;
11732
11733   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11734   // this operation.
11735   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11736       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11737     // Check if both vectors are constants. If not bail out.
11738     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11739           cast<BuildVectorSDNode>(RHS)->isConstant()))
11740       return SDValue();
11741
11742     SmallVector<SDValue, 8> Ops;
11743     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11744       SDValue LHSOp = LHS.getOperand(i);
11745       SDValue RHSOp = RHS.getOperand(i);
11746
11747       // Can't fold divide by zero.
11748       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11749           N->getOpcode() == ISD::FDIV) {
11750         if ((RHSOp.getOpcode() == ISD::Constant &&
11751              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11752             (RHSOp.getOpcode() == ISD::ConstantFP &&
11753              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11754           break;
11755       }
11756
11757       EVT VT = LHSOp.getValueType();
11758       EVT RVT = RHSOp.getValueType();
11759       if (RVT != VT) {
11760         // Integer BUILD_VECTOR operands may have types larger than the element
11761         // size (e.g., when the element type is not legal).  Prior to type
11762         // legalization, the types may not match between the two BUILD_VECTORS.
11763         // Truncate one of the operands to make them match.
11764         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11765           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11766         } else {
11767           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11768           VT = RVT;
11769         }
11770       }
11771       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11772                                    LHSOp, RHSOp);
11773       if (FoldOp.getOpcode() != ISD::UNDEF &&
11774           FoldOp.getOpcode() != ISD::Constant &&
11775           FoldOp.getOpcode() != ISD::ConstantFP)
11776         break;
11777       Ops.push_back(FoldOp);
11778       AddToWorklist(FoldOp.getNode());
11779     }
11780
11781     if (Ops.size() == LHS.getNumOperands())
11782       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11783   }
11784
11785   // Type legalization might introduce new shuffles in the DAG.
11786   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11787   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11788   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11789       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11790       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11791       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11792     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11793     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11794
11795     if (SVN0->getMask().equals(SVN1->getMask())) {
11796       EVT VT = N->getValueType(0);
11797       SDValue UndefVector = LHS.getOperand(1);
11798       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11799                                      LHS.getOperand(0), RHS.getOperand(0));
11800       AddUsersToWorklist(N);
11801       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11802                                   &SVN0->getMask()[0]);
11803     }
11804   }
11805
11806   return SDValue();
11807 }
11808
11809 /// Visit a binary vector operation, like FABS/FNEG.
11810 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11811   assert(N->getValueType(0).isVector() &&
11812          "SimplifyVUnaryOp only works on vectors!");
11813
11814   SDValue N0 = N->getOperand(0);
11815
11816   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11817     return SDValue();
11818
11819   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11820   SmallVector<SDValue, 8> Ops;
11821   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11822     SDValue Op = N0.getOperand(i);
11823     if (Op.getOpcode() != ISD::UNDEF &&
11824         Op.getOpcode() != ISD::ConstantFP)
11825       break;
11826     EVT EltVT = Op.getValueType();
11827     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11828     if (FoldOp.getOpcode() != ISD::UNDEF &&
11829         FoldOp.getOpcode() != ISD::ConstantFP)
11830       break;
11831     Ops.push_back(FoldOp);
11832     AddToWorklist(FoldOp.getNode());
11833   }
11834
11835   if (Ops.size() != N0.getNumOperands())
11836     return SDValue();
11837
11838   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11839 }
11840
11841 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11842                                     SDValue N1, SDValue N2){
11843   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11844
11845   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11846                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11847
11848   // If we got a simplified select_cc node back from SimplifySelectCC, then
11849   // break it down into a new SETCC node, and a new SELECT node, and then return
11850   // the SELECT node, since we were called with a SELECT node.
11851   if (SCC.getNode()) {
11852     // Check to see if we got a select_cc back (to turn into setcc/select).
11853     // Otherwise, just return whatever node we got back, like fabs.
11854     if (SCC.getOpcode() == ISD::SELECT_CC) {
11855       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11856                                   N0.getValueType(),
11857                                   SCC.getOperand(0), SCC.getOperand(1),
11858                                   SCC.getOperand(4));
11859       AddToWorklist(SETCC.getNode());
11860       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11861                            SCC.getOperand(2), SCC.getOperand(3));
11862     }
11863
11864     return SCC;
11865   }
11866   return SDValue();
11867 }
11868
11869 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11870 /// being selected between, see if we can simplify the select.  Callers of this
11871 /// should assume that TheSelect is deleted if this returns true.  As such, they
11872 /// should return the appropriate thing (e.g. the node) back to the top-level of
11873 /// the DAG combiner loop to avoid it being looked at.
11874 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11875                                     SDValue RHS) {
11876
11877   // Cannot simplify select with vector condition
11878   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11879
11880   // If this is a select from two identical things, try to pull the operation
11881   // through the select.
11882   if (LHS.getOpcode() != RHS.getOpcode() ||
11883       !LHS.hasOneUse() || !RHS.hasOneUse())
11884     return false;
11885
11886   // If this is a load and the token chain is identical, replace the select
11887   // of two loads with a load through a select of the address to load from.
11888   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11889   // constants have been dropped into the constant pool.
11890   if (LHS.getOpcode() == ISD::LOAD) {
11891     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11892     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11893
11894     // Token chains must be identical.
11895     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11896         // Do not let this transformation reduce the number of volatile loads.
11897         LLD->isVolatile() || RLD->isVolatile() ||
11898         // If this is an EXTLOAD, the VT's must match.
11899         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11900         // If this is an EXTLOAD, the kind of extension must match.
11901         (LLD->getExtensionType() != RLD->getExtensionType() &&
11902          // The only exception is if one of the extensions is anyext.
11903          LLD->getExtensionType() != ISD::EXTLOAD &&
11904          RLD->getExtensionType() != ISD::EXTLOAD) ||
11905         // FIXME: this discards src value information.  This is
11906         // over-conservative. It would be beneficial to be able to remember
11907         // both potential memory locations.  Since we are discarding
11908         // src value info, don't do the transformation if the memory
11909         // locations are not in the default address space.
11910         LLD->getPointerInfo().getAddrSpace() != 0 ||
11911         RLD->getPointerInfo().getAddrSpace() != 0 ||
11912         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11913                                       LLD->getBasePtr().getValueType()))
11914       return false;
11915
11916     // Check that the select condition doesn't reach either load.  If so,
11917     // folding this will induce a cycle into the DAG.  If not, this is safe to
11918     // xform, so create a select of the addresses.
11919     SDValue Addr;
11920     if (TheSelect->getOpcode() == ISD::SELECT) {
11921       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11922       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11923           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11924         return false;
11925       // The loads must not depend on one another.
11926       if (LLD->isPredecessorOf(RLD) ||
11927           RLD->isPredecessorOf(LLD))
11928         return false;
11929       Addr = DAG.getSelect(SDLoc(TheSelect),
11930                            LLD->getBasePtr().getValueType(),
11931                            TheSelect->getOperand(0), LLD->getBasePtr(),
11932                            RLD->getBasePtr());
11933     } else {  // Otherwise SELECT_CC
11934       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11935       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11936
11937       if ((LLD->hasAnyUseOfValue(1) &&
11938            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11939           (RLD->hasAnyUseOfValue(1) &&
11940            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11941         return false;
11942
11943       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11944                          LLD->getBasePtr().getValueType(),
11945                          TheSelect->getOperand(0),
11946                          TheSelect->getOperand(1),
11947                          LLD->getBasePtr(), RLD->getBasePtr(),
11948                          TheSelect->getOperand(4));
11949     }
11950
11951     SDValue Load;
11952     // It is safe to replace the two loads if they have different alignments,
11953     // but the new load must be the minimum (most restrictive) alignment of the
11954     // inputs.
11955     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11956     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11957     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11958       Load = DAG.getLoad(TheSelect->getValueType(0),
11959                          SDLoc(TheSelect),
11960                          // FIXME: Discards pointer and AA info.
11961                          LLD->getChain(), Addr, MachinePointerInfo(),
11962                          LLD->isVolatile(), LLD->isNonTemporal(),
11963                          isInvariant, Alignment);
11964     } else {
11965       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11966                             RLD->getExtensionType() : LLD->getExtensionType(),
11967                             SDLoc(TheSelect),
11968                             TheSelect->getValueType(0),
11969                             // FIXME: Discards pointer and AA info.
11970                             LLD->getChain(), Addr, MachinePointerInfo(),
11971                             LLD->getMemoryVT(), LLD->isVolatile(),
11972                             LLD->isNonTemporal(), isInvariant, Alignment);
11973     }
11974
11975     // Users of the select now use the result of the load.
11976     CombineTo(TheSelect, Load);
11977
11978     // Users of the old loads now use the new load's chain.  We know the
11979     // old-load value is dead now.
11980     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11981     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11982     return true;
11983   }
11984
11985   return false;
11986 }
11987
11988 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11989 /// where 'cond' is the comparison specified by CC.
11990 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11991                                       SDValue N2, SDValue N3,
11992                                       ISD::CondCode CC, bool NotExtCompare) {
11993   // (x ? y : y) -> y.
11994   if (N2 == N3) return N2;
11995
11996   EVT VT = N2.getValueType();
11997   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11998   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11999   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
12000
12001   // Determine if the condition we're dealing with is constant
12002   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
12003                               N0, N1, CC, DL, false);
12004   if (SCC.getNode()) AddToWorklist(SCC.getNode());
12005   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
12006
12007   // fold select_cc true, x, y -> x
12008   if (SCCC && !SCCC->isNullValue())
12009     return N2;
12010   // fold select_cc false, x, y -> y
12011   if (SCCC && SCCC->isNullValue())
12012     return N3;
12013
12014   // Check to see if we can simplify the select into an fabs node
12015   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
12016     // Allow either -0.0 or 0.0
12017     if (CFP->getValueAPF().isZero()) {
12018       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
12019       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
12020           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
12021           N2 == N3.getOperand(0))
12022         return DAG.getNode(ISD::FABS, DL, VT, N0);
12023
12024       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
12025       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
12026           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
12027           N2.getOperand(0) == N3)
12028         return DAG.getNode(ISD::FABS, DL, VT, N3);
12029     }
12030   }
12031
12032   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
12033   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
12034   // in it.  This is a win when the constant is not otherwise available because
12035   // it replaces two constant pool loads with one.  We only do this if the FP
12036   // type is known to be legal, because if it isn't, then we are before legalize
12037   // types an we want the other legalization to happen first (e.g. to avoid
12038   // messing with soft float) and if the ConstantFP is not legal, because if
12039   // it is legal, we may not need to store the FP constant in a constant pool.
12040   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
12041     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
12042       if (TLI.isTypeLegal(N2.getValueType()) &&
12043           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
12044                TargetLowering::Legal &&
12045            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
12046            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
12047           // If both constants have multiple uses, then we won't need to do an
12048           // extra load, they are likely around in registers for other users.
12049           (TV->hasOneUse() || FV->hasOneUse())) {
12050         Constant *Elts[] = {
12051           const_cast<ConstantFP*>(FV->getConstantFPValue()),
12052           const_cast<ConstantFP*>(TV->getConstantFPValue())
12053         };
12054         Type *FPTy = Elts[0]->getType();
12055         const DataLayout &TD = *TLI.getDataLayout();
12056
12057         // Create a ConstantArray of the two constants.
12058         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
12059         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
12060                                             TD.getPrefTypeAlignment(FPTy));
12061         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
12062
12063         // Get the offsets to the 0 and 1 element of the array so that we can
12064         // select between them.
12065         SDValue Zero = DAG.getIntPtrConstant(0);
12066         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
12067         SDValue One = DAG.getIntPtrConstant(EltSize);
12068
12069         SDValue Cond = DAG.getSetCC(DL,
12070                                     getSetCCResultType(N0.getValueType()),
12071                                     N0, N1, CC);
12072         AddToWorklist(Cond.getNode());
12073         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
12074                                           Cond, One, Zero);
12075         AddToWorklist(CstOffset.getNode());
12076         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
12077                             CstOffset);
12078         AddToWorklist(CPIdx.getNode());
12079         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
12080                            MachinePointerInfo::getConstantPool(), false,
12081                            false, false, Alignment);
12082
12083       }
12084     }
12085
12086   // Check to see if we can perform the "gzip trick", transforming
12087   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
12088   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
12089       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
12090        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
12091     EVT XType = N0.getValueType();
12092     EVT AType = N2.getValueType();
12093     if (XType.bitsGE(AType)) {
12094       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
12095       // single-bit constant.
12096       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
12097         unsigned ShCtV = N2C->getAPIntValue().logBase2();
12098         ShCtV = XType.getSizeInBits()-ShCtV-1;
12099         SDValue ShCt = DAG.getConstant(ShCtV,
12100                                        getShiftAmountTy(N0.getValueType()));
12101         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
12102                                     XType, N0, ShCt);
12103         AddToWorklist(Shift.getNode());
12104
12105         if (XType.bitsGT(AType)) {
12106           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12107           AddToWorklist(Shift.getNode());
12108         }
12109
12110         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12111       }
12112
12113       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
12114                                   XType, N0,
12115                                   DAG.getConstant(XType.getSizeInBits()-1,
12116                                          getShiftAmountTy(N0.getValueType())));
12117       AddToWorklist(Shift.getNode());
12118
12119       if (XType.bitsGT(AType)) {
12120         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
12121         AddToWorklist(Shift.getNode());
12122       }
12123
12124       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
12125     }
12126   }
12127
12128   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
12129   // where y is has a single bit set.
12130   // A plaintext description would be, we can turn the SELECT_CC into an AND
12131   // when the condition can be materialized as an all-ones register.  Any
12132   // single bit-test can be materialized as an all-ones register with
12133   // shift-left and shift-right-arith.
12134   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
12135       N0->getValueType(0) == VT &&
12136       N1C && N1C->isNullValue() &&
12137       N2C && N2C->isNullValue()) {
12138     SDValue AndLHS = N0->getOperand(0);
12139     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
12140     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
12141       // Shift the tested bit over the sign bit.
12142       APInt AndMask = ConstAndRHS->getAPIntValue();
12143       SDValue ShlAmt =
12144         DAG.getConstant(AndMask.countLeadingZeros(),
12145                         getShiftAmountTy(AndLHS.getValueType()));
12146       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
12147
12148       // Now arithmetic right shift it all the way over, so the result is either
12149       // all-ones, or zero.
12150       SDValue ShrAmt =
12151         DAG.getConstant(AndMask.getBitWidth()-1,
12152                         getShiftAmountTy(Shl.getValueType()));
12153       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
12154
12155       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
12156     }
12157   }
12158
12159   // fold select C, 16, 0 -> shl C, 4
12160   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
12161       TLI.getBooleanContents(N0.getValueType()) ==
12162           TargetLowering::ZeroOrOneBooleanContent) {
12163
12164     // If the caller doesn't want us to simplify this into a zext of a compare,
12165     // don't do it.
12166     if (NotExtCompare && N2C->getAPIntValue() == 1)
12167       return SDValue();
12168
12169     // Get a SetCC of the condition
12170     // NOTE: Don't create a SETCC if it's not legal on this target.
12171     if (!LegalOperations ||
12172         TLI.isOperationLegal(ISD::SETCC,
12173           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
12174       SDValue Temp, SCC;
12175       // cast from setcc result type to select result type
12176       if (LegalTypes) {
12177         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
12178                             N0, N1, CC);
12179         if (N2.getValueType().bitsLT(SCC.getValueType()))
12180           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
12181                                         N2.getValueType());
12182         else
12183           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12184                              N2.getValueType(), SCC);
12185       } else {
12186         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
12187         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
12188                            N2.getValueType(), SCC);
12189       }
12190
12191       AddToWorklist(SCC.getNode());
12192       AddToWorklist(Temp.getNode());
12193
12194       if (N2C->getAPIntValue() == 1)
12195         return Temp;
12196
12197       // shl setcc result by log2 n2c
12198       return DAG.getNode(
12199           ISD::SHL, DL, N2.getValueType(), Temp,
12200           DAG.getConstant(N2C->getAPIntValue().logBase2(),
12201                           getShiftAmountTy(Temp.getValueType())));
12202     }
12203   }
12204
12205   // Check to see if this is the equivalent of setcc
12206   // FIXME: Turn all of these into setcc if setcc if setcc is legal
12207   // otherwise, go ahead with the folds.
12208   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
12209     EVT XType = N0.getValueType();
12210     if (!LegalOperations ||
12211         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
12212       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
12213       if (Res.getValueType() != VT)
12214         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
12215       return Res;
12216     }
12217
12218     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
12219     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
12220         (!LegalOperations ||
12221          TLI.isOperationLegal(ISD::CTLZ, XType))) {
12222       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
12223       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
12224                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
12225                                        getShiftAmountTy(Ctlz.getValueType())));
12226     }
12227     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
12228     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
12229       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
12230                                   XType, DAG.getConstant(0, XType), N0);
12231       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12232       return DAG.getNode(ISD::SRL, DL, XType,
12233                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12234                          DAG.getConstant(XType.getSizeInBits()-1,
12235                                          getShiftAmountTy(XType)));
12236     }
12237     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12238     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12239       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12240                                  DAG.getConstant(XType.getSizeInBits()-1,
12241                                          getShiftAmountTy(N0.getValueType())));
12242       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12243     }
12244   }
12245
12246   // Check to see if this is an integer abs.
12247   // select_cc setg[te] X,  0,  X, -X ->
12248   // select_cc setgt    X, -1,  X, -X ->
12249   // select_cc setl[te] X,  0, -X,  X ->
12250   // select_cc setlt    X,  1, -X,  X ->
12251   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12252   if (N1C) {
12253     ConstantSDNode *SubC = nullptr;
12254     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12255          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12256         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12257       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12258     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12259               (N1C->isOne() && CC == ISD::SETLT)) &&
12260              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12261       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12262
12263     EVT XType = N0.getValueType();
12264     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12265       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12266                                   N0,
12267                                   DAG.getConstant(XType.getSizeInBits()-1,
12268                                          getShiftAmountTy(N0.getValueType())));
12269       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12270                                 XType, N0, Shift);
12271       AddToWorklist(Shift.getNode());
12272       AddToWorklist(Add.getNode());
12273       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12274     }
12275   }
12276
12277   return SDValue();
12278 }
12279
12280 /// This is a stub for TargetLowering::SimplifySetCC.
12281 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12282                                    SDValue N1, ISD::CondCode Cond,
12283                                    SDLoc DL, bool foldBooleans) {
12284   TargetLowering::DAGCombinerInfo
12285     DagCombineInfo(DAG, Level, false, this);
12286   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12287 }
12288
12289 /// Given an ISD::SDIV node expressing a divide by constant, return
12290 /// a DAG expression to select that will generate the same value by multiplying
12291 /// by a magic number.
12292 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12293 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12294   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12295   if (!C)
12296     return SDValue();
12297
12298   // Avoid division by zero.
12299   if (!C->getAPIntValue())
12300     return SDValue();
12301
12302   std::vector<SDNode*> Built;
12303   SDValue S =
12304       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12305
12306   for (SDNode *N : Built)
12307     AddToWorklist(N);
12308   return S;
12309 }
12310
12311 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12312 /// DAG expression that will generate the same value by right shifting.
12313 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12314   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12315   if (!C)
12316     return SDValue();
12317
12318   // Avoid division by zero.
12319   if (!C->getAPIntValue())
12320     return SDValue();
12321
12322   std::vector<SDNode *> Built;
12323   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12324
12325   for (SDNode *N : Built)
12326     AddToWorklist(N);
12327   return S;
12328 }
12329
12330 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12331 /// expression that will generate the same value by multiplying by a magic
12332 /// number.
12333 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12334 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12335   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12336   if (!C)
12337     return SDValue();
12338
12339   // Avoid division by zero.
12340   if (!C->getAPIntValue())
12341     return SDValue();
12342
12343   std::vector<SDNode*> Built;
12344   SDValue S =
12345       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12346
12347   for (SDNode *N : Built)
12348     AddToWorklist(N);
12349   return S;
12350 }
12351
12352 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12353   if (Level >= AfterLegalizeDAG)
12354     return SDValue();
12355
12356   // Expose the DAG combiner to the target combiner implementations.
12357   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12358
12359   unsigned Iterations = 0;
12360   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12361     if (Iterations) {
12362       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12363       // For the reciprocal, we need to find the zero of the function:
12364       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12365       //     =>
12366       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12367       //     does not require additional intermediate precision]
12368       EVT VT = Op.getValueType();
12369       SDLoc DL(Op);
12370       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12371
12372       AddToWorklist(Est.getNode());
12373
12374       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12375       for (unsigned i = 0; i < Iterations; ++i) {
12376         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12377         AddToWorklist(NewEst.getNode());
12378
12379         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12380         AddToWorklist(NewEst.getNode());
12381
12382         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12383         AddToWorklist(NewEst.getNode());
12384
12385         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12386         AddToWorklist(Est.getNode());
12387       }
12388     }
12389     return Est;
12390   }
12391
12392   return SDValue();
12393 }
12394
12395 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12396 /// For the reciprocal sqrt, we need to find the zero of the function:
12397 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12398 ///     =>
12399 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12400 /// As a result, we precompute A/2 prior to the iteration loop.
12401 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12402                                           unsigned Iterations) {
12403   EVT VT = Arg.getValueType();
12404   SDLoc DL(Arg);
12405   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12406
12407   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12408   // this entire sequence requires only one FP constant.
12409   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12410   AddToWorklist(HalfArg.getNode());
12411
12412   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12413   AddToWorklist(HalfArg.getNode());
12414
12415   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12416   for (unsigned i = 0; i < Iterations; ++i) {
12417     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12418     AddToWorklist(NewEst.getNode());
12419
12420     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12421     AddToWorklist(NewEst.getNode());
12422
12423     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12424     AddToWorklist(NewEst.getNode());
12425
12426     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12427     AddToWorklist(Est.getNode());
12428   }
12429   return Est;
12430 }
12431
12432 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12433 /// For the reciprocal sqrt, we need to find the zero of the function:
12434 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12435 ///     =>
12436 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12437 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12438                                           unsigned Iterations) {
12439   EVT VT = Arg.getValueType();
12440   SDLoc DL(Arg);
12441   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12442   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12443
12444   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12445   for (unsigned i = 0; i < Iterations; ++i) {
12446     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12447     AddToWorklist(HalfEst.getNode());
12448
12449     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12450     AddToWorklist(Est.getNode());
12451
12452     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12453     AddToWorklist(Est.getNode());
12454
12455     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12456     AddToWorklist(Est.getNode());
12457
12458     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12459     AddToWorklist(Est.getNode());
12460   }
12461   return Est;
12462 }
12463
12464 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12465   if (Level >= AfterLegalizeDAG)
12466     return SDValue();
12467
12468   // Expose the DAG combiner to the target combiner implementations.
12469   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12470   unsigned Iterations = 0;
12471   bool UseOneConstNR = false;
12472   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12473     AddToWorklist(Est.getNode());
12474     if (Iterations) {
12475       Est = UseOneConstNR ?
12476         BuildRsqrtNROneConst(Op, Est, Iterations) :
12477         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12478     }
12479     return Est;
12480   }
12481
12482   return SDValue();
12483 }
12484
12485 /// Return true if base is a frame index, which is known not to alias with
12486 /// anything but itself.  Provides base object and offset as results.
12487 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12488                            const GlobalValue *&GV, const void *&CV) {
12489   // Assume it is a primitive operation.
12490   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12491
12492   // If it's an adding a simple constant then integrate the offset.
12493   if (Base.getOpcode() == ISD::ADD) {
12494     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12495       Base = Base.getOperand(0);
12496       Offset += C->getZExtValue();
12497     }
12498   }
12499
12500   // Return the underlying GlobalValue, and update the Offset.  Return false
12501   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12502   // by multiple nodes with different offsets.
12503   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12504     GV = G->getGlobal();
12505     Offset += G->getOffset();
12506     return false;
12507   }
12508
12509   // Return the underlying Constant value, and update the Offset.  Return false
12510   // for ConstantSDNodes since the same constant pool entry may be represented
12511   // by multiple nodes with different offsets.
12512   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12513     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12514                                          : (const void *)C->getConstVal();
12515     Offset += C->getOffset();
12516     return false;
12517   }
12518   // If it's any of the following then it can't alias with anything but itself.
12519   return isa<FrameIndexSDNode>(Base);
12520 }
12521
12522 /// Return true if there is any possibility that the two addresses overlap.
12523 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12524   // If they are the same then they must be aliases.
12525   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12526
12527   // If they are both volatile then they cannot be reordered.
12528   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12529
12530   // Gather base node and offset information.
12531   SDValue Base1, Base2;
12532   int64_t Offset1, Offset2;
12533   const GlobalValue *GV1, *GV2;
12534   const void *CV1, *CV2;
12535   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12536                                       Base1, Offset1, GV1, CV1);
12537   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12538                                       Base2, Offset2, GV2, CV2);
12539
12540   // If they have a same base address then check to see if they overlap.
12541   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12542     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12543              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12544
12545   // It is possible for different frame indices to alias each other, mostly
12546   // when tail call optimization reuses return address slots for arguments.
12547   // To catch this case, look up the actual index of frame indices to compute
12548   // the real alias relationship.
12549   if (isFrameIndex1 && isFrameIndex2) {
12550     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12551     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12552     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12553     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12554              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12555   }
12556
12557   // Otherwise, if we know what the bases are, and they aren't identical, then
12558   // we know they cannot alias.
12559   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12560     return false;
12561
12562   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12563   // compared to the size and offset of the access, we may be able to prove they
12564   // do not alias.  This check is conservative for now to catch cases created by
12565   // splitting vector types.
12566   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12567       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12568       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12569        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12570       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12571     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12572     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12573
12574     // There is no overlap between these relatively aligned accesses of similar
12575     // size, return no alias.
12576     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12577         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12578       return false;
12579   }
12580
12581   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12582                    ? CombinerGlobalAA
12583                    : DAG.getSubtarget().useAA();
12584 #ifndef NDEBUG
12585   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12586       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12587     UseAA = false;
12588 #endif
12589   if (UseAA &&
12590       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12591     // Use alias analysis information.
12592     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12593                                  Op1->getSrcValueOffset());
12594     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12595         Op0->getSrcValueOffset() - MinOffset;
12596     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12597         Op1->getSrcValueOffset() - MinOffset;
12598     AliasAnalysis::AliasResult AAResult =
12599         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12600                                          Overlap1,
12601                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12602                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12603                                          Overlap2,
12604                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12605     if (AAResult == AliasAnalysis::NoAlias)
12606       return false;
12607   }
12608
12609   // Otherwise we have to assume they alias.
12610   return true;
12611 }
12612
12613 /// Walk up chain skipping non-aliasing memory nodes,
12614 /// looking for aliasing nodes and adding them to the Aliases vector.
12615 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12616                                    SmallVectorImpl<SDValue> &Aliases) {
12617   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12618   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12619
12620   // Get alias information for node.
12621   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12622
12623   // Starting off.
12624   Chains.push_back(OriginalChain);
12625   unsigned Depth = 0;
12626
12627   // Look at each chain and determine if it is an alias.  If so, add it to the
12628   // aliases list.  If not, then continue up the chain looking for the next
12629   // candidate.
12630   while (!Chains.empty()) {
12631     SDValue Chain = Chains.back();
12632     Chains.pop_back();
12633
12634     // For TokenFactor nodes, look at each operand and only continue up the
12635     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12636     // find more and revert to original chain since the xform is unlikely to be
12637     // profitable.
12638     //
12639     // FIXME: The depth check could be made to return the last non-aliasing
12640     // chain we found before we hit a tokenfactor rather than the original
12641     // chain.
12642     if (Depth > 6 || Aliases.size() == 2) {
12643       Aliases.clear();
12644       Aliases.push_back(OriginalChain);
12645       return;
12646     }
12647
12648     // Don't bother if we've been before.
12649     if (!Visited.insert(Chain.getNode()).second)
12650       continue;
12651
12652     switch (Chain.getOpcode()) {
12653     case ISD::EntryToken:
12654       // Entry token is ideal chain operand, but handled in FindBetterChain.
12655       break;
12656
12657     case ISD::LOAD:
12658     case ISD::STORE: {
12659       // Get alias information for Chain.
12660       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12661           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12662
12663       // If chain is alias then stop here.
12664       if (!(IsLoad && IsOpLoad) &&
12665           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12666         Aliases.push_back(Chain);
12667       } else {
12668         // Look further up the chain.
12669         Chains.push_back(Chain.getOperand(0));
12670         ++Depth;
12671       }
12672       break;
12673     }
12674
12675     case ISD::TokenFactor:
12676       // We have to check each of the operands of the token factor for "small"
12677       // token factors, so we queue them up.  Adding the operands to the queue
12678       // (stack) in reverse order maintains the original order and increases the
12679       // likelihood that getNode will find a matching token factor (CSE.)
12680       if (Chain.getNumOperands() > 16) {
12681         Aliases.push_back(Chain);
12682         break;
12683       }
12684       for (unsigned n = Chain.getNumOperands(); n;)
12685         Chains.push_back(Chain.getOperand(--n));
12686       ++Depth;
12687       break;
12688
12689     default:
12690       // For all other instructions we will just have to take what we can get.
12691       Aliases.push_back(Chain);
12692       break;
12693     }
12694   }
12695
12696   // We need to be careful here to also search for aliases through the
12697   // value operand of a store, etc. Consider the following situation:
12698   //   Token1 = ...
12699   //   L1 = load Token1, %52
12700   //   S1 = store Token1, L1, %51
12701   //   L2 = load Token1, %52+8
12702   //   S2 = store Token1, L2, %51+8
12703   //   Token2 = Token(S1, S2)
12704   //   L3 = load Token2, %53
12705   //   S3 = store Token2, L3, %52
12706   //   L4 = load Token2, %53+8
12707   //   S4 = store Token2, L4, %52+8
12708   // If we search for aliases of S3 (which loads address %52), and we look
12709   // only through the chain, then we'll miss the trivial dependence on L1
12710   // (which also loads from %52). We then might change all loads and
12711   // stores to use Token1 as their chain operand, which could result in
12712   // copying %53 into %52 before copying %52 into %51 (which should
12713   // happen first).
12714   //
12715   // The problem is, however, that searching for such data dependencies
12716   // can become expensive, and the cost is not directly related to the
12717   // chain depth. Instead, we'll rule out such configurations here by
12718   // insisting that we've visited all chain users (except for users
12719   // of the original chain, which is not necessary). When doing this,
12720   // we need to look through nodes we don't care about (otherwise, things
12721   // like register copies will interfere with trivial cases).
12722
12723   SmallVector<const SDNode *, 16> Worklist;
12724   for (const SDNode *N : Visited)
12725     if (N != OriginalChain.getNode())
12726       Worklist.push_back(N);
12727
12728   while (!Worklist.empty()) {
12729     const SDNode *M = Worklist.pop_back_val();
12730
12731     // We have already visited M, and want to make sure we've visited any uses
12732     // of M that we care about. For uses that we've not visisted, and don't
12733     // care about, queue them to the worklist.
12734
12735     for (SDNode::use_iterator UI = M->use_begin(),
12736          UIE = M->use_end(); UI != UIE; ++UI)
12737       if (UI.getUse().getValueType() == MVT::Other &&
12738           Visited.insert(*UI).second) {
12739         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12740           // We've not visited this use, and we care about it (it could have an
12741           // ordering dependency with the original node).
12742           Aliases.clear();
12743           Aliases.push_back(OriginalChain);
12744           return;
12745         }
12746
12747         // We've not visited this use, but we don't care about it. Mark it as
12748         // visited and enqueue it to the worklist.
12749         Worklist.push_back(*UI);
12750       }
12751   }
12752 }
12753
12754 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12755 /// (aliasing node.)
12756 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12757   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12758
12759   // Accumulate all the aliases to this node.
12760   GatherAllAliases(N, OldChain, Aliases);
12761
12762   // If no operands then chain to entry token.
12763   if (Aliases.size() == 0)
12764     return DAG.getEntryNode();
12765
12766   // If a single operand then chain to it.  We don't need to revisit it.
12767   if (Aliases.size() == 1)
12768     return Aliases[0];
12769
12770   // Construct a custom tailored token factor.
12771   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12772 }
12773
12774 /// This is the entry point for the file.
12775 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12776                            CodeGenOpt::Level OptLevel) {
12777   /// This is the main entry point to this class.
12778   DAGCombiner(*this, AA, OptLevel).Run(Level);
12779 }