[InstCombine] Minor optimization for bswap with binary ops
[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   WorklistRemover DeadNodes(*this);
796   DAG.ReplaceAllUsesWith(N, To);
797   if (AddTo) {
798     // Push the new nodes and any users onto the worklist
799     for (unsigned i = 0, e = NumTo; i != e; ++i) {
800       if (To[i].getNode()) {
801         AddToWorklist(To[i].getNode());
802         AddUsersToWorklist(To[i].getNode());
803       }
804     }
805   }
806
807   // Finally, if the node is now dead, remove it from the graph.  The node
808   // may not be dead if the replacement process recursively simplified to
809   // something else needing this node.
810   if (N->use_empty())
811     deleteAndRecombine(N);
812   return SDValue(N, 0);
813 }
814
815 void DAGCombiner::
816 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
817   // Replace all uses.  If any nodes become isomorphic to other nodes and
818   // are deleted, make sure to remove them from our worklist.
819   WorklistRemover DeadNodes(*this);
820   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
821
822   // Push the new node and any (possibly new) users onto the worklist.
823   AddToWorklist(TLO.New.getNode());
824   AddUsersToWorklist(TLO.New.getNode());
825
826   // Finally, if the node is now dead, remove it from the graph.  The node
827   // may not be dead if the replacement process recursively simplified to
828   // something else needing this node.
829   if (TLO.Old.getNode()->use_empty())
830     deleteAndRecombine(TLO.Old.getNode());
831 }
832
833 /// Check the specified integer node value to see if it can be simplified or if
834 /// things it uses can be simplified by bit propagation. If so, return true.
835 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
836   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
837   APInt KnownZero, KnownOne;
838   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
839     return false;
840
841   // Revisit the node.
842   AddToWorklist(Op.getNode());
843
844   // Replace the old value with the new one.
845   ++NodesCombined;
846   DEBUG(dbgs() << "\nReplacing.2 ";
847         TLO.Old.getNode()->dump(&DAG);
848         dbgs() << "\nWith: ";
849         TLO.New.getNode()->dump(&DAG);
850         dbgs() << '\n');
851
852   CommitTargetLoweringOpt(TLO);
853   return true;
854 }
855
856 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
857   SDLoc dl(Load);
858   EVT VT = Load->getValueType(0);
859   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
860
861   DEBUG(dbgs() << "\nReplacing.9 ";
862         Load->dump(&DAG);
863         dbgs() << "\nWith: ";
864         Trunc.getNode()->dump(&DAG);
865         dbgs() << '\n');
866   WorklistRemover DeadNodes(*this);
867   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
868   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
869   deleteAndRecombine(Load);
870   AddToWorklist(Trunc.getNode());
871 }
872
873 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
874   Replace = false;
875   SDLoc dl(Op);
876   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
877     EVT MemVT = LD->getMemoryVT();
878     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
879       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
880                                                   : ISD::EXTLOAD)
881       : LD->getExtensionType();
882     Replace = true;
883     return DAG.getExtLoad(ExtType, dl, PVT,
884                           LD->getChain(), LD->getBasePtr(),
885                           MemVT, LD->getMemOperand());
886   }
887
888   unsigned Opc = Op.getOpcode();
889   switch (Opc) {
890   default: break;
891   case ISD::AssertSext:
892     return DAG.getNode(ISD::AssertSext, dl, PVT,
893                        SExtPromoteOperand(Op.getOperand(0), PVT),
894                        Op.getOperand(1));
895   case ISD::AssertZext:
896     return DAG.getNode(ISD::AssertZext, dl, PVT,
897                        ZExtPromoteOperand(Op.getOperand(0), PVT),
898                        Op.getOperand(1));
899   case ISD::Constant: {
900     unsigned ExtOpc =
901       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
902     return DAG.getNode(ExtOpc, dl, PVT, Op);
903   }
904   }
905
906   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
907     return SDValue();
908   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
909 }
910
911 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
912   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
913     return SDValue();
914   EVT OldVT = Op.getValueType();
915   SDLoc dl(Op);
916   bool Replace = false;
917   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
918   if (!NewOp.getNode())
919     return SDValue();
920   AddToWorklist(NewOp.getNode());
921
922   if (Replace)
923     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
924   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
925                      DAG.getValueType(OldVT));
926 }
927
928 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
929   EVT OldVT = Op.getValueType();
930   SDLoc dl(Op);
931   bool Replace = false;
932   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
933   if (!NewOp.getNode())
934     return SDValue();
935   AddToWorklist(NewOp.getNode());
936
937   if (Replace)
938     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
939   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
940 }
941
942 /// Promote the specified integer binary operation if the target indicates it is
943 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
944 /// i32 since i16 instructions are longer.
945 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
946   if (!LegalOperations)
947     return SDValue();
948
949   EVT VT = Op.getValueType();
950   if (VT.isVector() || !VT.isInteger())
951     return SDValue();
952
953   // If operation type is 'undesirable', e.g. i16 on x86, consider
954   // promoting it.
955   unsigned Opc = Op.getOpcode();
956   if (TLI.isTypeDesirableForOp(Opc, VT))
957     return SDValue();
958
959   EVT PVT = VT;
960   // Consult target whether it is a good idea to promote this operation and
961   // what's the right type to promote it to.
962   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
963     assert(PVT != VT && "Don't know what type to promote to!");
964
965     bool Replace0 = false;
966     SDValue N0 = Op.getOperand(0);
967     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
968     if (!NN0.getNode())
969       return SDValue();
970
971     bool Replace1 = false;
972     SDValue N1 = Op.getOperand(1);
973     SDValue NN1;
974     if (N0 == N1)
975       NN1 = NN0;
976     else {
977       NN1 = PromoteOperand(N1, PVT, Replace1);
978       if (!NN1.getNode())
979         return SDValue();
980     }
981
982     AddToWorklist(NN0.getNode());
983     if (NN1.getNode())
984       AddToWorklist(NN1.getNode());
985
986     if (Replace0)
987       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
988     if (Replace1)
989       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
990
991     DEBUG(dbgs() << "\nPromoting ";
992           Op.getNode()->dump(&DAG));
993     SDLoc dl(Op);
994     return DAG.getNode(ISD::TRUNCATE, dl, VT,
995                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
996   }
997   return SDValue();
998 }
999
1000 /// Promote the specified integer shift operation if the target indicates it is
1001 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1002 /// i32 since i16 instructions are longer.
1003 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1004   if (!LegalOperations)
1005     return SDValue();
1006
1007   EVT VT = Op.getValueType();
1008   if (VT.isVector() || !VT.isInteger())
1009     return SDValue();
1010
1011   // If operation type is 'undesirable', e.g. i16 on x86, consider
1012   // promoting it.
1013   unsigned Opc = Op.getOpcode();
1014   if (TLI.isTypeDesirableForOp(Opc, VT))
1015     return SDValue();
1016
1017   EVT PVT = VT;
1018   // Consult target whether it is a good idea to promote this operation and
1019   // what's the right type to promote it to.
1020   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1021     assert(PVT != VT && "Don't know what type to promote to!");
1022
1023     bool Replace = false;
1024     SDValue N0 = Op.getOperand(0);
1025     if (Opc == ISD::SRA)
1026       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1027     else if (Opc == ISD::SRL)
1028       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1029     else
1030       N0 = PromoteOperand(N0, PVT, Replace);
1031     if (!N0.getNode())
1032       return SDValue();
1033
1034     AddToWorklist(N0.getNode());
1035     if (Replace)
1036       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1037
1038     DEBUG(dbgs() << "\nPromoting ";
1039           Op.getNode()->dump(&DAG));
1040     SDLoc dl(Op);
1041     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1042                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1043   }
1044   return SDValue();
1045 }
1046
1047 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1048   if (!LegalOperations)
1049     return SDValue();
1050
1051   EVT VT = Op.getValueType();
1052   if (VT.isVector() || !VT.isInteger())
1053     return SDValue();
1054
1055   // If operation type is 'undesirable', e.g. i16 on x86, consider
1056   // promoting it.
1057   unsigned Opc = Op.getOpcode();
1058   if (TLI.isTypeDesirableForOp(Opc, VT))
1059     return SDValue();
1060
1061   EVT PVT = VT;
1062   // Consult target whether it is a good idea to promote this operation and
1063   // what's the right type to promote it to.
1064   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1065     assert(PVT != VT && "Don't know what type to promote to!");
1066     // fold (aext (aext x)) -> (aext x)
1067     // fold (aext (zext x)) -> (zext x)
1068     // fold (aext (sext x)) -> (sext x)
1069     DEBUG(dbgs() << "\nPromoting ";
1070           Op.getNode()->dump(&DAG));
1071     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1072   }
1073   return SDValue();
1074 }
1075
1076 bool DAGCombiner::PromoteLoad(SDValue Op) {
1077   if (!LegalOperations)
1078     return false;
1079
1080   EVT VT = Op.getValueType();
1081   if (VT.isVector() || !VT.isInteger())
1082     return false;
1083
1084   // If operation type is 'undesirable', e.g. i16 on x86, consider
1085   // promoting it.
1086   unsigned Opc = Op.getOpcode();
1087   if (TLI.isTypeDesirableForOp(Opc, VT))
1088     return false;
1089
1090   EVT PVT = VT;
1091   // Consult target whether it is a good idea to promote this operation and
1092   // what's the right type to promote it to.
1093   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1094     assert(PVT != VT && "Don't know what type to promote to!");
1095
1096     SDLoc dl(Op);
1097     SDNode *N = Op.getNode();
1098     LoadSDNode *LD = cast<LoadSDNode>(N);
1099     EVT MemVT = LD->getMemoryVT();
1100     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1101       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1102                                                   : ISD::EXTLOAD)
1103       : LD->getExtensionType();
1104     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1105                                    LD->getChain(), LD->getBasePtr(),
1106                                    MemVT, LD->getMemOperand());
1107     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1108
1109     DEBUG(dbgs() << "\nPromoting ";
1110           N->dump(&DAG);
1111           dbgs() << "\nTo: ";
1112           Result.getNode()->dump(&DAG);
1113           dbgs() << '\n');
1114     WorklistRemover DeadNodes(*this);
1115     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1116     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1117     deleteAndRecombine(N);
1118     AddToWorklist(Result.getNode());
1119     return true;
1120   }
1121   return false;
1122 }
1123
1124 /// \brief Recursively delete a node which has no uses and any operands for
1125 /// which it is the only use.
1126 ///
1127 /// Note that this both deletes the nodes and removes them from the worklist.
1128 /// It also adds any nodes who have had a user deleted to the worklist as they
1129 /// may now have only one use and subject to other combines.
1130 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1131   if (!N->use_empty())
1132     return false;
1133
1134   SmallSetVector<SDNode *, 16> Nodes;
1135   Nodes.insert(N);
1136   do {
1137     N = Nodes.pop_back_val();
1138     if (!N)
1139       continue;
1140
1141     if (N->use_empty()) {
1142       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1143         Nodes.insert(N->getOperand(i).getNode());
1144
1145       removeFromWorklist(N);
1146       DAG.DeleteNode(N);
1147     } else {
1148       AddToWorklist(N);
1149     }
1150   } while (!Nodes.empty());
1151   return true;
1152 }
1153
1154 //===----------------------------------------------------------------------===//
1155 //  Main DAG Combiner implementation
1156 //===----------------------------------------------------------------------===//
1157
1158 void DAGCombiner::Run(CombineLevel AtLevel) {
1159   // set the instance variables, so that the various visit routines may use it.
1160   Level = AtLevel;
1161   LegalOperations = Level >= AfterLegalizeVectorOps;
1162   LegalTypes = Level >= AfterLegalizeTypes;
1163
1164   // Early exit if this basic block is in an optnone function.
1165   AttributeSet FnAttrs =
1166     DAG.getMachineFunction().getFunction()->getAttributes();
1167   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1168                            Attribute::OptimizeNone))
1169     return;
1170
1171   // Add all the dag nodes to the worklist.
1172   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1173        E = DAG.allnodes_end(); I != E; ++I)
1174     AddToWorklist(I);
1175
1176   // Create a dummy node (which is not added to allnodes), that adds a reference
1177   // to the root node, preventing it from being deleted, and tracking any
1178   // changes of the root.
1179   HandleSDNode Dummy(DAG.getRoot());
1180
1181   // while the worklist isn't empty, find a node and
1182   // try and combine it.
1183   while (!WorklistMap.empty()) {
1184     SDNode *N;
1185     // The Worklist holds the SDNodes in order, but it may contain null entries.
1186     do {
1187       N = Worklist.pop_back_val();
1188     } while (!N);
1189
1190     bool GoodWorklistEntry = WorklistMap.erase(N);
1191     (void)GoodWorklistEntry;
1192     assert(GoodWorklistEntry &&
1193            "Found a worklist entry without a corresponding map entry!");
1194
1195     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1196     // N is deleted from the DAG, since they too may now be dead or may have a
1197     // reduced number of uses, allowing other xforms.
1198     if (recursivelyDeleteUnusedNodes(N))
1199       continue;
1200
1201     WorklistRemover DeadNodes(*this);
1202
1203     // If this combine is running after legalizing the DAG, re-legalize any
1204     // nodes pulled off the worklist.
1205     if (Level == AfterLegalizeDAG) {
1206       SmallSetVector<SDNode *, 16> UpdatedNodes;
1207       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1208
1209       for (SDNode *LN : UpdatedNodes) {
1210         AddToWorklist(LN);
1211         AddUsersToWorklist(LN);
1212       }
1213       if (!NIsValid)
1214         continue;
1215     }
1216
1217     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1218
1219     // Add any operands of the new node which have not yet been combined to the
1220     // worklist as well. Because the worklist uniques things already, this
1221     // won't repeatedly process the same operand.
1222     CombinedNodes.insert(N);
1223     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1224       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1225         AddToWorklist(N->getOperand(i).getNode());
1226
1227     SDValue RV = combine(N);
1228
1229     if (!RV.getNode())
1230       continue;
1231
1232     ++NodesCombined;
1233
1234     // If we get back the same node we passed in, rather than a new node or
1235     // zero, we know that the node must have defined multiple values and
1236     // CombineTo was used.  Since CombineTo takes care of the worklist
1237     // mechanics for us, we have no work to do in this case.
1238     if (RV.getNode() == N)
1239       continue;
1240
1241     assert(N->getOpcode() != ISD::DELETED_NODE &&
1242            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1243            "Node was deleted but visit returned new node!");
1244
1245     DEBUG(dbgs() << " ... into: ";
1246           RV.getNode()->dump(&DAG));
1247
1248     // Transfer debug value.
1249     DAG.TransferDbgValues(SDValue(N, 0), RV);
1250     if (N->getNumValues() == RV.getNode()->getNumValues())
1251       DAG.ReplaceAllUsesWith(N, RV.getNode());
1252     else {
1253       assert(N->getValueType(0) == RV.getValueType() &&
1254              N->getNumValues() == 1 && "Type mismatch");
1255       SDValue OpV = RV;
1256       DAG.ReplaceAllUsesWith(N, &OpV);
1257     }
1258
1259     // Push the new node and any users onto the worklist
1260     AddToWorklist(RV.getNode());
1261     AddUsersToWorklist(RV.getNode());
1262
1263     // Finally, if the node is now dead, remove it from the graph.  The node
1264     // may not be dead if the replacement process recursively simplified to
1265     // something else needing this node. This will also take care of adding any
1266     // operands which have lost a user to the worklist.
1267     recursivelyDeleteUnusedNodes(N);
1268   }
1269
1270   // If the root changed (e.g. it was a dead load, update the root).
1271   DAG.setRoot(Dummy.getValue());
1272   DAG.RemoveDeadNodes();
1273 }
1274
1275 SDValue DAGCombiner::visit(SDNode *N) {
1276   switch (N->getOpcode()) {
1277   default: break;
1278   case ISD::TokenFactor:        return visitTokenFactor(N);
1279   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1280   case ISD::ADD:                return visitADD(N);
1281   case ISD::SUB:                return visitSUB(N);
1282   case ISD::ADDC:               return visitADDC(N);
1283   case ISD::SUBC:               return visitSUBC(N);
1284   case ISD::ADDE:               return visitADDE(N);
1285   case ISD::SUBE:               return visitSUBE(N);
1286   case ISD::MUL:                return visitMUL(N);
1287   case ISD::SDIV:               return visitSDIV(N);
1288   case ISD::UDIV:               return visitUDIV(N);
1289   case ISD::SREM:               return visitSREM(N);
1290   case ISD::UREM:               return visitUREM(N);
1291   case ISD::MULHU:              return visitMULHU(N);
1292   case ISD::MULHS:              return visitMULHS(N);
1293   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1294   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1295   case ISD::SMULO:              return visitSMULO(N);
1296   case ISD::UMULO:              return visitUMULO(N);
1297   case ISD::SDIVREM:            return visitSDIVREM(N);
1298   case ISD::UDIVREM:            return visitUDIVREM(N);
1299   case ISD::AND:                return visitAND(N);
1300   case ISD::OR:                 return visitOR(N);
1301   case ISD::XOR:                return visitXOR(N);
1302   case ISD::SHL:                return visitSHL(N);
1303   case ISD::SRA:                return visitSRA(N);
1304   case ISD::SRL:                return visitSRL(N);
1305   case ISD::ROTR:
1306   case ISD::ROTL:               return visitRotate(N);
1307   case ISD::CTLZ:               return visitCTLZ(N);
1308   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1309   case ISD::CTTZ:               return visitCTTZ(N);
1310   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1311   case ISD::CTPOP:              return visitCTPOP(N);
1312   case ISD::SELECT:             return visitSELECT(N);
1313   case ISD::VSELECT:            return visitVSELECT(N);
1314   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1315   case ISD::SETCC:              return visitSETCC(N);
1316   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1317   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1318   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1319   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1320   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1321   case ISD::BITCAST:            return visitBITCAST(N);
1322   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1323   case ISD::FADD:               return visitFADD(N);
1324   case ISD::FSUB:               return visitFSUB(N);
1325   case ISD::FMUL:               return visitFMUL(N);
1326   case ISD::FMA:                return visitFMA(N);
1327   case ISD::FDIV:               return visitFDIV(N);
1328   case ISD::FREM:               return visitFREM(N);
1329   case ISD::FSQRT:              return visitFSQRT(N);
1330   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1331   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1332   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1333   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1334   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1335   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1336   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1337   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1338   case ISD::FNEG:               return visitFNEG(N);
1339   case ISD::FABS:               return visitFABS(N);
1340   case ISD::FFLOOR:             return visitFFLOOR(N);
1341   case ISD::FMINNUM:            return visitFMINNUM(N);
1342   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1343   case ISD::FCEIL:              return visitFCEIL(N);
1344   case ISD::FTRUNC:             return visitFTRUNC(N);
1345   case ISD::BRCOND:             return visitBRCOND(N);
1346   case ISD::BR_CC:              return visitBR_CC(N);
1347   case ISD::LOAD:               return visitLOAD(N);
1348   case ISD::STORE:              return visitSTORE(N);
1349   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1350   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1351   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1352   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1353   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1354   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1355   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1356   case ISD::MLOAD:              return visitMLOAD(N);
1357   case ISD::MSTORE:             return visitMSTORE(N);
1358   }
1359   return SDValue();
1360 }
1361
1362 SDValue DAGCombiner::combine(SDNode *N) {
1363   SDValue RV = visit(N);
1364
1365   // If nothing happened, try a target-specific DAG combine.
1366   if (!RV.getNode()) {
1367     assert(N->getOpcode() != ISD::DELETED_NODE &&
1368            "Node was deleted but visit returned NULL!");
1369
1370     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1371         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1372
1373       // Expose the DAG combiner to the target combiner impls.
1374       TargetLowering::DAGCombinerInfo
1375         DagCombineInfo(DAG, Level, false, this);
1376
1377       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1378     }
1379   }
1380
1381   // If nothing happened still, try promoting the operation.
1382   if (!RV.getNode()) {
1383     switch (N->getOpcode()) {
1384     default: break;
1385     case ISD::ADD:
1386     case ISD::SUB:
1387     case ISD::MUL:
1388     case ISD::AND:
1389     case ISD::OR:
1390     case ISD::XOR:
1391       RV = PromoteIntBinOp(SDValue(N, 0));
1392       break;
1393     case ISD::SHL:
1394     case ISD::SRA:
1395     case ISD::SRL:
1396       RV = PromoteIntShiftOp(SDValue(N, 0));
1397       break;
1398     case ISD::SIGN_EXTEND:
1399     case ISD::ZERO_EXTEND:
1400     case ISD::ANY_EXTEND:
1401       RV = PromoteExtend(SDValue(N, 0));
1402       break;
1403     case ISD::LOAD:
1404       if (PromoteLoad(SDValue(N, 0)))
1405         RV = SDValue(N, 0);
1406       break;
1407     }
1408   }
1409
1410   // If N is a commutative binary node, try commuting it to enable more
1411   // sdisel CSE.
1412   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1413       N->getNumValues() == 1) {
1414     SDValue N0 = N->getOperand(0);
1415     SDValue N1 = N->getOperand(1);
1416
1417     // Constant operands are canonicalized to RHS.
1418     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1419       SDValue Ops[] = {N1, N0};
1420       SDNode *CSENode;
1421       if (const BinaryWithFlagsSDNode *BinNode =
1422               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1423         CSENode = DAG.getNodeIfExists(
1424             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1425             BinNode->hasNoSignedWrap(), BinNode->isExact());
1426       } else {
1427         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1428       }
1429       if (CSENode)
1430         return SDValue(CSENode, 0);
1431     }
1432   }
1433
1434   return RV;
1435 }
1436
1437 /// Given a node, return its input chain if it has one, otherwise return a null
1438 /// sd operand.
1439 static SDValue getInputChainForNode(SDNode *N) {
1440   if (unsigned NumOps = N->getNumOperands()) {
1441     if (N->getOperand(0).getValueType() == MVT::Other)
1442       return N->getOperand(0);
1443     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1444       return N->getOperand(NumOps-1);
1445     for (unsigned i = 1; i < NumOps-1; ++i)
1446       if (N->getOperand(i).getValueType() == MVT::Other)
1447         return N->getOperand(i);
1448   }
1449   return SDValue();
1450 }
1451
1452 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1453   // If N has two operands, where one has an input chain equal to the other,
1454   // the 'other' chain is redundant.
1455   if (N->getNumOperands() == 2) {
1456     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1457       return N->getOperand(0);
1458     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1459       return N->getOperand(1);
1460   }
1461
1462   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1463   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1464   SmallPtrSet<SDNode*, 16> SeenOps;
1465   bool Changed = false;             // If we should replace this token factor.
1466
1467   // Start out with this token factor.
1468   TFs.push_back(N);
1469
1470   // Iterate through token factors.  The TFs grows when new token factors are
1471   // encountered.
1472   for (unsigned i = 0; i < TFs.size(); ++i) {
1473     SDNode *TF = TFs[i];
1474
1475     // Check each of the operands.
1476     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1477       SDValue Op = TF->getOperand(i);
1478
1479       switch (Op.getOpcode()) {
1480       case ISD::EntryToken:
1481         // Entry tokens don't need to be added to the list. They are
1482         // rededundant.
1483         Changed = true;
1484         break;
1485
1486       case ISD::TokenFactor:
1487         if (Op.hasOneUse() &&
1488             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1489           // Queue up for processing.
1490           TFs.push_back(Op.getNode());
1491           // Clean up in case the token factor is removed.
1492           AddToWorklist(Op.getNode());
1493           Changed = true;
1494           break;
1495         }
1496         // Fall thru
1497
1498       default:
1499         // Only add if it isn't already in the list.
1500         if (SeenOps.insert(Op.getNode()).second)
1501           Ops.push_back(Op);
1502         else
1503           Changed = true;
1504         break;
1505       }
1506     }
1507   }
1508
1509   SDValue Result;
1510
1511   // If we've change things around then replace token factor.
1512   if (Changed) {
1513     if (Ops.empty()) {
1514       // The entry token is the only possible outcome.
1515       Result = DAG.getEntryNode();
1516     } else {
1517       // New and improved token factor.
1518       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1519     }
1520
1521     // Don't add users to work list.
1522     return CombineTo(N, Result, false);
1523   }
1524
1525   return Result;
1526 }
1527
1528 /// MERGE_VALUES can always be eliminated.
1529 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1530   WorklistRemover DeadNodes(*this);
1531   // Replacing results may cause a different MERGE_VALUES to suddenly
1532   // be CSE'd with N, and carry its uses with it. Iterate until no
1533   // uses remain, to ensure that the node can be safely deleted.
1534   // First add the users of this node to the work list so that they
1535   // can be tried again once they have new operands.
1536   AddUsersToWorklist(N);
1537   do {
1538     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1539       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1540   } while (!N->use_empty());
1541   deleteAndRecombine(N);
1542   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1543 }
1544
1545 SDValue DAGCombiner::visitADD(SDNode *N) {
1546   SDValue N0 = N->getOperand(0);
1547   SDValue N1 = N->getOperand(1);
1548   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1549   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1550   EVT VT = N0.getValueType();
1551
1552   // fold vector ops
1553   if (VT.isVector()) {
1554     SDValue FoldedVOp = SimplifyVBinOp(N);
1555     if (FoldedVOp.getNode()) return FoldedVOp;
1556
1557     // fold (add x, 0) -> x, vector edition
1558     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1559       return N0;
1560     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1561       return N1;
1562   }
1563
1564   // fold (add x, undef) -> undef
1565   if (N0.getOpcode() == ISD::UNDEF)
1566     return N0;
1567   if (N1.getOpcode() == ISD::UNDEF)
1568     return N1;
1569   // fold (add c1, c2) -> c1+c2
1570   if (N0C && N1C)
1571     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1572   // canonicalize constant to RHS
1573   if (N0C && !N1C)
1574     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1575   // fold (add x, 0) -> x
1576   if (N1C && N1C->isNullValue())
1577     return N0;
1578   // fold (add Sym, c) -> Sym+c
1579   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1580     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1581         GA->getOpcode() == ISD::GlobalAddress)
1582       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1583                                   GA->getOffset() +
1584                                     (uint64_t)N1C->getSExtValue());
1585   // fold ((c1-A)+c2) -> (c1+c2)-A
1586   if (N1C && N0.getOpcode() == ISD::SUB)
1587     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1588       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1589                          DAG.getConstant(N1C->getAPIntValue()+
1590                                          N0C->getAPIntValue(), VT),
1591                          N0.getOperand(1));
1592   // reassociate add
1593   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1594   if (RADD.getNode())
1595     return RADD;
1596   // fold ((0-A) + B) -> B-A
1597   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1598       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1599     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1600   // fold (A + (0-B)) -> A-B
1601   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1602       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1603     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1604   // fold (A+(B-A)) -> B
1605   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1606     return N1.getOperand(0);
1607   // fold ((B-A)+A) -> B
1608   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1609     return N0.getOperand(0);
1610   // fold (A+(B-(A+C))) to (B-C)
1611   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1612       N0 == N1.getOperand(1).getOperand(0))
1613     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1614                        N1.getOperand(1).getOperand(1));
1615   // fold (A+(B-(C+A))) to (B-C)
1616   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1617       N0 == N1.getOperand(1).getOperand(1))
1618     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1619                        N1.getOperand(1).getOperand(0));
1620   // fold (A+((B-A)+or-C)) to (B+or-C)
1621   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1622       N1.getOperand(0).getOpcode() == ISD::SUB &&
1623       N0 == N1.getOperand(0).getOperand(1))
1624     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1625                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1626
1627   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1628   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1629     SDValue N00 = N0.getOperand(0);
1630     SDValue N01 = N0.getOperand(1);
1631     SDValue N10 = N1.getOperand(0);
1632     SDValue N11 = N1.getOperand(1);
1633
1634     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1635       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1636                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1637                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1638   }
1639
1640   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1641     return SDValue(N, 0);
1642
1643   // fold (a+b) -> (a|b) iff a and b share no bits.
1644   if (VT.isInteger() && !VT.isVector()) {
1645     APInt LHSZero, LHSOne;
1646     APInt RHSZero, RHSOne;
1647     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1648
1649     if (LHSZero.getBoolValue()) {
1650       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1651
1652       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1653       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1654       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1655         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1656           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1657       }
1658     }
1659   }
1660
1661   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1662   if (N1.getOpcode() == ISD::SHL &&
1663       N1.getOperand(0).getOpcode() == ISD::SUB)
1664     if (ConstantSDNode *C =
1665           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1666       if (C->getAPIntValue() == 0)
1667         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1668                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1669                                        N1.getOperand(0).getOperand(1),
1670                                        N1.getOperand(1)));
1671   if (N0.getOpcode() == ISD::SHL &&
1672       N0.getOperand(0).getOpcode() == ISD::SUB)
1673     if (ConstantSDNode *C =
1674           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1675       if (C->getAPIntValue() == 0)
1676         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1677                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1678                                        N0.getOperand(0).getOperand(1),
1679                                        N0.getOperand(1)));
1680
1681   if (N1.getOpcode() == ISD::AND) {
1682     SDValue AndOp0 = N1.getOperand(0);
1683     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1684     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1685     unsigned DestBits = VT.getScalarType().getSizeInBits();
1686
1687     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1688     // and similar xforms where the inner op is either ~0 or 0.
1689     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1690       SDLoc DL(N);
1691       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1692     }
1693   }
1694
1695   // add (sext i1), X -> sub X, (zext i1)
1696   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1697       N0.getOperand(0).getValueType() == MVT::i1 &&
1698       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1699     SDLoc DL(N);
1700     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1701     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1702   }
1703
1704   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1705   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1706     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1707     if (TN->getVT() == MVT::i1) {
1708       SDLoc DL(N);
1709       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1710                                  DAG.getConstant(1, VT));
1711       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1712     }
1713   }
1714
1715   return SDValue();
1716 }
1717
1718 SDValue DAGCombiner::visitADDC(SDNode *N) {
1719   SDValue N0 = N->getOperand(0);
1720   SDValue N1 = N->getOperand(1);
1721   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1722   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1723   EVT VT = N0.getValueType();
1724
1725   // If the flag result is dead, turn this into an ADD.
1726   if (!N->hasAnyUseOfValue(1))
1727     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1728                      DAG.getNode(ISD::CARRY_FALSE,
1729                                  SDLoc(N), MVT::Glue));
1730
1731   // canonicalize constant to RHS.
1732   if (N0C && !N1C)
1733     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1734
1735   // fold (addc x, 0) -> x + no carry out
1736   if (N1C && N1C->isNullValue())
1737     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1738                                         SDLoc(N), MVT::Glue));
1739
1740   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1741   APInt LHSZero, LHSOne;
1742   APInt RHSZero, RHSOne;
1743   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1744
1745   if (LHSZero.getBoolValue()) {
1746     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1747
1748     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1749     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1750     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1751       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1752                        DAG.getNode(ISD::CARRY_FALSE,
1753                                    SDLoc(N), MVT::Glue));
1754   }
1755
1756   return SDValue();
1757 }
1758
1759 SDValue DAGCombiner::visitADDE(SDNode *N) {
1760   SDValue N0 = N->getOperand(0);
1761   SDValue N1 = N->getOperand(1);
1762   SDValue CarryIn = N->getOperand(2);
1763   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1764   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1765
1766   // canonicalize constant to RHS
1767   if (N0C && !N1C)
1768     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1769                        N1, N0, CarryIn);
1770
1771   // fold (adde x, y, false) -> (addc x, y)
1772   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1773     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1774
1775   return SDValue();
1776 }
1777
1778 // Since it may not be valid to emit a fold to zero for vector initializers
1779 // check if we can before folding.
1780 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1781                              SelectionDAG &DAG,
1782                              bool LegalOperations, bool LegalTypes) {
1783   if (!VT.isVector())
1784     return DAG.getConstant(0, VT);
1785   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1786     return DAG.getConstant(0, VT);
1787   return SDValue();
1788 }
1789
1790 SDValue DAGCombiner::visitSUB(SDNode *N) {
1791   SDValue N0 = N->getOperand(0);
1792   SDValue N1 = N->getOperand(1);
1793   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1794   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1795   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1796     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1797   EVT VT = N0.getValueType();
1798
1799   // fold vector ops
1800   if (VT.isVector()) {
1801     SDValue FoldedVOp = SimplifyVBinOp(N);
1802     if (FoldedVOp.getNode()) return FoldedVOp;
1803
1804     // fold (sub x, 0) -> x, vector edition
1805     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1806       return N0;
1807   }
1808
1809   // fold (sub x, x) -> 0
1810   // FIXME: Refactor this and xor and other similar operations together.
1811   if (N0 == N1)
1812     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1813   // fold (sub c1, c2) -> c1-c2
1814   if (N0C && N1C)
1815     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1816   // fold (sub x, c) -> (add x, -c)
1817   if (N1C)
1818     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1819                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1820   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1821   if (N0C && N0C->isAllOnesValue())
1822     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1823   // fold A-(A-B) -> B
1824   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1825     return N1.getOperand(1);
1826   // fold (A+B)-A -> B
1827   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1828     return N0.getOperand(1);
1829   // fold (A+B)-B -> A
1830   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1831     return N0.getOperand(0);
1832   // fold C2-(A+C1) -> (C2-C1)-A
1833   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1834     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1835                                    VT);
1836     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1837                        N1.getOperand(0));
1838   }
1839   // fold ((A+(B+or-C))-B) -> A+or-C
1840   if (N0.getOpcode() == ISD::ADD &&
1841       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1842        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1843       N0.getOperand(1).getOperand(0) == N1)
1844     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1845                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1846   // fold ((A+(C+B))-B) -> A+C
1847   if (N0.getOpcode() == ISD::ADD &&
1848       N0.getOperand(1).getOpcode() == ISD::ADD &&
1849       N0.getOperand(1).getOperand(1) == N1)
1850     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1851                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1852   // fold ((A-(B-C))-C) -> A-B
1853   if (N0.getOpcode() == ISD::SUB &&
1854       N0.getOperand(1).getOpcode() == ISD::SUB &&
1855       N0.getOperand(1).getOperand(1) == N1)
1856     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1857                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1858
1859   // If either operand of a sub is undef, the result is undef
1860   if (N0.getOpcode() == ISD::UNDEF)
1861     return N0;
1862   if (N1.getOpcode() == ISD::UNDEF)
1863     return N1;
1864
1865   // If the relocation model supports it, consider symbol offsets.
1866   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1867     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1868       // fold (sub Sym, c) -> Sym-c
1869       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1870         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1871                                     GA->getOffset() -
1872                                       (uint64_t)N1C->getSExtValue());
1873       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1874       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1875         if (GA->getGlobal() == GB->getGlobal())
1876           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1877                                  VT);
1878     }
1879
1880   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1881   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1882     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1883     if (TN->getVT() == MVT::i1) {
1884       SDLoc DL(N);
1885       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1886                                  DAG.getConstant(1, VT));
1887       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1888     }
1889   }
1890
1891   return SDValue();
1892 }
1893
1894 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1895   SDValue N0 = N->getOperand(0);
1896   SDValue N1 = N->getOperand(1);
1897   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1898   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1899   EVT VT = N0.getValueType();
1900
1901   // If the flag result is dead, turn this into an SUB.
1902   if (!N->hasAnyUseOfValue(1))
1903     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1904                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1905                                  MVT::Glue));
1906
1907   // fold (subc x, x) -> 0 + no borrow
1908   if (N0 == N1)
1909     return CombineTo(N, DAG.getConstant(0, VT),
1910                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1911                                  MVT::Glue));
1912
1913   // fold (subc x, 0) -> x + no borrow
1914   if (N1C && N1C->isNullValue())
1915     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1916                                         MVT::Glue));
1917
1918   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1919   if (N0C && N0C->isAllOnesValue())
1920     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1921                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1922                                  MVT::Glue));
1923
1924   return SDValue();
1925 }
1926
1927 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1928   SDValue N0 = N->getOperand(0);
1929   SDValue N1 = N->getOperand(1);
1930   SDValue CarryIn = N->getOperand(2);
1931
1932   // fold (sube x, y, false) -> (subc x, y)
1933   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1934     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1935
1936   return SDValue();
1937 }
1938
1939 SDValue DAGCombiner::visitMUL(SDNode *N) {
1940   SDValue N0 = N->getOperand(0);
1941   SDValue N1 = N->getOperand(1);
1942   EVT VT = N0.getValueType();
1943
1944   // fold (mul x, undef) -> 0
1945   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1946     return DAG.getConstant(0, VT);
1947
1948   bool N0IsConst = false;
1949   bool N1IsConst = false;
1950   APInt ConstValue0, ConstValue1;
1951   // fold vector ops
1952   if (VT.isVector()) {
1953     SDValue FoldedVOp = SimplifyVBinOp(N);
1954     if (FoldedVOp.getNode()) return FoldedVOp;
1955
1956     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1957     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1958   } else {
1959     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1960     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1961                             : APInt();
1962     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1963     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1964                             : APInt();
1965   }
1966
1967   // fold (mul c1, c2) -> c1*c2
1968   if (N0IsConst && N1IsConst)
1969     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1970
1971   // canonicalize constant to RHS
1972   if (N0IsConst && !N1IsConst)
1973     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1974   // fold (mul x, 0) -> 0
1975   if (N1IsConst && ConstValue1 == 0)
1976     return N1;
1977   // We require a splat of the entire scalar bit width for non-contiguous
1978   // bit patterns.
1979   bool IsFullSplat =
1980     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1981   // fold (mul x, 1) -> x
1982   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1983     return N0;
1984   // fold (mul x, -1) -> 0-x
1985   if (N1IsConst && ConstValue1.isAllOnesValue())
1986     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1987                        DAG.getConstant(0, VT), N0);
1988   // fold (mul x, (1 << c)) -> x << c
1989   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1990     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1991                        DAG.getConstant(ConstValue1.logBase2(),
1992                                        getShiftAmountTy(N0.getValueType())));
1993   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1994   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1995     unsigned Log2Val = (-ConstValue1).logBase2();
1996     // FIXME: If the input is something that is easily negated (e.g. a
1997     // single-use add), we should put the negate there.
1998     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1999                        DAG.getConstant(0, VT),
2000                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
2001                             DAG.getConstant(Log2Val,
2002                                       getShiftAmountTy(N0.getValueType()))));
2003   }
2004
2005   APInt Val;
2006   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2007   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2008       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2009                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2010     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2011                              N1, N0.getOperand(1));
2012     AddToWorklist(C3.getNode());
2013     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2014                        N0.getOperand(0), C3);
2015   }
2016
2017   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2018   // use.
2019   {
2020     SDValue Sh(nullptr,0), Y(nullptr,0);
2021     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2022     if (N0.getOpcode() == ISD::SHL &&
2023         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2024                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2025         N0.getNode()->hasOneUse()) {
2026       Sh = N0; Y = N1;
2027     } else if (N1.getOpcode() == ISD::SHL &&
2028                isa<ConstantSDNode>(N1.getOperand(1)) &&
2029                N1.getNode()->hasOneUse()) {
2030       Sh = N1; Y = N0;
2031     }
2032
2033     if (Sh.getNode()) {
2034       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2035                                 Sh.getOperand(0), Y);
2036       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2037                          Mul, Sh.getOperand(1));
2038     }
2039   }
2040
2041   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2042   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2043       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2044                      isa<ConstantSDNode>(N0.getOperand(1))))
2045     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2046                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2047                                    N0.getOperand(0), N1),
2048                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2049                                    N0.getOperand(1), N1));
2050
2051   // reassociate mul
2052   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2053   if (RMUL.getNode())
2054     return RMUL;
2055
2056   return SDValue();
2057 }
2058
2059 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2060   SDValue N0 = N->getOperand(0);
2061   SDValue N1 = N->getOperand(1);
2062   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2063   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2064   EVT VT = N->getValueType(0);
2065
2066   // fold vector ops
2067   if (VT.isVector()) {
2068     SDValue FoldedVOp = SimplifyVBinOp(N);
2069     if (FoldedVOp.getNode()) return FoldedVOp;
2070   }
2071
2072   // fold (sdiv c1, c2) -> c1/c2
2073   if (N0C && N1C && !N1C->isNullValue())
2074     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2075   // fold (sdiv X, 1) -> X
2076   if (N1C && N1C->getAPIntValue() == 1LL)
2077     return N0;
2078   // fold (sdiv X, -1) -> 0-X
2079   if (N1C && N1C->isAllOnesValue())
2080     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2081                        DAG.getConstant(0, VT), N0);
2082   // If we know the sign bits of both operands are zero, strength reduce to a
2083   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2084   if (!VT.isVector()) {
2085     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2086       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2087                          N0, N1);
2088   }
2089
2090   // fold (sdiv X, pow2) -> simple ops after legalize
2091   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2092                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2093     // If dividing by powers of two is cheap, then don't perform the following
2094     // fold.
2095     if (TLI.isPow2SDivCheap())
2096       return SDValue();
2097
2098     // Target-specific implementation of sdiv x, pow2.
2099     SDValue Res = BuildSDIVPow2(N);
2100     if (Res.getNode())
2101       return Res;
2102
2103     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2104
2105     // Splat the sign bit into the register
2106     SDValue SGN =
2107         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2108                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2109                                     getShiftAmountTy(N0.getValueType())));
2110     AddToWorklist(SGN.getNode());
2111
2112     // Add (N0 < 0) ? abs2 - 1 : 0;
2113     SDValue SRL =
2114         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2115                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2116                                     getShiftAmountTy(SGN.getValueType())));
2117     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2118     AddToWorklist(SRL.getNode());
2119     AddToWorklist(ADD.getNode());    // Divide by pow2
2120     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2121                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2122
2123     // If we're dividing by a positive value, we're done.  Otherwise, we must
2124     // negate the result.
2125     if (N1C->getAPIntValue().isNonNegative())
2126       return SRA;
2127
2128     AddToWorklist(SRA.getNode());
2129     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2130   }
2131
2132   // if integer divide is expensive and we satisfy the requirements, emit an
2133   // alternate sequence.
2134   if (N1C && !TLI.isIntDivCheap()) {
2135     SDValue Op = BuildSDIV(N);
2136     if (Op.getNode()) return Op;
2137   }
2138
2139   // undef / X -> 0
2140   if (N0.getOpcode() == ISD::UNDEF)
2141     return DAG.getConstant(0, VT);
2142   // X / undef -> undef
2143   if (N1.getOpcode() == ISD::UNDEF)
2144     return N1;
2145
2146   return SDValue();
2147 }
2148
2149 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2150   SDValue N0 = N->getOperand(0);
2151   SDValue N1 = N->getOperand(1);
2152   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2153   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2154   EVT VT = N->getValueType(0);
2155
2156   // fold vector ops
2157   if (VT.isVector()) {
2158     SDValue FoldedVOp = SimplifyVBinOp(N);
2159     if (FoldedVOp.getNode()) return FoldedVOp;
2160   }
2161
2162   // fold (udiv c1, c2) -> c1/c2
2163   if (N0C && N1C && !N1C->isNullValue())
2164     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2165   // fold (udiv x, (1 << c)) -> x >>u c
2166   if (N1C && N1C->getAPIntValue().isPowerOf2())
2167     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2168                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2169                                        getShiftAmountTy(N0.getValueType())));
2170   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2171   if (N1.getOpcode() == ISD::SHL) {
2172     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2173       if (SHC->getAPIntValue().isPowerOf2()) {
2174         EVT ADDVT = N1.getOperand(1).getValueType();
2175         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2176                                   N1.getOperand(1),
2177                                   DAG.getConstant(SHC->getAPIntValue()
2178                                                                   .logBase2(),
2179                                                   ADDVT));
2180         AddToWorklist(Add.getNode());
2181         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2182       }
2183     }
2184   }
2185   // fold (udiv x, c) -> alternate
2186   if (N1C && !TLI.isIntDivCheap()) {
2187     SDValue Op = BuildUDIV(N);
2188     if (Op.getNode()) return Op;
2189   }
2190
2191   // undef / X -> 0
2192   if (N0.getOpcode() == ISD::UNDEF)
2193     return DAG.getConstant(0, VT);
2194   // X / undef -> undef
2195   if (N1.getOpcode() == ISD::UNDEF)
2196     return N1;
2197
2198   return SDValue();
2199 }
2200
2201 SDValue DAGCombiner::visitSREM(SDNode *N) {
2202   SDValue N0 = N->getOperand(0);
2203   SDValue N1 = N->getOperand(1);
2204   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2205   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2206   EVT VT = N->getValueType(0);
2207
2208   // fold (srem c1, c2) -> c1%c2
2209   if (N0C && N1C && !N1C->isNullValue())
2210     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2211   // If we know the sign bits of both operands are zero, strength reduce to a
2212   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2213   if (!VT.isVector()) {
2214     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2215       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2216   }
2217
2218   // If X/C can be simplified by the division-by-constant logic, lower
2219   // X%C to the equivalent of X-X/C*C.
2220   if (N1C && !N1C->isNullValue()) {
2221     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2222     AddToWorklist(Div.getNode());
2223     SDValue OptimizedDiv = combine(Div.getNode());
2224     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2225       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2226                                 OptimizedDiv, N1);
2227       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2228       AddToWorklist(Mul.getNode());
2229       return Sub;
2230     }
2231   }
2232
2233   // undef % X -> 0
2234   if (N0.getOpcode() == ISD::UNDEF)
2235     return DAG.getConstant(0, VT);
2236   // X % undef -> undef
2237   if (N1.getOpcode() == ISD::UNDEF)
2238     return N1;
2239
2240   return SDValue();
2241 }
2242
2243 SDValue DAGCombiner::visitUREM(SDNode *N) {
2244   SDValue N0 = N->getOperand(0);
2245   SDValue N1 = N->getOperand(1);
2246   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2247   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2248   EVT VT = N->getValueType(0);
2249
2250   // fold (urem c1, c2) -> c1%c2
2251   if (N0C && N1C && !N1C->isNullValue())
2252     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2253   // fold (urem x, pow2) -> (and x, pow2-1)
2254   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2255     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2256                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2257   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2258   if (N1.getOpcode() == ISD::SHL) {
2259     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2260       if (SHC->getAPIntValue().isPowerOf2()) {
2261         SDValue Add =
2262           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2263                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2264                                  VT));
2265         AddToWorklist(Add.getNode());
2266         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2267       }
2268     }
2269   }
2270
2271   // If X/C can be simplified by the division-by-constant logic, lower
2272   // X%C to the equivalent of X-X/C*C.
2273   if (N1C && !N1C->isNullValue()) {
2274     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2275     AddToWorklist(Div.getNode());
2276     SDValue OptimizedDiv = combine(Div.getNode());
2277     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2278       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2279                                 OptimizedDiv, N1);
2280       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2281       AddToWorklist(Mul.getNode());
2282       return Sub;
2283     }
2284   }
2285
2286   // undef % X -> 0
2287   if (N0.getOpcode() == ISD::UNDEF)
2288     return DAG.getConstant(0, VT);
2289   // X % undef -> undef
2290   if (N1.getOpcode() == ISD::UNDEF)
2291     return N1;
2292
2293   return SDValue();
2294 }
2295
2296 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2297   SDValue N0 = N->getOperand(0);
2298   SDValue N1 = N->getOperand(1);
2299   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2300   EVT VT = N->getValueType(0);
2301   SDLoc DL(N);
2302
2303   // fold (mulhs x, 0) -> 0
2304   if (N1C && N1C->isNullValue())
2305     return N1;
2306   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2307   if (N1C && N1C->getAPIntValue() == 1)
2308     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2309                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2310                                        getShiftAmountTy(N0.getValueType())));
2311   // fold (mulhs x, undef) -> 0
2312   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2313     return DAG.getConstant(0, VT);
2314
2315   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2316   // plus a shift.
2317   if (VT.isSimple() && !VT.isVector()) {
2318     MVT Simple = VT.getSimpleVT();
2319     unsigned SimpleSize = Simple.getSizeInBits();
2320     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2321     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2322       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2323       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2324       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2325       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2326             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2327       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2328     }
2329   }
2330
2331   return SDValue();
2332 }
2333
2334 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2335   SDValue N0 = N->getOperand(0);
2336   SDValue N1 = N->getOperand(1);
2337   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2338   EVT VT = N->getValueType(0);
2339   SDLoc DL(N);
2340
2341   // fold (mulhu x, 0) -> 0
2342   if (N1C && N1C->isNullValue())
2343     return N1;
2344   // fold (mulhu x, 1) -> 0
2345   if (N1C && N1C->getAPIntValue() == 1)
2346     return DAG.getConstant(0, N0.getValueType());
2347   // fold (mulhu x, undef) -> 0
2348   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2349     return DAG.getConstant(0, VT);
2350
2351   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2352   // plus a shift.
2353   if (VT.isSimple() && !VT.isVector()) {
2354     MVT Simple = VT.getSimpleVT();
2355     unsigned SimpleSize = Simple.getSizeInBits();
2356     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2357     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2358       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2359       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2360       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2361       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2362             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2363       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2364     }
2365   }
2366
2367   return SDValue();
2368 }
2369
2370 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2371 /// give the opcodes for the two computations that are being performed. Return
2372 /// true if a simplification was made.
2373 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2374                                                 unsigned HiOp) {
2375   // If the high half is not needed, just compute the low half.
2376   bool HiExists = N->hasAnyUseOfValue(1);
2377   if (!HiExists &&
2378       (!LegalOperations ||
2379        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2380     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2381     return CombineTo(N, Res, Res);
2382   }
2383
2384   // If the low half is not needed, just compute the high half.
2385   bool LoExists = N->hasAnyUseOfValue(0);
2386   if (!LoExists &&
2387       (!LegalOperations ||
2388        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2389     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2390     return CombineTo(N, Res, Res);
2391   }
2392
2393   // If both halves are used, return as it is.
2394   if (LoExists && HiExists)
2395     return SDValue();
2396
2397   // If the two computed results can be simplified separately, separate them.
2398   if (LoExists) {
2399     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2400     AddToWorklist(Lo.getNode());
2401     SDValue LoOpt = combine(Lo.getNode());
2402     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2403         (!LegalOperations ||
2404          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2405       return CombineTo(N, LoOpt, LoOpt);
2406   }
2407
2408   if (HiExists) {
2409     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2410     AddToWorklist(Hi.getNode());
2411     SDValue HiOpt = combine(Hi.getNode());
2412     if (HiOpt.getNode() && HiOpt != Hi &&
2413         (!LegalOperations ||
2414          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2415       return CombineTo(N, HiOpt, HiOpt);
2416   }
2417
2418   return SDValue();
2419 }
2420
2421 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2422   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2423   if (Res.getNode()) return Res;
2424
2425   EVT VT = N->getValueType(0);
2426   SDLoc DL(N);
2427
2428   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2429   // plus a shift.
2430   if (VT.isSimple() && !VT.isVector()) {
2431     MVT Simple = VT.getSimpleVT();
2432     unsigned SimpleSize = Simple.getSizeInBits();
2433     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2434     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2435       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2436       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2437       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2438       // Compute the high part as N1.
2439       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2440             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2441       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2442       // Compute the low part as N0.
2443       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2444       return CombineTo(N, Lo, Hi);
2445     }
2446   }
2447
2448   return SDValue();
2449 }
2450
2451 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2452   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2453   if (Res.getNode()) return Res;
2454
2455   EVT VT = N->getValueType(0);
2456   SDLoc DL(N);
2457
2458   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2459   // plus a shift.
2460   if (VT.isSimple() && !VT.isVector()) {
2461     MVT Simple = VT.getSimpleVT();
2462     unsigned SimpleSize = Simple.getSizeInBits();
2463     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2464     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2465       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2466       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2467       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2468       // Compute the high part as N1.
2469       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2470             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2471       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2472       // Compute the low part as N0.
2473       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2474       return CombineTo(N, Lo, Hi);
2475     }
2476   }
2477
2478   return SDValue();
2479 }
2480
2481 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2482   // (smulo x, 2) -> (saddo x, x)
2483   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2484     if (C2->getAPIntValue() == 2)
2485       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2486                          N->getOperand(0), N->getOperand(0));
2487
2488   return SDValue();
2489 }
2490
2491 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2492   // (umulo x, 2) -> (uaddo x, x)
2493   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2494     if (C2->getAPIntValue() == 2)
2495       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2496                          N->getOperand(0), N->getOperand(0));
2497
2498   return SDValue();
2499 }
2500
2501 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2502   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2503   if (Res.getNode()) return Res;
2504
2505   return SDValue();
2506 }
2507
2508 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2509   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2510   if (Res.getNode()) return Res;
2511
2512   return SDValue();
2513 }
2514
2515 /// If this is a binary operator with two operands of the same opcode, try to
2516 /// simplify it.
2517 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2518   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2519   EVT VT = N0.getValueType();
2520   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2521
2522   // Bail early if none of these transforms apply.
2523   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2524
2525   // For each of OP in AND/OR/XOR:
2526   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2527   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2528   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2529   // fold (OP (bswap x), (bswap y)) -> (bswap (OP x, y))
2530   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2531   //
2532   // do not sink logical op inside of a vector extend, since it may combine
2533   // into a vsetcc.
2534   EVT Op0VT = N0.getOperand(0).getValueType();
2535   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2536        N0.getOpcode() == ISD::SIGN_EXTEND ||
2537        N0.getOpcode() == ISD::BSWAP ||
2538        // Avoid infinite looping with PromoteIntBinOp.
2539        (N0.getOpcode() == ISD::ANY_EXTEND &&
2540         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2541        (N0.getOpcode() == ISD::TRUNCATE &&
2542         (!TLI.isZExtFree(VT, Op0VT) ||
2543          !TLI.isTruncateFree(Op0VT, VT)) &&
2544         TLI.isTypeLegal(Op0VT))) &&
2545       !VT.isVector() &&
2546       Op0VT == N1.getOperand(0).getValueType() &&
2547       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2548     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2549                                  N0.getOperand(0).getValueType(),
2550                                  N0.getOperand(0), N1.getOperand(0));
2551     AddToWorklist(ORNode.getNode());
2552     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2553   }
2554
2555   // For each of OP in SHL/SRL/SRA/AND...
2556   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2557   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2558   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2559   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2560        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2561       N0.getOperand(1) == N1.getOperand(1)) {
2562     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2563                                  N0.getOperand(0).getValueType(),
2564                                  N0.getOperand(0), N1.getOperand(0));
2565     AddToWorklist(ORNode.getNode());
2566     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2567                        ORNode, N0.getOperand(1));
2568   }
2569
2570   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2571   // Only perform this optimization after type legalization and before
2572   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2573   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2574   // we don't want to undo this promotion.
2575   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2576   // on scalars.
2577   if ((N0.getOpcode() == ISD::BITCAST ||
2578        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2579       Level == AfterLegalizeTypes) {
2580     SDValue In0 = N0.getOperand(0);
2581     SDValue In1 = N1.getOperand(0);
2582     EVT In0Ty = In0.getValueType();
2583     EVT In1Ty = In1.getValueType();
2584     SDLoc DL(N);
2585     // If both incoming values are integers, and the original types are the
2586     // same.
2587     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2588       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2589       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2590       AddToWorklist(Op.getNode());
2591       return BC;
2592     }
2593   }
2594
2595   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2596   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2597   // If both shuffles use the same mask, and both shuffle within a single
2598   // vector, then it is worthwhile to move the swizzle after the operation.
2599   // The type-legalizer generates this pattern when loading illegal
2600   // vector types from memory. In many cases this allows additional shuffle
2601   // optimizations.
2602   // There are other cases where moving the shuffle after the xor/and/or
2603   // is profitable even if shuffles don't perform a swizzle.
2604   // If both shuffles use the same mask, and both shuffles have the same first
2605   // or second operand, then it might still be profitable to move the shuffle
2606   // after the xor/and/or operation.
2607   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2608     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2609     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2610
2611     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2612            "Inputs to shuffles are not the same type");
2613
2614     // Check that both shuffles use the same mask. The masks are known to be of
2615     // the same length because the result vector type is the same.
2616     // Check also that shuffles have only one use to avoid introducing extra
2617     // instructions.
2618     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2619         SVN0->getMask().equals(SVN1->getMask())) {
2620       SDValue ShOp = N0->getOperand(1);
2621
2622       // Don't try to fold this node if it requires introducing a
2623       // build vector of all zeros that might be illegal at this stage.
2624       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2625         if (!LegalTypes)
2626           ShOp = DAG.getConstant(0, VT);
2627         else
2628           ShOp = SDValue();
2629       }
2630
2631       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2632       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2633       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2634       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2635         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2636                                       N0->getOperand(0), N1->getOperand(0));
2637         AddToWorklist(NewNode.getNode());
2638         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2639                                     &SVN0->getMask()[0]);
2640       }
2641
2642       // Don't try to fold this node if it requires introducing a
2643       // build vector of all zeros that might be illegal at this stage.
2644       ShOp = N0->getOperand(0);
2645       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2646         if (!LegalTypes)
2647           ShOp = DAG.getConstant(0, VT);
2648         else
2649           ShOp = SDValue();
2650       }
2651
2652       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2653       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2654       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2655       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2656         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2657                                       N0->getOperand(1), N1->getOperand(1));
2658         AddToWorklist(NewNode.getNode());
2659         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2660                                     &SVN0->getMask()[0]);
2661       }
2662     }
2663   }
2664
2665   return SDValue();
2666 }
2667
2668 SDValue DAGCombiner::visitAND(SDNode *N) {
2669   SDValue N0 = N->getOperand(0);
2670   SDValue N1 = N->getOperand(1);
2671   SDValue LL, LR, RL, RR, CC0, CC1;
2672   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2673   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2674   EVT VT = N1.getValueType();
2675   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2676
2677   // fold vector ops
2678   if (VT.isVector()) {
2679     SDValue FoldedVOp = SimplifyVBinOp(N);
2680     if (FoldedVOp.getNode()) return FoldedVOp;
2681
2682     // fold (and x, 0) -> 0, vector edition
2683     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2684       // do not return N0, because undef node may exist in N0
2685       return DAG.getConstant(
2686           APInt::getNullValue(
2687               N0.getValueType().getScalarType().getSizeInBits()),
2688           N0.getValueType());
2689     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2690       // do not return N1, because undef node may exist in N1
2691       return DAG.getConstant(
2692           APInt::getNullValue(
2693               N1.getValueType().getScalarType().getSizeInBits()),
2694           N1.getValueType());
2695
2696     // fold (and x, -1) -> x, vector edition
2697     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2698       return N1;
2699     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2700       return N0;
2701   }
2702
2703   // fold (and x, undef) -> 0
2704   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2705     return DAG.getConstant(0, VT);
2706   // fold (and c1, c2) -> c1&c2
2707   if (N0C && N1C)
2708     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2709   // canonicalize constant to RHS
2710   if (N0C && !N1C)
2711     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2712   // fold (and x, -1) -> x
2713   if (N1C && N1C->isAllOnesValue())
2714     return N0;
2715   // if (and x, c) is known to be zero, return 0
2716   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2717                                    APInt::getAllOnesValue(BitWidth)))
2718     return DAG.getConstant(0, VT);
2719   // reassociate and
2720   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2721   if (RAND.getNode())
2722     return RAND;
2723   // fold (and (or x, C), D) -> D if (C & D) == D
2724   if (N1C && N0.getOpcode() == ISD::OR)
2725     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2726       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2727         return N1;
2728   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2729   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2730     SDValue N0Op0 = N0.getOperand(0);
2731     APInt Mask = ~N1C->getAPIntValue();
2732     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2733     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2734       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2735                                  N0.getValueType(), N0Op0);
2736
2737       // Replace uses of the AND with uses of the Zero extend node.
2738       CombineTo(N, Zext);
2739
2740       // We actually want to replace all uses of the any_extend with the
2741       // zero_extend, to avoid duplicating things.  This will later cause this
2742       // AND to be folded.
2743       CombineTo(N0.getNode(), Zext);
2744       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2745     }
2746   }
2747   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2748   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2749   // already be zero by virtue of the width of the base type of the load.
2750   //
2751   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2752   // more cases.
2753   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2754        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2755       N0.getOpcode() == ISD::LOAD) {
2756     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2757                                          N0 : N0.getOperand(0) );
2758
2759     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2760     // This can be a pure constant or a vector splat, in which case we treat the
2761     // vector as a scalar and use the splat value.
2762     APInt Constant = APInt::getNullValue(1);
2763     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2764       Constant = C->getAPIntValue();
2765     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2766       APInt SplatValue, SplatUndef;
2767       unsigned SplatBitSize;
2768       bool HasAnyUndefs;
2769       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2770                                              SplatBitSize, HasAnyUndefs);
2771       if (IsSplat) {
2772         // Undef bits can contribute to a possible optimisation if set, so
2773         // set them.
2774         SplatValue |= SplatUndef;
2775
2776         // The splat value may be something like "0x00FFFFFF", which means 0 for
2777         // the first vector value and FF for the rest, repeating. We need a mask
2778         // that will apply equally to all members of the vector, so AND all the
2779         // lanes of the constant together.
2780         EVT VT = Vector->getValueType(0);
2781         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2782
2783         // If the splat value has been compressed to a bitlength lower
2784         // than the size of the vector lane, we need to re-expand it to
2785         // the lane size.
2786         if (BitWidth > SplatBitSize)
2787           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2788                SplatBitSize < BitWidth;
2789                SplatBitSize = SplatBitSize * 2)
2790             SplatValue |= SplatValue.shl(SplatBitSize);
2791
2792         Constant = APInt::getAllOnesValue(BitWidth);
2793         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2794           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2795       }
2796     }
2797
2798     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2799     // actually legal and isn't going to get expanded, else this is a false
2800     // optimisation.
2801     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2802                                                     Load->getMemoryVT());
2803
2804     // Resize the constant to the same size as the original memory access before
2805     // extension. If it is still the AllOnesValue then this AND is completely
2806     // unneeded.
2807     Constant =
2808       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2809
2810     bool B;
2811     switch (Load->getExtensionType()) {
2812     default: B = false; break;
2813     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2814     case ISD::ZEXTLOAD:
2815     case ISD::NON_EXTLOAD: B = true; break;
2816     }
2817
2818     if (B && Constant.isAllOnesValue()) {
2819       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2820       // preserve semantics once we get rid of the AND.
2821       SDValue NewLoad(Load, 0);
2822       if (Load->getExtensionType() == ISD::EXTLOAD) {
2823         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2824                               Load->getValueType(0), SDLoc(Load),
2825                               Load->getChain(), Load->getBasePtr(),
2826                               Load->getOffset(), Load->getMemoryVT(),
2827                               Load->getMemOperand());
2828         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2829         if (Load->getNumValues() == 3) {
2830           // PRE/POST_INC loads have 3 values.
2831           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2832                            NewLoad.getValue(2) };
2833           CombineTo(Load, To, 3, true);
2834         } else {
2835           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2836         }
2837       }
2838
2839       // Fold the AND away, taking care not to fold to the old load node if we
2840       // replaced it.
2841       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2842
2843       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2844     }
2845   }
2846   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2847   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2848     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2849     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2850
2851     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2852         LL.getValueType().isInteger()) {
2853       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2854       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2855         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2856                                      LR.getValueType(), LL, RL);
2857         AddToWorklist(ORNode.getNode());
2858         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2859       }
2860       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2861       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2862         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2863                                       LR.getValueType(), LL, RL);
2864         AddToWorklist(ANDNode.getNode());
2865         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2866       }
2867       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2868       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2869         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2870                                      LR.getValueType(), LL, RL);
2871         AddToWorklist(ORNode.getNode());
2872         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2873       }
2874     }
2875     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2876     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2877         Op0 == Op1 && LL.getValueType().isInteger() &&
2878       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2879                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2880                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2881                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2882       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2883                                     LL, DAG.getConstant(1, LL.getValueType()));
2884       AddToWorklist(ADDNode.getNode());
2885       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2886                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2887     }
2888     // canonicalize equivalent to ll == rl
2889     if (LL == RR && LR == RL) {
2890       Op1 = ISD::getSetCCSwappedOperands(Op1);
2891       std::swap(RL, RR);
2892     }
2893     if (LL == RL && LR == RR) {
2894       bool isInteger = LL.getValueType().isInteger();
2895       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2896       if (Result != ISD::SETCC_INVALID &&
2897           (!LegalOperations ||
2898            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2899             TLI.isOperationLegal(ISD::SETCC,
2900                             getSetCCResultType(N0.getSimpleValueType())))))
2901         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2902                             LL, LR, Result);
2903     }
2904   }
2905
2906   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2907   if (N0.getOpcode() == N1.getOpcode()) {
2908     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2909     if (Tmp.getNode()) return Tmp;
2910   }
2911
2912   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2913   // fold (and (sra)) -> (and (srl)) when possible.
2914   if (!VT.isVector() &&
2915       SimplifyDemandedBits(SDValue(N, 0)))
2916     return SDValue(N, 0);
2917
2918   // fold (zext_inreg (extload x)) -> (zextload x)
2919   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2920     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2921     EVT MemVT = LN0->getMemoryVT();
2922     // If we zero all the possible extended bits, then we can turn this into
2923     // a zextload if we are running before legalize or the operation is legal.
2924     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2925     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2926                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2927         ((!LegalOperations && !LN0->isVolatile()) ||
2928          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2929       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2930                                        LN0->getChain(), LN0->getBasePtr(),
2931                                        MemVT, LN0->getMemOperand());
2932       AddToWorklist(N);
2933       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2934       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2935     }
2936   }
2937   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2938   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2939       N0.hasOneUse()) {
2940     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2941     EVT MemVT = LN0->getMemoryVT();
2942     // If we zero all the possible extended bits, then we can turn this into
2943     // a zextload if we are running before legalize or the operation is legal.
2944     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2945     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2946                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2947         ((!LegalOperations && !LN0->isVolatile()) ||
2948          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2949       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2950                                        LN0->getChain(), LN0->getBasePtr(),
2951                                        MemVT, LN0->getMemOperand());
2952       AddToWorklist(N);
2953       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2954       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2955     }
2956   }
2957
2958   // fold (and (load x), 255) -> (zextload x, i8)
2959   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2960   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2961   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2962               (N0.getOpcode() == ISD::ANY_EXTEND &&
2963                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2964     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2965     LoadSDNode *LN0 = HasAnyExt
2966       ? cast<LoadSDNode>(N0.getOperand(0))
2967       : cast<LoadSDNode>(N0);
2968     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2969         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2970       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2971       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2972         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2973         EVT LoadedVT = LN0->getMemoryVT();
2974
2975         if (ExtVT == LoadedVT &&
2976             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2977           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2978
2979           SDValue NewLoad =
2980             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2981                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2982                            LN0->getMemOperand());
2983           AddToWorklist(N);
2984           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2985           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2986         }
2987
2988         // Do not change the width of a volatile load.
2989         // Do not generate loads of non-round integer types since these can
2990         // be expensive (and would be wrong if the type is not byte sized).
2991         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2992             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2993           EVT PtrType = LN0->getOperand(1).getValueType();
2994
2995           unsigned Alignment = LN0->getAlignment();
2996           SDValue NewPtr = LN0->getBasePtr();
2997
2998           // For big endian targets, we need to add an offset to the pointer
2999           // to load the correct bytes.  For little endian systems, we merely
3000           // need to read fewer bytes from the same pointer.
3001           if (TLI.isBigEndian()) {
3002             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
3003             unsigned EVTStoreBytes = ExtVT.getStoreSize();
3004             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
3005             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3006                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3007             Alignment = MinAlign(Alignment, PtrOff);
3008           }
3009
3010           AddToWorklist(NewPtr.getNode());
3011
3012           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3013           SDValue Load =
3014             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3015                            LN0->getChain(), NewPtr,
3016                            LN0->getPointerInfo(),
3017                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3018                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3019           AddToWorklist(N);
3020           CombineTo(LN0, Load, Load.getValue(1));
3021           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3022         }
3023       }
3024     }
3025   }
3026
3027   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3028       VT.getSizeInBits() <= 64) {
3029     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3030       APInt ADDC = ADDI->getAPIntValue();
3031       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3032         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3033         // immediate for an add, but it is legal if its top c2 bits are set,
3034         // transform the ADD so the immediate doesn't need to be materialized
3035         // in a register.
3036         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3037           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3038                                              SRLI->getZExtValue());
3039           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3040             ADDC |= Mask;
3041             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3042               SDValue NewAdd =
3043                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3044                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3045               CombineTo(N0.getNode(), NewAdd);
3046               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3047             }
3048           }
3049         }
3050       }
3051     }
3052   }
3053
3054   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3055   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3056     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3057                                        N0.getOperand(1), false);
3058     if (BSwap.getNode())
3059       return BSwap;
3060   }
3061
3062   return SDValue();
3063 }
3064
3065 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3066 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3067                                         bool DemandHighBits) {
3068   if (!LegalOperations)
3069     return SDValue();
3070
3071   EVT VT = N->getValueType(0);
3072   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3073     return SDValue();
3074   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3075     return SDValue();
3076
3077   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3078   bool LookPassAnd0 = false;
3079   bool LookPassAnd1 = false;
3080   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3081       std::swap(N0, N1);
3082   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3083       std::swap(N0, N1);
3084   if (N0.getOpcode() == ISD::AND) {
3085     if (!N0.getNode()->hasOneUse())
3086       return SDValue();
3087     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3088     if (!N01C || N01C->getZExtValue() != 0xFF00)
3089       return SDValue();
3090     N0 = N0.getOperand(0);
3091     LookPassAnd0 = true;
3092   }
3093
3094   if (N1.getOpcode() == ISD::AND) {
3095     if (!N1.getNode()->hasOneUse())
3096       return SDValue();
3097     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3098     if (!N11C || N11C->getZExtValue() != 0xFF)
3099       return SDValue();
3100     N1 = N1.getOperand(0);
3101     LookPassAnd1 = true;
3102   }
3103
3104   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3105     std::swap(N0, N1);
3106   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3107     return SDValue();
3108   if (!N0.getNode()->hasOneUse() ||
3109       !N1.getNode()->hasOneUse())
3110     return SDValue();
3111
3112   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3113   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3114   if (!N01C || !N11C)
3115     return SDValue();
3116   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3117     return SDValue();
3118
3119   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3120   SDValue N00 = N0->getOperand(0);
3121   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3122     if (!N00.getNode()->hasOneUse())
3123       return SDValue();
3124     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3125     if (!N001C || N001C->getZExtValue() != 0xFF)
3126       return SDValue();
3127     N00 = N00.getOperand(0);
3128     LookPassAnd0 = true;
3129   }
3130
3131   SDValue N10 = N1->getOperand(0);
3132   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3133     if (!N10.getNode()->hasOneUse())
3134       return SDValue();
3135     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3136     if (!N101C || N101C->getZExtValue() != 0xFF00)
3137       return SDValue();
3138     N10 = N10.getOperand(0);
3139     LookPassAnd1 = true;
3140   }
3141
3142   if (N00 != N10)
3143     return SDValue();
3144
3145   // Make sure everything beyond the low halfword gets set to zero since the SRL
3146   // 16 will clear the top bits.
3147   unsigned OpSizeInBits = VT.getSizeInBits();
3148   if (DemandHighBits && OpSizeInBits > 16) {
3149     // If the left-shift isn't masked out then the only way this is a bswap is
3150     // if all bits beyond the low 8 are 0. In that case the entire pattern
3151     // reduces to a left shift anyway: leave it for other parts of the combiner.
3152     if (!LookPassAnd0)
3153       return SDValue();
3154
3155     // However, if the right shift isn't masked out then it might be because
3156     // it's not needed. See if we can spot that too.
3157     if (!LookPassAnd1 &&
3158         !DAG.MaskedValueIsZero(
3159             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3160       return SDValue();
3161   }
3162
3163   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3164   if (OpSizeInBits > 16)
3165     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3166                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3167   return Res;
3168 }
3169
3170 /// Return true if the specified node is an element that makes up a 32-bit
3171 /// packed halfword byteswap.
3172 /// ((x & 0x000000ff) << 8) |
3173 /// ((x & 0x0000ff00) >> 8) |
3174 /// ((x & 0x00ff0000) << 8) |
3175 /// ((x & 0xff000000) >> 8)
3176 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3177   if (!N.getNode()->hasOneUse())
3178     return false;
3179
3180   unsigned Opc = N.getOpcode();
3181   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3182     return false;
3183
3184   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3185   if (!N1C)
3186     return false;
3187
3188   unsigned Num;
3189   switch (N1C->getZExtValue()) {
3190   default:
3191     return false;
3192   case 0xFF:       Num = 0; break;
3193   case 0xFF00:     Num = 1; break;
3194   case 0xFF0000:   Num = 2; break;
3195   case 0xFF000000: Num = 3; break;
3196   }
3197
3198   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3199   SDValue N0 = N.getOperand(0);
3200   if (Opc == ISD::AND) {
3201     if (Num == 0 || Num == 2) {
3202       // (x >> 8) & 0xff
3203       // (x >> 8) & 0xff0000
3204       if (N0.getOpcode() != ISD::SRL)
3205         return false;
3206       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3207       if (!C || C->getZExtValue() != 8)
3208         return false;
3209     } else {
3210       // (x << 8) & 0xff00
3211       // (x << 8) & 0xff000000
3212       if (N0.getOpcode() != ISD::SHL)
3213         return false;
3214       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3215       if (!C || C->getZExtValue() != 8)
3216         return false;
3217     }
3218   } else if (Opc == ISD::SHL) {
3219     // (x & 0xff) << 8
3220     // (x & 0xff0000) << 8
3221     if (Num != 0 && Num != 2)
3222       return false;
3223     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3224     if (!C || C->getZExtValue() != 8)
3225       return false;
3226   } else { // Opc == ISD::SRL
3227     // (x & 0xff00) >> 8
3228     // (x & 0xff000000) >> 8
3229     if (Num != 1 && Num != 3)
3230       return false;
3231     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3232     if (!C || C->getZExtValue() != 8)
3233       return false;
3234   }
3235
3236   if (Parts[Num])
3237     return false;
3238
3239   Parts[Num] = N0.getOperand(0).getNode();
3240   return true;
3241 }
3242
3243 /// Match a 32-bit packed halfword bswap. That is
3244 /// ((x & 0x000000ff) << 8) |
3245 /// ((x & 0x0000ff00) >> 8) |
3246 /// ((x & 0x00ff0000) << 8) |
3247 /// ((x & 0xff000000) >> 8)
3248 /// => (rotl (bswap x), 16)
3249 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3250   if (!LegalOperations)
3251     return SDValue();
3252
3253   EVT VT = N->getValueType(0);
3254   if (VT != MVT::i32)
3255     return SDValue();
3256   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3257     return SDValue();
3258
3259   // Look for either
3260   // (or (or (and), (and)), (or (and), (and)))
3261   // (or (or (or (and), (and)), (and)), (and))
3262   if (N0.getOpcode() != ISD::OR)
3263     return SDValue();
3264   SDValue N00 = N0.getOperand(0);
3265   SDValue N01 = N0.getOperand(1);
3266   SDNode *Parts[4] = {};
3267
3268   if (N1.getOpcode() == ISD::OR &&
3269       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3270     // (or (or (and), (and)), (or (and), (and)))
3271     SDValue N000 = N00.getOperand(0);
3272     if (!isBSwapHWordElement(N000, Parts))
3273       return SDValue();
3274
3275     SDValue N001 = N00.getOperand(1);
3276     if (!isBSwapHWordElement(N001, Parts))
3277       return SDValue();
3278     SDValue N010 = N01.getOperand(0);
3279     if (!isBSwapHWordElement(N010, Parts))
3280       return SDValue();
3281     SDValue N011 = N01.getOperand(1);
3282     if (!isBSwapHWordElement(N011, Parts))
3283       return SDValue();
3284   } else {
3285     // (or (or (or (and), (and)), (and)), (and))
3286     if (!isBSwapHWordElement(N1, Parts))
3287       return SDValue();
3288     if (!isBSwapHWordElement(N01, Parts))
3289       return SDValue();
3290     if (N00.getOpcode() != ISD::OR)
3291       return SDValue();
3292     SDValue N000 = N00.getOperand(0);
3293     if (!isBSwapHWordElement(N000, Parts))
3294       return SDValue();
3295     SDValue N001 = N00.getOperand(1);
3296     if (!isBSwapHWordElement(N001, Parts))
3297       return SDValue();
3298   }
3299
3300   // Make sure the parts are all coming from the same node.
3301   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3302     return SDValue();
3303
3304   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3305                               SDValue(Parts[0],0));
3306
3307   // Result of the bswap should be rotated by 16. If it's not legal, then
3308   // do  (x << 16) | (x >> 16).
3309   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3310   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3311     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3312   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3313     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3314   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3315                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3316                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3317 }
3318
3319 SDValue DAGCombiner::visitOR(SDNode *N) {
3320   SDValue N0 = N->getOperand(0);
3321   SDValue N1 = N->getOperand(1);
3322   SDValue LL, LR, RL, RR, CC0, CC1;
3323   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3324   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3325   EVT VT = N1.getValueType();
3326
3327   // fold vector ops
3328   if (VT.isVector()) {
3329     SDValue FoldedVOp = SimplifyVBinOp(N);
3330     if (FoldedVOp.getNode()) return FoldedVOp;
3331
3332     // fold (or x, 0) -> x, vector edition
3333     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3334       return N1;
3335     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3336       return N0;
3337
3338     // fold (or x, -1) -> -1, vector edition
3339     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3340       // do not return N0, because undef node may exist in N0
3341       return DAG.getConstant(
3342           APInt::getAllOnesValue(
3343               N0.getValueType().getScalarType().getSizeInBits()),
3344           N0.getValueType());
3345     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3346       // do not return N1, because undef node may exist in N1
3347       return DAG.getConstant(
3348           APInt::getAllOnesValue(
3349               N1.getValueType().getScalarType().getSizeInBits()),
3350           N1.getValueType());
3351
3352     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3353     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3354     // Do this only if the resulting shuffle is legal.
3355     if (isa<ShuffleVectorSDNode>(N0) &&
3356         isa<ShuffleVectorSDNode>(N1) &&
3357         // Avoid folding a node with illegal type.
3358         TLI.isTypeLegal(VT) &&
3359         N0->getOperand(1) == N1->getOperand(1) &&
3360         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3361       bool CanFold = true;
3362       unsigned NumElts = VT.getVectorNumElements();
3363       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3364       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3365       // We construct two shuffle masks:
3366       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3367       // and N1 as the second operand.
3368       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3369       // and N0 as the second operand.
3370       // We do this because OR is commutable and therefore there might be
3371       // two ways to fold this node into a shuffle.
3372       SmallVector<int,4> Mask1;
3373       SmallVector<int,4> Mask2;
3374
3375       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3376         int M0 = SV0->getMaskElt(i);
3377         int M1 = SV1->getMaskElt(i);
3378
3379         // Both shuffle indexes are undef. Propagate Undef.
3380         if (M0 < 0 && M1 < 0) {
3381           Mask1.push_back(M0);
3382           Mask2.push_back(M0);
3383           continue;
3384         }
3385
3386         if (M0 < 0 || M1 < 0 ||
3387             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3388             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3389           CanFold = false;
3390           break;
3391         }
3392
3393         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3394         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3395       }
3396
3397       if (CanFold) {
3398         // Fold this sequence only if the resulting shuffle is 'legal'.
3399         if (TLI.isShuffleMaskLegal(Mask1, VT))
3400           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3401                                       N1->getOperand(0), &Mask1[0]);
3402         if (TLI.isShuffleMaskLegal(Mask2, VT))
3403           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3404                                       N0->getOperand(0), &Mask2[0]);
3405       }
3406     }
3407   }
3408
3409   // fold (or x, undef) -> -1
3410   if (!LegalOperations &&
3411       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3412     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3413     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3414   }
3415   // fold (or c1, c2) -> c1|c2
3416   if (N0C && N1C)
3417     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3418   // canonicalize constant to RHS
3419   if (N0C && !N1C)
3420     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3421   // fold (or x, 0) -> x
3422   if (N1C && N1C->isNullValue())
3423     return N0;
3424   // fold (or x, -1) -> -1
3425   if (N1C && N1C->isAllOnesValue())
3426     return N1;
3427   // fold (or x, c) -> c iff (x & ~c) == 0
3428   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3429     return N1;
3430
3431   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3432   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3433   if (BSwap.getNode())
3434     return BSwap;
3435   BSwap = MatchBSwapHWordLow(N, N0, N1);
3436   if (BSwap.getNode())
3437     return BSwap;
3438
3439   // reassociate or
3440   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3441   if (ROR.getNode())
3442     return ROR;
3443   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3444   // iff (c1 & c2) == 0.
3445   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3446              isa<ConstantSDNode>(N0.getOperand(1))) {
3447     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3448     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3449       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3450       if (!COR.getNode())
3451         return SDValue();
3452       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3453                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3454                                      N0.getOperand(0), N1), COR);
3455     }
3456   }
3457   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3458   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3459     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3460     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3461
3462     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3463         LL.getValueType().isInteger()) {
3464       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3465       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3466       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3467           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3468         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3469                                      LR.getValueType(), LL, RL);
3470         AddToWorklist(ORNode.getNode());
3471         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3472       }
3473       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3474       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3475       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3476           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3477         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3478                                       LR.getValueType(), LL, RL);
3479         AddToWorklist(ANDNode.getNode());
3480         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3481       }
3482     }
3483     // canonicalize equivalent to ll == rl
3484     if (LL == RR && LR == RL) {
3485       Op1 = ISD::getSetCCSwappedOperands(Op1);
3486       std::swap(RL, RR);
3487     }
3488     if (LL == RL && LR == RR) {
3489       bool isInteger = LL.getValueType().isInteger();
3490       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3491       if (Result != ISD::SETCC_INVALID &&
3492           (!LegalOperations ||
3493            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3494             TLI.isOperationLegal(ISD::SETCC,
3495               getSetCCResultType(N0.getValueType())))))
3496         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3497                             LL, LR, Result);
3498     }
3499   }
3500
3501   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3502   if (N0.getOpcode() == N1.getOpcode()) {
3503     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3504     if (Tmp.getNode()) return Tmp;
3505   }
3506
3507   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3508   if (N0.getOpcode() == ISD::AND &&
3509       N1.getOpcode() == ISD::AND &&
3510       N0.getOperand(1).getOpcode() == ISD::Constant &&
3511       N1.getOperand(1).getOpcode() == ISD::Constant &&
3512       // Don't increase # computations.
3513       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3514     // We can only do this xform if we know that bits from X that are set in C2
3515     // but not in C1 are already zero.  Likewise for Y.
3516     const APInt &LHSMask =
3517       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3518     const APInt &RHSMask =
3519       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3520
3521     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3522         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3523       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3524                               N0.getOperand(0), N1.getOperand(0));
3525       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3526                          DAG.getConstant(LHSMask | RHSMask, VT));
3527     }
3528   }
3529
3530   // See if this is some rotate idiom.
3531   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3532     return SDValue(Rot, 0);
3533
3534   // Simplify the operands using demanded-bits information.
3535   if (!VT.isVector() &&
3536       SimplifyDemandedBits(SDValue(N, 0)))
3537     return SDValue(N, 0);
3538
3539   return SDValue();
3540 }
3541
3542 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3543 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3544   if (Op.getOpcode() == ISD::AND) {
3545     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3546       Mask = Op.getOperand(1);
3547       Op = Op.getOperand(0);
3548     } else {
3549       return false;
3550     }
3551   }
3552
3553   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3554     Shift = Op;
3555     return true;
3556   }
3557
3558   return false;
3559 }
3560
3561 // Return true if we can prove that, whenever Neg and Pos are both in the
3562 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3563 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3564 //
3565 //     (or (shift1 X, Neg), (shift2 X, Pos))
3566 //
3567 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3568 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3569 // to consider shift amounts with defined behavior.
3570 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3571   // If OpSize is a power of 2 then:
3572   //
3573   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3574   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3575   //
3576   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3577   // for the stronger condition:
3578   //
3579   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3580   //
3581   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3582   // we can just replace Neg with Neg' for the rest of the function.
3583   //
3584   // In other cases we check for the even stronger condition:
3585   //
3586   //     Neg == OpSize - Pos                                    [B]
3587   //
3588   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3589   // behavior if Pos == 0 (and consequently Neg == OpSize).
3590   //
3591   // We could actually use [A] whenever OpSize is a power of 2, but the
3592   // only extra cases that it would match are those uninteresting ones
3593   // where Neg and Pos are never in range at the same time.  E.g. for
3594   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3595   // as well as (sub 32, Pos), but:
3596   //
3597   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3598   //
3599   // always invokes undefined behavior for 32-bit X.
3600   //
3601   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3602   unsigned MaskLoBits = 0;
3603   if (Neg.getOpcode() == ISD::AND &&
3604       isPowerOf2_64(OpSize) &&
3605       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3606       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3607     Neg = Neg.getOperand(0);
3608     MaskLoBits = Log2_64(OpSize);
3609   }
3610
3611   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3612   if (Neg.getOpcode() != ISD::SUB)
3613     return 0;
3614   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3615   if (!NegC)
3616     return 0;
3617   SDValue NegOp1 = Neg.getOperand(1);
3618
3619   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3620   // Pos'.  The truncation is redundant for the purpose of the equality.
3621   if (MaskLoBits &&
3622       Pos.getOpcode() == ISD::AND &&
3623       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3624       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3625     Pos = Pos.getOperand(0);
3626
3627   // The condition we need is now:
3628   //
3629   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3630   //
3631   // If NegOp1 == Pos then we need:
3632   //
3633   //              OpSize & Mask == NegC & Mask
3634   //
3635   // (because "x & Mask" is a truncation and distributes through subtraction).
3636   APInt Width;
3637   if (Pos == NegOp1)
3638     Width = NegC->getAPIntValue();
3639   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3640   // Then the condition we want to prove becomes:
3641   //
3642   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3643   //
3644   // which, again because "x & Mask" is a truncation, becomes:
3645   //
3646   //                NegC & Mask == (OpSize - PosC) & Mask
3647   //              OpSize & Mask == (NegC + PosC) & Mask
3648   else if (Pos.getOpcode() == ISD::ADD &&
3649            Pos.getOperand(0) == NegOp1 &&
3650            Pos.getOperand(1).getOpcode() == ISD::Constant)
3651     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3652              NegC->getAPIntValue());
3653   else
3654     return false;
3655
3656   // Now we just need to check that OpSize & Mask == Width & Mask.
3657   if (MaskLoBits)
3658     // Opsize & Mask is 0 since Mask is Opsize - 1.
3659     return Width.getLoBits(MaskLoBits) == 0;
3660   return Width == OpSize;
3661 }
3662
3663 // A subroutine of MatchRotate used once we have found an OR of two opposite
3664 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3665 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3666 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3667 // Neg with outer conversions stripped away.
3668 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3669                                        SDValue Neg, SDValue InnerPos,
3670                                        SDValue InnerNeg, unsigned PosOpcode,
3671                                        unsigned NegOpcode, SDLoc DL) {
3672   // fold (or (shl x, (*ext y)),
3673   //          (srl x, (*ext (sub 32, y)))) ->
3674   //   (rotl x, y) or (rotr x, (sub 32, y))
3675   //
3676   // fold (or (shl x, (*ext (sub 32, y))),
3677   //          (srl x, (*ext y))) ->
3678   //   (rotr x, y) or (rotl x, (sub 32, y))
3679   EVT VT = Shifted.getValueType();
3680   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3681     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3682     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3683                        HasPos ? Pos : Neg).getNode();
3684   }
3685
3686   return nullptr;
3687 }
3688
3689 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3690 // idioms for rotate, and if the target supports rotation instructions, generate
3691 // a rot[lr].
3692 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3693   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3694   EVT VT = LHS.getValueType();
3695   if (!TLI.isTypeLegal(VT)) return nullptr;
3696
3697   // The target must have at least one rotate flavor.
3698   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3699   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3700   if (!HasROTL && !HasROTR) return nullptr;
3701
3702   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3703   SDValue LHSShift;   // The shift.
3704   SDValue LHSMask;    // AND value if any.
3705   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3706     return nullptr; // Not part of a rotate.
3707
3708   SDValue RHSShift;   // The shift.
3709   SDValue RHSMask;    // AND value if any.
3710   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3711     return nullptr; // Not part of a rotate.
3712
3713   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3714     return nullptr;   // Not shifting the same value.
3715
3716   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3717     return nullptr;   // Shifts must disagree.
3718
3719   // Canonicalize shl to left side in a shl/srl pair.
3720   if (RHSShift.getOpcode() == ISD::SHL) {
3721     std::swap(LHS, RHS);
3722     std::swap(LHSShift, RHSShift);
3723     std::swap(LHSMask , RHSMask );
3724   }
3725
3726   unsigned OpSizeInBits = VT.getSizeInBits();
3727   SDValue LHSShiftArg = LHSShift.getOperand(0);
3728   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3729   SDValue RHSShiftArg = RHSShift.getOperand(0);
3730   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3731
3732   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3733   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3734   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3735       RHSShiftAmt.getOpcode() == ISD::Constant) {
3736     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3737     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3738     if ((LShVal + RShVal) != OpSizeInBits)
3739       return nullptr;
3740
3741     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3742                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3743
3744     // If there is an AND of either shifted operand, apply it to the result.
3745     if (LHSMask.getNode() || RHSMask.getNode()) {
3746       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3747
3748       if (LHSMask.getNode()) {
3749         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3750         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3751       }
3752       if (RHSMask.getNode()) {
3753         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3754         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3755       }
3756
3757       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3758     }
3759
3760     return Rot.getNode();
3761   }
3762
3763   // If there is a mask here, and we have a variable shift, we can't be sure
3764   // that we're masking out the right stuff.
3765   if (LHSMask.getNode() || RHSMask.getNode())
3766     return nullptr;
3767
3768   // If the shift amount is sign/zext/any-extended just peel it off.
3769   SDValue LExtOp0 = LHSShiftAmt;
3770   SDValue RExtOp0 = RHSShiftAmt;
3771   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3772        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3773        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3774        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3775       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3776        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3777        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3778        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3779     LExtOp0 = LHSShiftAmt.getOperand(0);
3780     RExtOp0 = RHSShiftAmt.getOperand(0);
3781   }
3782
3783   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3784                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3785   if (TryL)
3786     return TryL;
3787
3788   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3789                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3790   if (TryR)
3791     return TryR;
3792
3793   return nullptr;
3794 }
3795
3796 SDValue DAGCombiner::visitXOR(SDNode *N) {
3797   SDValue N0 = N->getOperand(0);
3798   SDValue N1 = N->getOperand(1);
3799   SDValue LHS, RHS, CC;
3800   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3801   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3802   EVT VT = N0.getValueType();
3803
3804   // fold vector ops
3805   if (VT.isVector()) {
3806     SDValue FoldedVOp = SimplifyVBinOp(N);
3807     if (FoldedVOp.getNode()) return FoldedVOp;
3808
3809     // fold (xor x, 0) -> x, vector edition
3810     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3811       return N1;
3812     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3813       return N0;
3814   }
3815
3816   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3817   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3818     return DAG.getConstant(0, VT);
3819   // fold (xor x, undef) -> undef
3820   if (N0.getOpcode() == ISD::UNDEF)
3821     return N0;
3822   if (N1.getOpcode() == ISD::UNDEF)
3823     return N1;
3824   // fold (xor c1, c2) -> c1^c2
3825   if (N0C && N1C)
3826     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3827   // canonicalize constant to RHS
3828   if (N0C && !N1C)
3829     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3830   // fold (xor x, 0) -> x
3831   if (N1C && N1C->isNullValue())
3832     return N0;
3833   // reassociate xor
3834   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3835   if (RXOR.getNode())
3836     return RXOR;
3837
3838   // fold !(x cc y) -> (x !cc y)
3839   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3840     bool isInt = LHS.getValueType().isInteger();
3841     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3842                                                isInt);
3843
3844     if (!LegalOperations ||
3845         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3846       switch (N0.getOpcode()) {
3847       default:
3848         llvm_unreachable("Unhandled SetCC Equivalent!");
3849       case ISD::SETCC:
3850         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3851       case ISD::SELECT_CC:
3852         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3853                                N0.getOperand(3), NotCC);
3854       }
3855     }
3856   }
3857
3858   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3859   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3860       N0.getNode()->hasOneUse() &&
3861       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3862     SDValue V = N0.getOperand(0);
3863     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3864                     DAG.getConstant(1, V.getValueType()));
3865     AddToWorklist(V.getNode());
3866     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3867   }
3868
3869   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3870   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3871       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3872     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3873     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3874       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3875       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3876       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3877       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3878       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3879     }
3880   }
3881   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3882   if (N1C && N1C->isAllOnesValue() &&
3883       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3884     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3885     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3886       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3887       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3888       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3889       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3890       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3891     }
3892   }
3893   // fold (xor (and x, y), y) -> (and (not x), y)
3894   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3895       N0->getOperand(1) == N1) {
3896     SDValue X = N0->getOperand(0);
3897     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3898     AddToWorklist(NotX.getNode());
3899     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3900   }
3901   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3902   if (N1C && N0.getOpcode() == ISD::XOR) {
3903     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3904     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3905     if (N00C)
3906       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3907                          DAG.getConstant(N1C->getAPIntValue() ^
3908                                          N00C->getAPIntValue(), VT));
3909     if (N01C)
3910       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3911                          DAG.getConstant(N1C->getAPIntValue() ^
3912                                          N01C->getAPIntValue(), VT));
3913   }
3914   // fold (xor x, x) -> 0
3915   if (N0 == N1)
3916     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3917
3918   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3919   if (N0.getOpcode() == N1.getOpcode()) {
3920     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3921     if (Tmp.getNode()) return Tmp;
3922   }
3923
3924   // Simplify the expression using non-local knowledge.
3925   if (!VT.isVector() &&
3926       SimplifyDemandedBits(SDValue(N, 0)))
3927     return SDValue(N, 0);
3928
3929   return SDValue();
3930 }
3931
3932 /// Handle transforms common to the three shifts, when the shift amount is a
3933 /// constant.
3934 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3935   // We can't and shouldn't fold opaque constants.
3936   if (Amt->isOpaque())
3937     return SDValue();
3938
3939   SDNode *LHS = N->getOperand(0).getNode();
3940   if (!LHS->hasOneUse()) return SDValue();
3941
3942   // We want to pull some binops through shifts, so that we have (and (shift))
3943   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3944   // thing happens with address calculations, so it's important to canonicalize
3945   // it.
3946   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3947
3948   switch (LHS->getOpcode()) {
3949   default: return SDValue();
3950   case ISD::OR:
3951   case ISD::XOR:
3952     HighBitSet = false; // We can only transform sra if the high bit is clear.
3953     break;
3954   case ISD::AND:
3955     HighBitSet = true;  // We can only transform sra if the high bit is set.
3956     break;
3957   case ISD::ADD:
3958     if (N->getOpcode() != ISD::SHL)
3959       return SDValue(); // only shl(add) not sr[al](add).
3960     HighBitSet = false; // We can only transform sra if the high bit is clear.
3961     break;
3962   }
3963
3964   // We require the RHS of the binop to be a constant and not opaque as well.
3965   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3966   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3967
3968   // FIXME: disable this unless the input to the binop is a shift by a constant.
3969   // If it is not a shift, it pessimizes some common cases like:
3970   //
3971   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3972   //    int bar(int *X, int i) { return X[i & 255]; }
3973   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3974   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3975        BinOpLHSVal->getOpcode() != ISD::SRA &&
3976        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3977       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3978     return SDValue();
3979
3980   EVT VT = N->getValueType(0);
3981
3982   // If this is a signed shift right, and the high bit is modified by the
3983   // logical operation, do not perform the transformation. The highBitSet
3984   // boolean indicates the value of the high bit of the constant which would
3985   // cause it to be modified for this operation.
3986   if (N->getOpcode() == ISD::SRA) {
3987     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3988     if (BinOpRHSSignSet != HighBitSet)
3989       return SDValue();
3990   }
3991
3992   if (!TLI.isDesirableToCommuteWithShift(LHS))
3993     return SDValue();
3994
3995   // Fold the constants, shifting the binop RHS by the shift amount.
3996   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3997                                N->getValueType(0),
3998                                LHS->getOperand(1), N->getOperand(1));
3999   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
4000
4001   // Create the new shift.
4002   SDValue NewShift = DAG.getNode(N->getOpcode(),
4003                                  SDLoc(LHS->getOperand(0)),
4004                                  VT, LHS->getOperand(0), N->getOperand(1));
4005
4006   // Create the new binop.
4007   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4008 }
4009
4010 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4011   assert(N->getOpcode() == ISD::TRUNCATE);
4012   assert(N->getOperand(0).getOpcode() == ISD::AND);
4013
4014   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4015   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4016     SDValue N01 = N->getOperand(0).getOperand(1);
4017
4018     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4019       EVT TruncVT = N->getValueType(0);
4020       SDValue N00 = N->getOperand(0).getOperand(0);
4021       APInt TruncC = N01C->getAPIntValue();
4022       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4023
4024       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4025                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4026                          DAG.getConstant(TruncC, TruncVT));
4027     }
4028   }
4029
4030   return SDValue();
4031 }
4032
4033 SDValue DAGCombiner::visitRotate(SDNode *N) {
4034   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4035   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4036       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4037     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4038     if (NewOp1.getNode())
4039       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4040                          N->getOperand(0), NewOp1);
4041   }
4042   return SDValue();
4043 }
4044
4045 SDValue DAGCombiner::visitSHL(SDNode *N) {
4046   SDValue N0 = N->getOperand(0);
4047   SDValue N1 = N->getOperand(1);
4048   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4049   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4050   EVT VT = N0.getValueType();
4051   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4052
4053   // fold vector ops
4054   if (VT.isVector()) {
4055     SDValue FoldedVOp = SimplifyVBinOp(N);
4056     if (FoldedVOp.getNode()) return FoldedVOp;
4057
4058     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4059     // If setcc produces all-one true value then:
4060     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4061     if (N1CV && N1CV->isConstant()) {
4062       if (N0.getOpcode() == ISD::AND) {
4063         SDValue N00 = N0->getOperand(0);
4064         SDValue N01 = N0->getOperand(1);
4065         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4066
4067         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4068             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4069                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4070           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4071           if (C.getNode())
4072             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4073         }
4074       } else {
4075         N1C = isConstOrConstSplat(N1);
4076       }
4077     }
4078   }
4079
4080   // fold (shl c1, c2) -> c1<<c2
4081   if (N0C && N1C)
4082     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4083   // fold (shl 0, x) -> 0
4084   if (N0C && N0C->isNullValue())
4085     return N0;
4086   // fold (shl x, c >= size(x)) -> undef
4087   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4088     return DAG.getUNDEF(VT);
4089   // fold (shl x, 0) -> x
4090   if (N1C && N1C->isNullValue())
4091     return N0;
4092   // fold (shl undef, x) -> 0
4093   if (N0.getOpcode() == ISD::UNDEF)
4094     return DAG.getConstant(0, VT);
4095   // if (shl x, c) is known to be zero, return 0
4096   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4097                             APInt::getAllOnesValue(OpSizeInBits)))
4098     return DAG.getConstant(0, VT);
4099   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4100   if (N1.getOpcode() == ISD::TRUNCATE &&
4101       N1.getOperand(0).getOpcode() == ISD::AND) {
4102     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4103     if (NewOp1.getNode())
4104       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4105   }
4106
4107   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4108     return SDValue(N, 0);
4109
4110   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4111   if (N1C && N0.getOpcode() == ISD::SHL) {
4112     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4113       uint64_t c1 = N0C1->getZExtValue();
4114       uint64_t c2 = N1C->getZExtValue();
4115       if (c1 + c2 >= OpSizeInBits)
4116         return DAG.getConstant(0, VT);
4117       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4118                          DAG.getConstant(c1 + c2, N1.getValueType()));
4119     }
4120   }
4121
4122   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4123   // For this to be valid, the second form must not preserve any of the bits
4124   // that are shifted out by the inner shift in the first form.  This means
4125   // the outer shift size must be >= the number of bits added by the ext.
4126   // As a corollary, we don't care what kind of ext it is.
4127   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4128               N0.getOpcode() == ISD::ANY_EXTEND ||
4129               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4130       N0.getOperand(0).getOpcode() == ISD::SHL) {
4131     SDValue N0Op0 = N0.getOperand(0);
4132     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4133       uint64_t c1 = N0Op0C1->getZExtValue();
4134       uint64_t c2 = N1C->getZExtValue();
4135       EVT InnerShiftVT = N0Op0.getValueType();
4136       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4137       if (c2 >= OpSizeInBits - InnerShiftSize) {
4138         if (c1 + c2 >= OpSizeInBits)
4139           return DAG.getConstant(0, VT);
4140         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4141                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4142                                        N0Op0->getOperand(0)),
4143                            DAG.getConstant(c1 + c2, N1.getValueType()));
4144       }
4145     }
4146   }
4147
4148   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4149   // Only fold this if the inner zext has no other uses to avoid increasing
4150   // the total number of instructions.
4151   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4152       N0.getOperand(0).getOpcode() == ISD::SRL) {
4153     SDValue N0Op0 = N0.getOperand(0);
4154     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4155       uint64_t c1 = N0Op0C1->getZExtValue();
4156       if (c1 < VT.getScalarSizeInBits()) {
4157         uint64_t c2 = N1C->getZExtValue();
4158         if (c1 == c2) {
4159           SDValue NewOp0 = N0.getOperand(0);
4160           EVT CountVT = NewOp0.getOperand(1).getValueType();
4161           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4162                                        NewOp0, DAG.getConstant(c2, CountVT));
4163           AddToWorklist(NewSHL.getNode());
4164           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4165         }
4166       }
4167     }
4168   }
4169
4170   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4171   //                               (and (srl x, (sub c1, c2), MASK)
4172   // Only fold this if the inner shift has no other uses -- if it does, folding
4173   // this will increase the total number of instructions.
4174   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4175     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4176       uint64_t c1 = N0C1->getZExtValue();
4177       if (c1 < OpSizeInBits) {
4178         uint64_t c2 = N1C->getZExtValue();
4179         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4180         SDValue Shift;
4181         if (c2 > c1) {
4182           Mask = Mask.shl(c2 - c1);
4183           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4184                               DAG.getConstant(c2 - c1, N1.getValueType()));
4185         } else {
4186           Mask = Mask.lshr(c1 - c2);
4187           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4188                               DAG.getConstant(c1 - c2, N1.getValueType()));
4189         }
4190         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4191                            DAG.getConstant(Mask, VT));
4192       }
4193     }
4194   }
4195   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4196   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4197     unsigned BitSize = VT.getScalarSizeInBits();
4198     SDValue HiBitsMask =
4199       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4200                                             BitSize - N1C->getZExtValue()), VT);
4201     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4202                        HiBitsMask);
4203   }
4204
4205   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4206   // Variant of version done on multiply, except mul by a power of 2 is turned
4207   // into a shift.
4208   APInt Val;
4209   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4210       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4211        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4212     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4213     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4214     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4215   }
4216
4217   if (N1C) {
4218     SDValue NewSHL = visitShiftByConstant(N, N1C);
4219     if (NewSHL.getNode())
4220       return NewSHL;
4221   }
4222
4223   return SDValue();
4224 }
4225
4226 SDValue DAGCombiner::visitSRA(SDNode *N) {
4227   SDValue N0 = N->getOperand(0);
4228   SDValue N1 = N->getOperand(1);
4229   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4230   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4231   EVT VT = N0.getValueType();
4232   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4233
4234   // fold vector ops
4235   if (VT.isVector()) {
4236     SDValue FoldedVOp = SimplifyVBinOp(N);
4237     if (FoldedVOp.getNode()) return FoldedVOp;
4238
4239     N1C = isConstOrConstSplat(N1);
4240   }
4241
4242   // fold (sra c1, c2) -> (sra c1, c2)
4243   if (N0C && N1C)
4244     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4245   // fold (sra 0, x) -> 0
4246   if (N0C && N0C->isNullValue())
4247     return N0;
4248   // fold (sra -1, x) -> -1
4249   if (N0C && N0C->isAllOnesValue())
4250     return N0;
4251   // fold (sra x, (setge c, size(x))) -> undef
4252   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4253     return DAG.getUNDEF(VT);
4254   // fold (sra x, 0) -> x
4255   if (N1C && N1C->isNullValue())
4256     return N0;
4257   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4258   // sext_inreg.
4259   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4260     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4261     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4262     if (VT.isVector())
4263       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4264                                ExtVT, VT.getVectorNumElements());
4265     if ((!LegalOperations ||
4266          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4267       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4268                          N0.getOperand(0), DAG.getValueType(ExtVT));
4269   }
4270
4271   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4272   if (N1C && N0.getOpcode() == ISD::SRA) {
4273     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4274       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4275       if (Sum >= OpSizeInBits)
4276         Sum = OpSizeInBits - 1;
4277       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4278                          DAG.getConstant(Sum, N1.getValueType()));
4279     }
4280   }
4281
4282   // fold (sra (shl X, m), (sub result_size, n))
4283   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4284   // result_size - n != m.
4285   // If truncate is free for the target sext(shl) is likely to result in better
4286   // code.
4287   if (N0.getOpcode() == ISD::SHL && N1C) {
4288     // Get the two constanst of the shifts, CN0 = m, CN = n.
4289     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4290     if (N01C) {
4291       LLVMContext &Ctx = *DAG.getContext();
4292       // Determine what the truncate's result bitsize and type would be.
4293       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4294
4295       if (VT.isVector())
4296         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4297
4298       // Determine the residual right-shift amount.
4299       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4300
4301       // If the shift is not a no-op (in which case this should be just a sign
4302       // extend already), the truncated to type is legal, sign_extend is legal
4303       // on that type, and the truncate to that type is both legal and free,
4304       // perform the transform.
4305       if ((ShiftAmt > 0) &&
4306           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4307           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4308           TLI.isTruncateFree(VT, TruncVT)) {
4309
4310           SDValue Amt = DAG.getConstant(ShiftAmt,
4311               getShiftAmountTy(N0.getOperand(0).getValueType()));
4312           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4313                                       N0.getOperand(0), Amt);
4314           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4315                                       Shift);
4316           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4317                              N->getValueType(0), Trunc);
4318       }
4319     }
4320   }
4321
4322   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4323   if (N1.getOpcode() == ISD::TRUNCATE &&
4324       N1.getOperand(0).getOpcode() == ISD::AND) {
4325     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4326     if (NewOp1.getNode())
4327       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4328   }
4329
4330   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4331   //      if c1 is equal to the number of bits the trunc removes
4332   if (N0.getOpcode() == ISD::TRUNCATE &&
4333       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4334        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4335       N0.getOperand(0).hasOneUse() &&
4336       N0.getOperand(0).getOperand(1).hasOneUse() &&
4337       N1C) {
4338     SDValue N0Op0 = N0.getOperand(0);
4339     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4340       unsigned LargeShiftVal = LargeShift->getZExtValue();
4341       EVT LargeVT = N0Op0.getValueType();
4342
4343       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4344         SDValue Amt =
4345           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4346                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4347         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4348                                   N0Op0.getOperand(0), Amt);
4349         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4350       }
4351     }
4352   }
4353
4354   // Simplify, based on bits shifted out of the LHS.
4355   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4356     return SDValue(N, 0);
4357
4358
4359   // If the sign bit is known to be zero, switch this to a SRL.
4360   if (DAG.SignBitIsZero(N0))
4361     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4362
4363   if (N1C) {
4364     SDValue NewSRA = visitShiftByConstant(N, N1C);
4365     if (NewSRA.getNode())
4366       return NewSRA;
4367   }
4368
4369   return SDValue();
4370 }
4371
4372 SDValue DAGCombiner::visitSRL(SDNode *N) {
4373   SDValue N0 = N->getOperand(0);
4374   SDValue N1 = N->getOperand(1);
4375   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4376   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4377   EVT VT = N0.getValueType();
4378   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4379
4380   // fold vector ops
4381   if (VT.isVector()) {
4382     SDValue FoldedVOp = SimplifyVBinOp(N);
4383     if (FoldedVOp.getNode()) return FoldedVOp;
4384
4385     N1C = isConstOrConstSplat(N1);
4386   }
4387
4388   // fold (srl c1, c2) -> c1 >>u c2
4389   if (N0C && N1C)
4390     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4391   // fold (srl 0, x) -> 0
4392   if (N0C && N0C->isNullValue())
4393     return N0;
4394   // fold (srl x, c >= size(x)) -> undef
4395   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4396     return DAG.getUNDEF(VT);
4397   // fold (srl x, 0) -> x
4398   if (N1C && N1C->isNullValue())
4399     return N0;
4400   // if (srl x, c) is known to be zero, return 0
4401   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4402                                    APInt::getAllOnesValue(OpSizeInBits)))
4403     return DAG.getConstant(0, VT);
4404
4405   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4406   if (N1C && N0.getOpcode() == ISD::SRL) {
4407     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4408       uint64_t c1 = N01C->getZExtValue();
4409       uint64_t c2 = N1C->getZExtValue();
4410       if (c1 + c2 >= OpSizeInBits)
4411         return DAG.getConstant(0, VT);
4412       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4413                          DAG.getConstant(c1 + c2, N1.getValueType()));
4414     }
4415   }
4416
4417   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4418   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4419       N0.getOperand(0).getOpcode() == ISD::SRL &&
4420       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4421     uint64_t c1 =
4422       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4423     uint64_t c2 = N1C->getZExtValue();
4424     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4425     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4426     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4427     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4428     if (c1 + OpSizeInBits == InnerShiftSize) {
4429       if (c1 + c2 >= InnerShiftSize)
4430         return DAG.getConstant(0, VT);
4431       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4432                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4433                                      N0.getOperand(0)->getOperand(0),
4434                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4435     }
4436   }
4437
4438   // fold (srl (shl x, c), c) -> (and x, cst2)
4439   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4440     unsigned BitSize = N0.getScalarValueSizeInBits();
4441     if (BitSize <= 64) {
4442       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4443       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4444                          DAG.getConstant(~0ULL >> ShAmt, VT));
4445     }
4446   }
4447
4448   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4449   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4450     // Shifting in all undef bits?
4451     EVT SmallVT = N0.getOperand(0).getValueType();
4452     unsigned BitSize = SmallVT.getScalarSizeInBits();
4453     if (N1C->getZExtValue() >= BitSize)
4454       return DAG.getUNDEF(VT);
4455
4456     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4457       uint64_t ShiftAmt = N1C->getZExtValue();
4458       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4459                                        N0.getOperand(0),
4460                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4461       AddToWorklist(SmallShift.getNode());
4462       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4463       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4464                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4465                          DAG.getConstant(Mask, VT));
4466     }
4467   }
4468
4469   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4470   // bit, which is unmodified by sra.
4471   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4472     if (N0.getOpcode() == ISD::SRA)
4473       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4474   }
4475
4476   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4477   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4478       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4479     APInt KnownZero, KnownOne;
4480     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4481
4482     // If any of the input bits are KnownOne, then the input couldn't be all
4483     // zeros, thus the result of the srl will always be zero.
4484     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4485
4486     // If all of the bits input the to ctlz node are known to be zero, then
4487     // the result of the ctlz is "32" and the result of the shift is one.
4488     APInt UnknownBits = ~KnownZero;
4489     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4490
4491     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4492     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4493       // Okay, we know that only that the single bit specified by UnknownBits
4494       // could be set on input to the CTLZ node. If this bit is set, the SRL
4495       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4496       // to an SRL/XOR pair, which is likely to simplify more.
4497       unsigned ShAmt = UnknownBits.countTrailingZeros();
4498       SDValue Op = N0.getOperand(0);
4499
4500       if (ShAmt) {
4501         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4502                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4503         AddToWorklist(Op.getNode());
4504       }
4505
4506       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4507                          Op, DAG.getConstant(1, VT));
4508     }
4509   }
4510
4511   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4512   if (N1.getOpcode() == ISD::TRUNCATE &&
4513       N1.getOperand(0).getOpcode() == ISD::AND) {
4514     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4515     if (NewOp1.getNode())
4516       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4517   }
4518
4519   // fold operands of srl based on knowledge that the low bits are not
4520   // demanded.
4521   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4522     return SDValue(N, 0);
4523
4524   if (N1C) {
4525     SDValue NewSRL = visitShiftByConstant(N, N1C);
4526     if (NewSRL.getNode())
4527       return NewSRL;
4528   }
4529
4530   // Attempt to convert a srl of a load into a narrower zero-extending load.
4531   SDValue NarrowLoad = ReduceLoadWidth(N);
4532   if (NarrowLoad.getNode())
4533     return NarrowLoad;
4534
4535   // Here is a common situation. We want to optimize:
4536   //
4537   //   %a = ...
4538   //   %b = and i32 %a, 2
4539   //   %c = srl i32 %b, 1
4540   //   brcond i32 %c ...
4541   //
4542   // into
4543   //
4544   //   %a = ...
4545   //   %b = and %a, 2
4546   //   %c = setcc eq %b, 0
4547   //   brcond %c ...
4548   //
4549   // However when after the source operand of SRL is optimized into AND, the SRL
4550   // itself may not be optimized further. Look for it and add the BRCOND into
4551   // the worklist.
4552   if (N->hasOneUse()) {
4553     SDNode *Use = *N->use_begin();
4554     if (Use->getOpcode() == ISD::BRCOND)
4555       AddToWorklist(Use);
4556     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4557       // Also look pass the truncate.
4558       Use = *Use->use_begin();
4559       if (Use->getOpcode() == ISD::BRCOND)
4560         AddToWorklist(Use);
4561     }
4562   }
4563
4564   return SDValue();
4565 }
4566
4567 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4568   SDValue N0 = N->getOperand(0);
4569   EVT VT = N->getValueType(0);
4570
4571   // fold (ctlz c1) -> c2
4572   if (isa<ConstantSDNode>(N0))
4573     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4574   return SDValue();
4575 }
4576
4577 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4578   SDValue N0 = N->getOperand(0);
4579   EVT VT = N->getValueType(0);
4580
4581   // fold (ctlz_zero_undef c1) -> c2
4582   if (isa<ConstantSDNode>(N0))
4583     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4584   return SDValue();
4585 }
4586
4587 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4588   SDValue N0 = N->getOperand(0);
4589   EVT VT = N->getValueType(0);
4590
4591   // fold (cttz c1) -> c2
4592   if (isa<ConstantSDNode>(N0))
4593     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4594   return SDValue();
4595 }
4596
4597 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4598   SDValue N0 = N->getOperand(0);
4599   EVT VT = N->getValueType(0);
4600
4601   // fold (cttz_zero_undef c1) -> c2
4602   if (isa<ConstantSDNode>(N0))
4603     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4604   return SDValue();
4605 }
4606
4607 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4608   SDValue N0 = N->getOperand(0);
4609   EVT VT = N->getValueType(0);
4610
4611   // fold (ctpop c1) -> c2
4612   if (isa<ConstantSDNode>(N0))
4613     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4614   return SDValue();
4615 }
4616
4617 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4618   SDValue N0 = N->getOperand(0);
4619   SDValue N1 = N->getOperand(1);
4620   SDValue N2 = N->getOperand(2);
4621   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4622   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4623   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4624   EVT VT = N->getValueType(0);
4625   EVT VT0 = N0.getValueType();
4626
4627   // fold (select C, X, X) -> X
4628   if (N1 == N2)
4629     return N1;
4630   // fold (select true, X, Y) -> X
4631   if (N0C && !N0C->isNullValue())
4632     return N1;
4633   // fold (select false, X, Y) -> Y
4634   if (N0C && N0C->isNullValue())
4635     return N2;
4636   // fold (select C, 1, X) -> (or C, X)
4637   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4638     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4639   // fold (select C, 0, 1) -> (xor C, 1)
4640   // We can't do this reliably if integer based booleans have different contents
4641   // to floating point based booleans. This is because we can't tell whether we
4642   // have an integer-based boolean or a floating-point-based boolean unless we
4643   // can find the SETCC that produced it and inspect its operands. This is
4644   // fairly easy if C is the SETCC node, but it can potentially be
4645   // undiscoverable (or not reasonably discoverable). For example, it could be
4646   // in another basic block or it could require searching a complicated
4647   // expression.
4648   if (VT.isInteger() &&
4649       (VT0 == MVT::i1 || (VT0.isInteger() &&
4650                           TLI.getBooleanContents(false, false) ==
4651                               TLI.getBooleanContents(false, true) &&
4652                           TLI.getBooleanContents(false, false) ==
4653                               TargetLowering::ZeroOrOneBooleanContent)) &&
4654       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4655     SDValue XORNode;
4656     if (VT == VT0)
4657       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4658                          N0, DAG.getConstant(1, VT0));
4659     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4660                           N0, DAG.getConstant(1, VT0));
4661     AddToWorklist(XORNode.getNode());
4662     if (VT.bitsGT(VT0))
4663       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4664     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4665   }
4666   // fold (select C, 0, X) -> (and (not C), X)
4667   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4668     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4669     AddToWorklist(NOTNode.getNode());
4670     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4671   }
4672   // fold (select C, X, 1) -> (or (not C), X)
4673   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4674     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4675     AddToWorklist(NOTNode.getNode());
4676     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4677   }
4678   // fold (select C, X, 0) -> (and C, X)
4679   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4680     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4681   // fold (select X, X, Y) -> (or X, Y)
4682   // fold (select X, 1, Y) -> (or X, Y)
4683   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4684     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4685   // fold (select X, Y, X) -> (and X, Y)
4686   // fold (select X, Y, 0) -> (and X, Y)
4687   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4688     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4689
4690   // If we can fold this based on the true/false value, do so.
4691   if (SimplifySelectOps(N, N1, N2))
4692     return SDValue(N, 0);  // Don't revisit N.
4693
4694   // fold selects based on a setcc into other things, such as min/max/abs
4695   if (N0.getOpcode() == ISD::SETCC) {
4696     if ((!LegalOperations &&
4697          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4698         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4699       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4700                          N0.getOperand(0), N0.getOperand(1),
4701                          N1, N2, N0.getOperand(2));
4702     return SimplifySelect(SDLoc(N), N0, N1, N2);
4703   }
4704
4705   return SDValue();
4706 }
4707
4708 static
4709 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4710   SDLoc DL(N);
4711   EVT LoVT, HiVT;
4712   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4713
4714   // Split the inputs.
4715   SDValue Lo, Hi, LL, LH, RL, RH;
4716   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4717   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4718
4719   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4720   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4721
4722   return std::make_pair(Lo, Hi);
4723 }
4724
4725 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4726 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4727 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4728   SDLoc dl(N);
4729   SDValue Cond = N->getOperand(0);
4730   SDValue LHS = N->getOperand(1);
4731   SDValue RHS = N->getOperand(2);
4732   EVT VT = N->getValueType(0);
4733   int NumElems = VT.getVectorNumElements();
4734   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4735          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4736          Cond.getOpcode() == ISD::BUILD_VECTOR);
4737
4738   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4739   // binary ones here.
4740   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4741     return SDValue();
4742
4743   // We're sure we have an even number of elements due to the
4744   // concat_vectors we have as arguments to vselect.
4745   // Skip BV elements until we find one that's not an UNDEF
4746   // After we find an UNDEF element, keep looping until we get to half the
4747   // length of the BV and see if all the non-undef nodes are the same.
4748   ConstantSDNode *BottomHalf = nullptr;
4749   for (int i = 0; i < NumElems / 2; ++i) {
4750     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4751       continue;
4752
4753     if (BottomHalf == nullptr)
4754       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4755     else if (Cond->getOperand(i).getNode() != BottomHalf)
4756       return SDValue();
4757   }
4758
4759   // Do the same for the second half of the BuildVector
4760   ConstantSDNode *TopHalf = nullptr;
4761   for (int i = NumElems / 2; i < NumElems; ++i) {
4762     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4763       continue;
4764
4765     if (TopHalf == nullptr)
4766       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4767     else if (Cond->getOperand(i).getNode() != TopHalf)
4768       return SDValue();
4769   }
4770
4771   assert(TopHalf && BottomHalf &&
4772          "One half of the selector was all UNDEFs and the other was all the "
4773          "same value. This should have been addressed before this function.");
4774   return DAG.getNode(
4775       ISD::CONCAT_VECTORS, dl, VT,
4776       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4777       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4778 }
4779
4780 SDValue DAGCombiner::visitMSTORE(SDNode *N) {
4781
4782   if (Level >= AfterLegalizeTypes)
4783     return SDValue();
4784
4785   MaskedStoreSDNode *MST = dyn_cast<MaskedStoreSDNode>(N);
4786   SDValue Mask = MST->getMask();
4787   SDValue Data  = MST->getData();
4788   SDLoc DL(N);
4789
4790   // If the MSTORE data type requires splitting and the mask is provided by a
4791   // SETCC, then split both nodes and its operands before legalization. This
4792   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4793   // and enables future optimizations (e.g. min/max pattern matching on X86).
4794   if (Mask.getOpcode() == ISD::SETCC) {
4795
4796     // Check if any splitting is required.
4797     if (TLI.getTypeAction(*DAG.getContext(), Data.getValueType()) !=
4798         TargetLowering::TypeSplitVector)
4799       return SDValue();
4800
4801     SDValue MaskLo, MaskHi, Lo, Hi;
4802     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4803
4804     EVT LoVT, HiVT;
4805     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MST->getValueType(0));
4806
4807     SDValue Chain = MST->getChain();
4808     SDValue Ptr   = MST->getBasePtr();
4809
4810     EVT MemoryVT = MST->getMemoryVT();
4811     unsigned Alignment = MST->getOriginalAlignment();
4812
4813     // if Alignment is equal to the vector size,
4814     // take the half of it for the second part
4815     unsigned SecondHalfAlignment =
4816       (Alignment == Data->getValueType(0).getSizeInBits()/8) ?
4817          Alignment/2 : Alignment;
4818
4819     EVT LoMemVT, HiMemVT;
4820     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4821
4822     SDValue DataLo, DataHi;
4823     std::tie(DataLo, DataHi) = DAG.SplitVector(Data, DL);
4824
4825     MachineMemOperand *MMO = DAG.getMachineFunction().
4826       getMachineMemOperand(MST->getPointerInfo(), 
4827                            MachineMemOperand::MOStore,  LoMemVT.getStoreSize(),
4828                            Alignment, MST->getAAInfo(), MST->getRanges());
4829
4830     Lo = DAG.getMaskedStore(Chain, DL, DataLo, Ptr, MaskLo, MMO);
4831
4832     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4833     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4834                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4835
4836     MMO = DAG.getMachineFunction().
4837       getMachineMemOperand(MST->getPointerInfo(), 
4838                            MachineMemOperand::MOStore,  HiMemVT.getStoreSize(),
4839                            SecondHalfAlignment, MST->getAAInfo(),
4840                            MST->getRanges());
4841
4842     Hi = DAG.getMaskedStore(Chain, DL, DataHi, Ptr, MaskHi, MMO);
4843
4844     AddToWorklist(Lo.getNode());
4845     AddToWorklist(Hi.getNode());
4846
4847     return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo, Hi);
4848   }
4849   return SDValue();
4850 }
4851
4852 SDValue DAGCombiner::visitMLOAD(SDNode *N) {
4853
4854   if (Level >= AfterLegalizeTypes)
4855     return SDValue();
4856
4857   MaskedLoadSDNode *MLD = dyn_cast<MaskedLoadSDNode>(N);
4858   SDValue Mask = MLD->getMask();
4859   SDLoc DL(N);
4860
4861   // If the MLOAD result requires splitting and the mask is provided by a
4862   // SETCC, then split both nodes and its operands before legalization. This
4863   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4864   // and enables future optimizations (e.g. min/max pattern matching on X86).
4865
4866   if (Mask.getOpcode() == ISD::SETCC) {
4867     EVT VT = N->getValueType(0);
4868
4869     // Check if any splitting is required.
4870     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4871         TargetLowering::TypeSplitVector)
4872       return SDValue();
4873
4874     SDValue MaskLo, MaskHi, Lo, Hi;
4875     std::tie(MaskLo, MaskHi) = SplitVSETCC(Mask.getNode(), DAG);
4876
4877     SDValue Src0 = MLD->getSrc0();
4878     SDValue Src0Lo, Src0Hi;
4879     std::tie(Src0Lo, Src0Hi) = DAG.SplitVector(Src0, DL);
4880
4881     EVT LoVT, HiVT;
4882     std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(MLD->getValueType(0));
4883
4884     SDValue Chain = MLD->getChain();
4885     SDValue Ptr   = MLD->getBasePtr();
4886     EVT MemoryVT = MLD->getMemoryVT();
4887     unsigned Alignment = MLD->getOriginalAlignment();
4888
4889     // if Alignment is equal to the vector size,
4890     // take the half of it for the second part
4891     unsigned SecondHalfAlignment =
4892       (Alignment == MLD->getValueType(0).getSizeInBits()/8) ?
4893          Alignment/2 : Alignment;
4894
4895     EVT LoMemVT, HiMemVT;
4896     std::tie(LoMemVT, HiMemVT) = DAG.GetSplitDestVTs(MemoryVT);
4897
4898     MachineMemOperand *MMO = DAG.getMachineFunction().
4899     getMachineMemOperand(MLD->getPointerInfo(), 
4900                          MachineMemOperand::MOLoad,  LoMemVT.getStoreSize(),
4901                          Alignment, MLD->getAAInfo(), MLD->getRanges());
4902
4903     Lo = DAG.getMaskedLoad(LoVT, DL, Chain, Ptr, MaskLo, Src0Lo, MMO);
4904
4905     unsigned IncrementSize = LoMemVT.getSizeInBits()/8;
4906     Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
4907                       DAG.getConstant(IncrementSize, Ptr.getValueType()));
4908
4909     MMO = DAG.getMachineFunction().
4910     getMachineMemOperand(MLD->getPointerInfo(), 
4911                          MachineMemOperand::MOLoad,  HiMemVT.getStoreSize(),
4912                          SecondHalfAlignment, MLD->getAAInfo(), MLD->getRanges());
4913
4914     Hi = DAG.getMaskedLoad(HiVT, DL, Chain, Ptr, MaskHi, Src0Hi, MMO);
4915
4916     AddToWorklist(Lo.getNode());
4917     AddToWorklist(Hi.getNode());
4918
4919     // Build a factor node to remember that this load is independent of the
4920     // other one.
4921     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Lo.getValue(1),
4922                         Hi.getValue(1));
4923
4924     // Legalized the chain result - switch anything that used the old chain to
4925     // use the new one.
4926     DAG.ReplaceAllUsesOfValueWith(SDValue(MLD, 1), Chain);
4927
4928     SDValue LoadRes = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4929
4930     SDValue RetOps[] = { LoadRes, Chain };
4931     return DAG.getMergeValues(RetOps, DL);
4932   }
4933   return SDValue();
4934 }
4935
4936 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4937   SDValue N0 = N->getOperand(0);
4938   SDValue N1 = N->getOperand(1);
4939   SDValue N2 = N->getOperand(2);
4940   SDLoc DL(N);
4941
4942   // Canonicalize integer abs.
4943   // vselect (setg[te] X,  0),  X, -X ->
4944   // vselect (setgt    X, -1),  X, -X ->
4945   // vselect (setl[te] X,  0), -X,  X ->
4946   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4947   if (N0.getOpcode() == ISD::SETCC) {
4948     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4949     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4950     bool isAbs = false;
4951     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4952
4953     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4954          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4955         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4956       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4957     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4958              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4959       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4960
4961     if (isAbs) {
4962       EVT VT = LHS.getValueType();
4963       SDValue Shift = DAG.getNode(
4964           ISD::SRA, DL, VT, LHS,
4965           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4966       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4967       AddToWorklist(Shift.getNode());
4968       AddToWorklist(Add.getNode());
4969       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4970     }
4971   }
4972
4973   // If the VSELECT result requires splitting and the mask is provided by a
4974   // SETCC, then split both nodes and its operands before legalization. This
4975   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4976   // and enables future optimizations (e.g. min/max pattern matching on X86).
4977   if (N0.getOpcode() == ISD::SETCC) {
4978     EVT VT = N->getValueType(0);
4979
4980     // Check if any splitting is required.
4981     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4982         TargetLowering::TypeSplitVector)
4983       return SDValue();
4984
4985     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4986     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4987     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4988     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4989
4990     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4991     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4992
4993     // Add the new VSELECT nodes to the work list in case they need to be split
4994     // again.
4995     AddToWorklist(Lo.getNode());
4996     AddToWorklist(Hi.getNode());
4997
4998     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4999   }
5000
5001   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
5002   if (ISD::isBuildVectorAllOnes(N0.getNode()))
5003     return N1;
5004   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
5005   if (ISD::isBuildVectorAllZeros(N0.getNode()))
5006     return N2;
5007
5008   // The ConvertSelectToConcatVector function is assuming both the above
5009   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
5010   // and addressed.
5011   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
5012       N2.getOpcode() == ISD::CONCAT_VECTORS &&
5013       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
5014     SDValue CV = ConvertSelectToConcatVector(N, DAG);
5015     if (CV.getNode())
5016       return CV;
5017   }
5018
5019   return SDValue();
5020 }
5021
5022 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
5023   SDValue N0 = N->getOperand(0);
5024   SDValue N1 = N->getOperand(1);
5025   SDValue N2 = N->getOperand(2);
5026   SDValue N3 = N->getOperand(3);
5027   SDValue N4 = N->getOperand(4);
5028   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
5029
5030   // fold select_cc lhs, rhs, x, x, cc -> x
5031   if (N2 == N3)
5032     return N2;
5033
5034   // Determine if the condition we're dealing with is constant
5035   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
5036                               N0, N1, CC, SDLoc(N), false);
5037   if (SCC.getNode()) {
5038     AddToWorklist(SCC.getNode());
5039
5040     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
5041       if (!SCCC->isNullValue())
5042         return N2;    // cond always true -> true val
5043       else
5044         return N3;    // cond always false -> false val
5045     }
5046
5047     // Fold to a simpler select_cc
5048     if (SCC.getOpcode() == ISD::SETCC)
5049       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
5050                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
5051                          SCC.getOperand(2));
5052   }
5053
5054   // If we can fold this based on the true/false value, do so.
5055   if (SimplifySelectOps(N, N2, N3))
5056     return SDValue(N, 0);  // Don't revisit N.
5057
5058   // fold select_cc into other things, such as min/max/abs
5059   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
5060 }
5061
5062 SDValue DAGCombiner::visitSETCC(SDNode *N) {
5063   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
5064                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
5065                        SDLoc(N));
5066 }
5067
5068 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
5069 // dag node into a ConstantSDNode or a build_vector of constants.
5070 // This function is called by the DAGCombiner when visiting sext/zext/aext
5071 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
5072 // Vector extends are not folded if operations are legal; this is to
5073 // avoid introducing illegal build_vector dag nodes.
5074 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
5075                                          SelectionDAG &DAG, bool LegalTypes,
5076                                          bool LegalOperations) {
5077   unsigned Opcode = N->getOpcode();
5078   SDValue N0 = N->getOperand(0);
5079   EVT VT = N->getValueType(0);
5080
5081   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
5082          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
5083
5084   // fold (sext c1) -> c1
5085   // fold (zext c1) -> c1
5086   // fold (aext c1) -> c1
5087   if (isa<ConstantSDNode>(N0))
5088     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
5089
5090   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
5091   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
5092   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
5093   EVT SVT = VT.getScalarType();
5094   if (!(VT.isVector() &&
5095       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
5096       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
5097     return nullptr;
5098
5099   // We can fold this node into a build_vector.
5100   unsigned VTBits = SVT.getSizeInBits();
5101   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
5102   unsigned ShAmt = VTBits - EVTBits;
5103   SmallVector<SDValue, 8> Elts;
5104   unsigned NumElts = N0->getNumOperands();
5105   SDLoc DL(N);
5106
5107   for (unsigned i=0; i != NumElts; ++i) {
5108     SDValue Op = N0->getOperand(i);
5109     if (Op->getOpcode() == ISD::UNDEF) {
5110       Elts.push_back(DAG.getUNDEF(SVT));
5111       continue;
5112     }
5113
5114     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
5115     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
5116     if (Opcode == ISD::SIGN_EXTEND)
5117       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
5118                                      SVT));
5119     else
5120       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
5121                                      SVT));
5122   }
5123
5124   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
5125 }
5126
5127 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
5128 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
5129 // transformation. Returns true if extension are possible and the above
5130 // mentioned transformation is profitable.
5131 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
5132                                     unsigned ExtOpc,
5133                                     SmallVectorImpl<SDNode *> &ExtendNodes,
5134                                     const TargetLowering &TLI) {
5135   bool HasCopyToRegUses = false;
5136   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
5137   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
5138                             UE = N0.getNode()->use_end();
5139        UI != UE; ++UI) {
5140     SDNode *User = *UI;
5141     if (User == N)
5142       continue;
5143     if (UI.getUse().getResNo() != N0.getResNo())
5144       continue;
5145     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
5146     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
5147       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
5148       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
5149         // Sign bits will be lost after a zext.
5150         return false;
5151       bool Add = false;
5152       for (unsigned i = 0; i != 2; ++i) {
5153         SDValue UseOp = User->getOperand(i);
5154         if (UseOp == N0)
5155           continue;
5156         if (!isa<ConstantSDNode>(UseOp))
5157           return false;
5158         Add = true;
5159       }
5160       if (Add)
5161         ExtendNodes.push_back(User);
5162       continue;
5163     }
5164     // If truncates aren't free and there are users we can't
5165     // extend, it isn't worthwhile.
5166     if (!isTruncFree)
5167       return false;
5168     // Remember if this value is live-out.
5169     if (User->getOpcode() == ISD::CopyToReg)
5170       HasCopyToRegUses = true;
5171   }
5172
5173   if (HasCopyToRegUses) {
5174     bool BothLiveOut = false;
5175     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5176          UI != UE; ++UI) {
5177       SDUse &Use = UI.getUse();
5178       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5179         BothLiveOut = true;
5180         break;
5181       }
5182     }
5183     if (BothLiveOut)
5184       // Both unextended and extended values are live out. There had better be
5185       // a good reason for the transformation.
5186       return ExtendNodes.size();
5187   }
5188   return true;
5189 }
5190
5191 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5192                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5193                                   ISD::NodeType ExtType) {
5194   // Extend SetCC uses if necessary.
5195   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5196     SDNode *SetCC = SetCCs[i];
5197     SmallVector<SDValue, 4> Ops;
5198
5199     for (unsigned j = 0; j != 2; ++j) {
5200       SDValue SOp = SetCC->getOperand(j);
5201       if (SOp == Trunc)
5202         Ops.push_back(ExtLoad);
5203       else
5204         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5205     }
5206
5207     Ops.push_back(SetCC->getOperand(2));
5208     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5209   }
5210 }
5211
5212 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5213   SDValue N0 = N->getOperand(0);
5214   EVT VT = N->getValueType(0);
5215
5216   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5217                                               LegalOperations))
5218     return SDValue(Res, 0);
5219
5220   // fold (sext (sext x)) -> (sext x)
5221   // fold (sext (aext x)) -> (sext x)
5222   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5223     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5224                        N0.getOperand(0));
5225
5226   if (N0.getOpcode() == ISD::TRUNCATE) {
5227     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5228     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5229     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5230     if (NarrowLoad.getNode()) {
5231       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5232       if (NarrowLoad.getNode() != N0.getNode()) {
5233         CombineTo(N0.getNode(), NarrowLoad);
5234         // CombineTo deleted the truncate, if needed, but not what's under it.
5235         AddToWorklist(oye);
5236       }
5237       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5238     }
5239
5240     // See if the value being truncated is already sign extended.  If so, just
5241     // eliminate the trunc/sext pair.
5242     SDValue Op = N0.getOperand(0);
5243     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5244     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5245     unsigned DestBits = VT.getScalarType().getSizeInBits();
5246     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5247
5248     if (OpBits == DestBits) {
5249       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5250       // bits, it is already ready.
5251       if (NumSignBits > DestBits-MidBits)
5252         return Op;
5253     } else if (OpBits < DestBits) {
5254       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5255       // bits, just sext from i32.
5256       if (NumSignBits > OpBits-MidBits)
5257         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5258     } else {
5259       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5260       // bits, just truncate to i32.
5261       if (NumSignBits > OpBits-MidBits)
5262         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5263     }
5264
5265     // fold (sext (truncate x)) -> (sextinreg x).
5266     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5267                                                  N0.getValueType())) {
5268       if (OpBits < DestBits)
5269         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5270       else if (OpBits > DestBits)
5271         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5272       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5273                          DAG.getValueType(N0.getValueType()));
5274     }
5275   }
5276
5277   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5278   // None of the supported targets knows how to perform load and sign extend
5279   // on vectors in one instruction.  We only perform this transformation on
5280   // scalars.
5281   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5282       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5283       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5284        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5285     bool DoXform = true;
5286     SmallVector<SDNode*, 4> SetCCs;
5287     if (!N0.hasOneUse())
5288       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5289     if (DoXform) {
5290       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5291       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5292                                        LN0->getChain(),
5293                                        LN0->getBasePtr(), N0.getValueType(),
5294                                        LN0->getMemOperand());
5295       CombineTo(N, ExtLoad);
5296       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5297                                   N0.getValueType(), ExtLoad);
5298       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5299       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5300                       ISD::SIGN_EXTEND);
5301       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5302     }
5303   }
5304
5305   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5306   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5307   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5308       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5309     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5310     EVT MemVT = LN0->getMemoryVT();
5311     if ((!LegalOperations && !LN0->isVolatile()) ||
5312         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5313       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5314                                        LN0->getChain(),
5315                                        LN0->getBasePtr(), MemVT,
5316                                        LN0->getMemOperand());
5317       CombineTo(N, ExtLoad);
5318       CombineTo(N0.getNode(),
5319                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5320                             N0.getValueType(), ExtLoad),
5321                 ExtLoad.getValue(1));
5322       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5323     }
5324   }
5325
5326   // fold (sext (and/or/xor (load x), cst)) ->
5327   //      (and/or/xor (sextload x), (sext cst))
5328   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5329        N0.getOpcode() == ISD::XOR) &&
5330       isa<LoadSDNode>(N0.getOperand(0)) &&
5331       N0.getOperand(1).getOpcode() == ISD::Constant &&
5332       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5333       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5334     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5335     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5336       bool DoXform = true;
5337       SmallVector<SDNode*, 4> SetCCs;
5338       if (!N0.hasOneUse())
5339         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5340                                           SetCCs, TLI);
5341       if (DoXform) {
5342         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5343                                          LN0->getChain(), LN0->getBasePtr(),
5344                                          LN0->getMemoryVT(),
5345                                          LN0->getMemOperand());
5346         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5347         Mask = Mask.sext(VT.getSizeInBits());
5348         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5349                                   ExtLoad, DAG.getConstant(Mask, VT));
5350         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5351                                     SDLoc(N0.getOperand(0)),
5352                                     N0.getOperand(0).getValueType(), ExtLoad);
5353         CombineTo(N, And);
5354         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5355         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5356                         ISD::SIGN_EXTEND);
5357         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5358       }
5359     }
5360   }
5361
5362   if (N0.getOpcode() == ISD::SETCC) {
5363     EVT N0VT = N0.getOperand(0).getValueType();
5364     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5365     // Only do this before legalize for now.
5366     if (VT.isVector() && !LegalOperations &&
5367         TLI.getBooleanContents(N0VT) ==
5368             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5369       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5370       // of the same size as the compared operands. Only optimize sext(setcc())
5371       // if this is the case.
5372       EVT SVT = getSetCCResultType(N0VT);
5373
5374       // We know that the # elements of the results is the same as the
5375       // # elements of the compare (and the # elements of the compare result
5376       // for that matter).  Check to see that they are the same size.  If so,
5377       // we know that the element size of the sext'd result matches the
5378       // element size of the compare operands.
5379       if (VT.getSizeInBits() == SVT.getSizeInBits())
5380         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5381                              N0.getOperand(1),
5382                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5383
5384       // If the desired elements are smaller or larger than the source
5385       // elements we can use a matching integer vector type and then
5386       // truncate/sign extend
5387       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5388       if (SVT == MatchingVectorType) {
5389         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5390                                N0.getOperand(0), N0.getOperand(1),
5391                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5392         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5393       }
5394     }
5395
5396     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5397     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5398     SDValue NegOne =
5399       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5400     SDValue SCC =
5401       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5402                        NegOne, DAG.getConstant(0, VT),
5403                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5404     if (SCC.getNode()) return SCC;
5405
5406     if (!VT.isVector()) {
5407       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5408       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5409         SDLoc DL(N);
5410         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5411         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5412                                      N0.getOperand(0), N0.getOperand(1), CC);
5413         return DAG.getSelect(DL, VT, SetCC,
5414                              NegOne, DAG.getConstant(0, VT));
5415       }
5416     }
5417   }
5418
5419   // fold (sext x) -> (zext x) if the sign bit is known zero.
5420   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5421       DAG.SignBitIsZero(N0))
5422     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5423
5424   return SDValue();
5425 }
5426
5427 // isTruncateOf - If N is a truncate of some other value, return true, record
5428 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5429 // This function computes KnownZero to avoid a duplicated call to
5430 // computeKnownBits in the caller.
5431 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5432                          APInt &KnownZero) {
5433   APInt KnownOne;
5434   if (N->getOpcode() == ISD::TRUNCATE) {
5435     Op = N->getOperand(0);
5436     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5437     return true;
5438   }
5439
5440   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5441       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5442     return false;
5443
5444   SDValue Op0 = N->getOperand(0);
5445   SDValue Op1 = N->getOperand(1);
5446   assert(Op0.getValueType() == Op1.getValueType());
5447
5448   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5449   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5450   if (COp0 && COp0->isNullValue())
5451     Op = Op1;
5452   else if (COp1 && COp1->isNullValue())
5453     Op = Op0;
5454   else
5455     return false;
5456
5457   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5458
5459   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5460     return false;
5461
5462   return true;
5463 }
5464
5465 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5466   SDValue N0 = N->getOperand(0);
5467   EVT VT = N->getValueType(0);
5468
5469   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5470                                               LegalOperations))
5471     return SDValue(Res, 0);
5472
5473   // fold (zext (zext x)) -> (zext x)
5474   // fold (zext (aext x)) -> (zext x)
5475   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5476     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5477                        N0.getOperand(0));
5478
5479   // fold (zext (truncate x)) -> (zext x) or
5480   //      (zext (truncate x)) -> (truncate x)
5481   // This is valid when the truncated bits of x are already zero.
5482   // FIXME: We should extend this to work for vectors too.
5483   SDValue Op;
5484   APInt KnownZero;
5485   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5486     APInt TruncatedBits =
5487       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5488       APInt(Op.getValueSizeInBits(), 0) :
5489       APInt::getBitsSet(Op.getValueSizeInBits(),
5490                         N0.getValueSizeInBits(),
5491                         std::min(Op.getValueSizeInBits(),
5492                                  VT.getSizeInBits()));
5493     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5494       if (VT.bitsGT(Op.getValueType()))
5495         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5496       if (VT.bitsLT(Op.getValueType()))
5497         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5498
5499       return Op;
5500     }
5501   }
5502
5503   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5504   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5505   if (N0.getOpcode() == ISD::TRUNCATE) {
5506     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5507     if (NarrowLoad.getNode()) {
5508       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5509       if (NarrowLoad.getNode() != N0.getNode()) {
5510         CombineTo(N0.getNode(), NarrowLoad);
5511         // CombineTo deleted the truncate, if needed, but not what's under it.
5512         AddToWorklist(oye);
5513       }
5514       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5515     }
5516   }
5517
5518   // fold (zext (truncate x)) -> (and x, mask)
5519   if (N0.getOpcode() == ISD::TRUNCATE &&
5520       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5521
5522     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5523     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5524     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5525     if (NarrowLoad.getNode()) {
5526       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5527       if (NarrowLoad.getNode() != N0.getNode()) {
5528         CombineTo(N0.getNode(), NarrowLoad);
5529         // CombineTo deleted the truncate, if needed, but not what's under it.
5530         AddToWorklist(oye);
5531       }
5532       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5533     }
5534
5535     SDValue Op = N0.getOperand(0);
5536     if (Op.getValueType().bitsLT(VT)) {
5537       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5538       AddToWorklist(Op.getNode());
5539     } else if (Op.getValueType().bitsGT(VT)) {
5540       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5541       AddToWorklist(Op.getNode());
5542     }
5543     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5544                                   N0.getValueType().getScalarType());
5545   }
5546
5547   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5548   // if either of the casts is not free.
5549   if (N0.getOpcode() == ISD::AND &&
5550       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5551       N0.getOperand(1).getOpcode() == ISD::Constant &&
5552       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5553                            N0.getValueType()) ||
5554        !TLI.isZExtFree(N0.getValueType(), VT))) {
5555     SDValue X = N0.getOperand(0).getOperand(0);
5556     if (X.getValueType().bitsLT(VT)) {
5557       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5558     } else if (X.getValueType().bitsGT(VT)) {
5559       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5560     }
5561     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5562     Mask = Mask.zext(VT.getSizeInBits());
5563     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5564                        X, DAG.getConstant(Mask, VT));
5565   }
5566
5567   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5568   // None of the supported targets knows how to perform load and vector_zext
5569   // on vectors in one instruction.  We only perform this transformation on
5570   // scalars.
5571   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5572       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5573       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5574        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5575     bool DoXform = true;
5576     SmallVector<SDNode*, 4> SetCCs;
5577     if (!N0.hasOneUse())
5578       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5579     if (DoXform) {
5580       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5581       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5582                                        LN0->getChain(),
5583                                        LN0->getBasePtr(), N0.getValueType(),
5584                                        LN0->getMemOperand());
5585       CombineTo(N, ExtLoad);
5586       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5587                                   N0.getValueType(), ExtLoad);
5588       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5589
5590       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5591                       ISD::ZERO_EXTEND);
5592       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5593     }
5594   }
5595
5596   // fold (zext (and/or/xor (load x), cst)) ->
5597   //      (and/or/xor (zextload x), (zext cst))
5598   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5599        N0.getOpcode() == ISD::XOR) &&
5600       isa<LoadSDNode>(N0.getOperand(0)) &&
5601       N0.getOperand(1).getOpcode() == ISD::Constant &&
5602       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5603       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5604     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5605     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5606       bool DoXform = true;
5607       SmallVector<SDNode*, 4> SetCCs;
5608       if (!N0.hasOneUse())
5609         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5610                                           SetCCs, TLI);
5611       if (DoXform) {
5612         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5613                                          LN0->getChain(), LN0->getBasePtr(),
5614                                          LN0->getMemoryVT(),
5615                                          LN0->getMemOperand());
5616         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5617         Mask = Mask.zext(VT.getSizeInBits());
5618         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5619                                   ExtLoad, DAG.getConstant(Mask, VT));
5620         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5621                                     SDLoc(N0.getOperand(0)),
5622                                     N0.getOperand(0).getValueType(), ExtLoad);
5623         CombineTo(N, And);
5624         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5625         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5626                         ISD::ZERO_EXTEND);
5627         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5628       }
5629     }
5630   }
5631
5632   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5633   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5634   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5635       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5636     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5637     EVT MemVT = LN0->getMemoryVT();
5638     if ((!LegalOperations && !LN0->isVolatile()) ||
5639         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5640       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5641                                        LN0->getChain(),
5642                                        LN0->getBasePtr(), MemVT,
5643                                        LN0->getMemOperand());
5644       CombineTo(N, ExtLoad);
5645       CombineTo(N0.getNode(),
5646                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5647                             ExtLoad),
5648                 ExtLoad.getValue(1));
5649       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5650     }
5651   }
5652
5653   if (N0.getOpcode() == ISD::SETCC) {
5654     if (!LegalOperations && VT.isVector() &&
5655         N0.getValueType().getVectorElementType() == MVT::i1) {
5656       EVT N0VT = N0.getOperand(0).getValueType();
5657       if (getSetCCResultType(N0VT) == N0.getValueType())
5658         return SDValue();
5659
5660       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5661       // Only do this before legalize for now.
5662       EVT EltVT = VT.getVectorElementType();
5663       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5664                                     DAG.getConstant(1, EltVT));
5665       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5666         // We know that the # elements of the results is the same as the
5667         // # elements of the compare (and the # elements of the compare result
5668         // for that matter).  Check to see that they are the same size.  If so,
5669         // we know that the element size of the sext'd result matches the
5670         // element size of the compare operands.
5671         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5672                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5673                                          N0.getOperand(1),
5674                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5675                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5676                                        OneOps));
5677
5678       // If the desired elements are smaller or larger than the source
5679       // elements we can use a matching integer vector type and then
5680       // truncate/sign extend
5681       EVT MatchingElementType =
5682         EVT::getIntegerVT(*DAG.getContext(),
5683                           N0VT.getScalarType().getSizeInBits());
5684       EVT MatchingVectorType =
5685         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5686                          N0VT.getVectorNumElements());
5687       SDValue VsetCC =
5688         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5689                       N0.getOperand(1),
5690                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5691       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5692                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5693                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5694     }
5695
5696     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5697     SDValue SCC =
5698       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5699                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5700                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5701     if (SCC.getNode()) return SCC;
5702   }
5703
5704   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5705   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5706       isa<ConstantSDNode>(N0.getOperand(1)) &&
5707       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5708       N0.hasOneUse()) {
5709     SDValue ShAmt = N0.getOperand(1);
5710     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5711     if (N0.getOpcode() == ISD::SHL) {
5712       SDValue InnerZExt = N0.getOperand(0);
5713       // If the original shl may be shifting out bits, do not perform this
5714       // transformation.
5715       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5716         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5717       if (ShAmtVal > KnownZeroBits)
5718         return SDValue();
5719     }
5720
5721     SDLoc DL(N);
5722
5723     // Ensure that the shift amount is wide enough for the shifted value.
5724     if (VT.getSizeInBits() >= 256)
5725       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5726
5727     return DAG.getNode(N0.getOpcode(), DL, VT,
5728                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5729                        ShAmt);
5730   }
5731
5732   return SDValue();
5733 }
5734
5735 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5736   SDValue N0 = N->getOperand(0);
5737   EVT VT = N->getValueType(0);
5738
5739   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5740                                               LegalOperations))
5741     return SDValue(Res, 0);
5742
5743   // fold (aext (aext x)) -> (aext x)
5744   // fold (aext (zext x)) -> (zext x)
5745   // fold (aext (sext x)) -> (sext x)
5746   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5747       N0.getOpcode() == ISD::ZERO_EXTEND ||
5748       N0.getOpcode() == ISD::SIGN_EXTEND)
5749     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5750
5751   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5752   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5753   if (N0.getOpcode() == ISD::TRUNCATE) {
5754     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5755     if (NarrowLoad.getNode()) {
5756       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5757       if (NarrowLoad.getNode() != N0.getNode()) {
5758         CombineTo(N0.getNode(), NarrowLoad);
5759         // CombineTo deleted the truncate, if needed, but not what's under it.
5760         AddToWorklist(oye);
5761       }
5762       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5763     }
5764   }
5765
5766   // fold (aext (truncate x))
5767   if (N0.getOpcode() == ISD::TRUNCATE) {
5768     SDValue TruncOp = N0.getOperand(0);
5769     if (TruncOp.getValueType() == VT)
5770       return TruncOp; // x iff x size == zext size.
5771     if (TruncOp.getValueType().bitsGT(VT))
5772       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5773     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5774   }
5775
5776   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5777   // if the trunc is not free.
5778   if (N0.getOpcode() == ISD::AND &&
5779       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5780       N0.getOperand(1).getOpcode() == ISD::Constant &&
5781       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5782                           N0.getValueType())) {
5783     SDValue X = N0.getOperand(0).getOperand(0);
5784     if (X.getValueType().bitsLT(VT)) {
5785       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5786     } else if (X.getValueType().bitsGT(VT)) {
5787       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5788     }
5789     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5790     Mask = Mask.zext(VT.getSizeInBits());
5791     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5792                        X, DAG.getConstant(Mask, VT));
5793   }
5794
5795   // fold (aext (load x)) -> (aext (truncate (extload x)))
5796   // None of the supported targets knows how to perform load and any_ext
5797   // on vectors in one instruction.  We only perform this transformation on
5798   // scalars.
5799   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5800       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5801       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5802     bool DoXform = true;
5803     SmallVector<SDNode*, 4> SetCCs;
5804     if (!N0.hasOneUse())
5805       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5806     if (DoXform) {
5807       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5808       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5809                                        LN0->getChain(),
5810                                        LN0->getBasePtr(), N0.getValueType(),
5811                                        LN0->getMemOperand());
5812       CombineTo(N, ExtLoad);
5813       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5814                                   N0.getValueType(), ExtLoad);
5815       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5816       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5817                       ISD::ANY_EXTEND);
5818       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5819     }
5820   }
5821
5822   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5823   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5824   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5825   if (N0.getOpcode() == ISD::LOAD &&
5826       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5827       N0.hasOneUse()) {
5828     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5829     ISD::LoadExtType ExtType = LN0->getExtensionType();
5830     EVT MemVT = LN0->getMemoryVT();
5831     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5832       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5833                                        VT, LN0->getChain(), LN0->getBasePtr(),
5834                                        MemVT, LN0->getMemOperand());
5835       CombineTo(N, ExtLoad);
5836       CombineTo(N0.getNode(),
5837                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5838                             N0.getValueType(), ExtLoad),
5839                 ExtLoad.getValue(1));
5840       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5841     }
5842   }
5843
5844   if (N0.getOpcode() == ISD::SETCC) {
5845     // For vectors:
5846     // aext(setcc) -> vsetcc
5847     // aext(setcc) -> truncate(vsetcc)
5848     // aext(setcc) -> aext(vsetcc)
5849     // Only do this before legalize for now.
5850     if (VT.isVector() && !LegalOperations) {
5851       EVT N0VT = N0.getOperand(0).getValueType();
5852         // We know that the # elements of the results is the same as the
5853         // # elements of the compare (and the # elements of the compare result
5854         // for that matter).  Check to see that they are the same size.  If so,
5855         // we know that the element size of the sext'd result matches the
5856         // element size of the compare operands.
5857       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5858         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5859                              N0.getOperand(1),
5860                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5861       // If the desired elements are smaller or larger than the source
5862       // elements we can use a matching integer vector type and then
5863       // truncate/any extend
5864       else {
5865         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5866         SDValue VsetCC =
5867           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5868                         N0.getOperand(1),
5869                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5870         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5871       }
5872     }
5873
5874     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5875     SDValue SCC =
5876       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5877                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5878                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5879     if (SCC.getNode())
5880       return SCC;
5881   }
5882
5883   return SDValue();
5884 }
5885
5886 /// See if the specified operand can be simplified with the knowledge that only
5887 /// the bits specified by Mask are used.  If so, return the simpler operand,
5888 /// otherwise return a null SDValue.
5889 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5890   switch (V.getOpcode()) {
5891   default: break;
5892   case ISD::Constant: {
5893     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5894     assert(CV && "Const value should be ConstSDNode.");
5895     const APInt &CVal = CV->getAPIntValue();
5896     APInt NewVal = CVal & Mask;
5897     if (NewVal != CVal)
5898       return DAG.getConstant(NewVal, V.getValueType());
5899     break;
5900   }
5901   case ISD::OR:
5902   case ISD::XOR:
5903     // If the LHS or RHS don't contribute bits to the or, drop them.
5904     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5905       return V.getOperand(1);
5906     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5907       return V.getOperand(0);
5908     break;
5909   case ISD::SRL:
5910     // Only look at single-use SRLs.
5911     if (!V.getNode()->hasOneUse())
5912       break;
5913     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5914       // See if we can recursively simplify the LHS.
5915       unsigned Amt = RHSC->getZExtValue();
5916
5917       // Watch out for shift count overflow though.
5918       if (Amt >= Mask.getBitWidth()) break;
5919       APInt NewMask = Mask << Amt;
5920       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5921       if (SimplifyLHS.getNode())
5922         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5923                            SimplifyLHS, V.getOperand(1));
5924     }
5925   }
5926   return SDValue();
5927 }
5928
5929 /// If the result of a wider load is shifted to right of N  bits and then
5930 /// truncated to a narrower type and where N is a multiple of number of bits of
5931 /// the narrower type, transform it to a narrower load from address + N / num of
5932 /// bits of new type. If the result is to be extended, also fold the extension
5933 /// to form a extending load.
5934 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5935   unsigned Opc = N->getOpcode();
5936
5937   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5938   SDValue N0 = N->getOperand(0);
5939   EVT VT = N->getValueType(0);
5940   EVT ExtVT = VT;
5941
5942   // This transformation isn't valid for vector loads.
5943   if (VT.isVector())
5944     return SDValue();
5945
5946   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5947   // extended to VT.
5948   if (Opc == ISD::SIGN_EXTEND_INREG) {
5949     ExtType = ISD::SEXTLOAD;
5950     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5951   } else if (Opc == ISD::SRL) {
5952     // Another special-case: SRL is basically zero-extending a narrower value.
5953     ExtType = ISD::ZEXTLOAD;
5954     N0 = SDValue(N, 0);
5955     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5956     if (!N01) return SDValue();
5957     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5958                               VT.getSizeInBits() - N01->getZExtValue());
5959   }
5960   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5961     return SDValue();
5962
5963   unsigned EVTBits = ExtVT.getSizeInBits();
5964
5965   // Do not generate loads of non-round integer types since these can
5966   // be expensive (and would be wrong if the type is not byte sized).
5967   if (!ExtVT.isRound())
5968     return SDValue();
5969
5970   unsigned ShAmt = 0;
5971   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5972     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5973       ShAmt = N01->getZExtValue();
5974       // Is the shift amount a multiple of size of VT?
5975       if ((ShAmt & (EVTBits-1)) == 0) {
5976         N0 = N0.getOperand(0);
5977         // Is the load width a multiple of size of VT?
5978         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5979           return SDValue();
5980       }
5981
5982       // At this point, we must have a load or else we can't do the transform.
5983       if (!isa<LoadSDNode>(N0)) return SDValue();
5984
5985       // Because a SRL must be assumed to *need* to zero-extend the high bits
5986       // (as opposed to anyext the high bits), we can't combine the zextload
5987       // lowering of SRL and an sextload.
5988       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5989         return SDValue();
5990
5991       // If the shift amount is larger than the input type then we're not
5992       // accessing any of the loaded bytes.  If the load was a zextload/extload
5993       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5994       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5995         return SDValue();
5996     }
5997   }
5998
5999   // If the load is shifted left (and the result isn't shifted back right),
6000   // we can fold the truncate through the shift.
6001   unsigned ShLeftAmt = 0;
6002   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
6003       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
6004     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
6005       ShLeftAmt = N01->getZExtValue();
6006       N0 = N0.getOperand(0);
6007     }
6008   }
6009
6010   // If we haven't found a load, we can't narrow it.  Don't transform one with
6011   // multiple uses, this would require adding a new load.
6012   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
6013     return SDValue();
6014
6015   // Don't change the width of a volatile load.
6016   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6017   if (LN0->isVolatile())
6018     return SDValue();
6019
6020   // Verify that we are actually reducing a load width here.
6021   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
6022     return SDValue();
6023
6024   // For the transform to be legal, the load must produce only two values
6025   // (the value loaded and the chain).  Don't transform a pre-increment
6026   // load, for example, which produces an extra value.  Otherwise the
6027   // transformation is not equivalent, and the downstream logic to replace
6028   // uses gets things wrong.
6029   if (LN0->getNumValues() > 2)
6030     return SDValue();
6031
6032   // If the load that we're shrinking is an extload and we're not just
6033   // discarding the extension we can't simply shrink the load. Bail.
6034   // TODO: It would be possible to merge the extensions in some cases.
6035   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
6036       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
6037     return SDValue();
6038
6039   EVT PtrType = N0.getOperand(1).getValueType();
6040
6041   if (PtrType == MVT::Untyped || PtrType.isExtended())
6042     // It's not possible to generate a constant of extended or untyped type.
6043     return SDValue();
6044
6045   // For big endian targets, we need to adjust the offset to the pointer to
6046   // load the correct bytes.
6047   if (TLI.isBigEndian()) {
6048     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
6049     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
6050     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
6051   }
6052
6053   uint64_t PtrOff = ShAmt / 8;
6054   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
6055   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
6056                                PtrType, LN0->getBasePtr(),
6057                                DAG.getConstant(PtrOff, PtrType));
6058   AddToWorklist(NewPtr.getNode());
6059
6060   SDValue Load;
6061   if (ExtType == ISD::NON_EXTLOAD)
6062     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
6063                         LN0->getPointerInfo().getWithOffset(PtrOff),
6064                         LN0->isVolatile(), LN0->isNonTemporal(),
6065                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6066   else
6067     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
6068                           LN0->getPointerInfo().getWithOffset(PtrOff),
6069                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
6070                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
6071
6072   // Replace the old load's chain with the new load's chain.
6073   WorklistRemover DeadNodes(*this);
6074   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6075
6076   // Shift the result left, if we've swallowed a left shift.
6077   SDValue Result = Load;
6078   if (ShLeftAmt != 0) {
6079     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
6080     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
6081       ShImmTy = VT;
6082     // If the shift amount is as large as the result size (but, presumably,
6083     // no larger than the source) then the useful bits of the result are
6084     // zero; we can't simply return the shortened shift, because the result
6085     // of that operation is undefined.
6086     if (ShLeftAmt >= VT.getSizeInBits())
6087       Result = DAG.getConstant(0, VT);
6088     else
6089       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
6090                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
6091   }
6092
6093   // Return the new loaded value.
6094   return Result;
6095 }
6096
6097 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
6098   SDValue N0 = N->getOperand(0);
6099   SDValue N1 = N->getOperand(1);
6100   EVT VT = N->getValueType(0);
6101   EVT EVT = cast<VTSDNode>(N1)->getVT();
6102   unsigned VTBits = VT.getScalarType().getSizeInBits();
6103   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
6104
6105   // fold (sext_in_reg c1) -> c1
6106   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
6107     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
6108
6109   // If the input is already sign extended, just drop the extension.
6110   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
6111     return N0;
6112
6113   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
6114   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
6115       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
6116     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6117                        N0.getOperand(0), N1);
6118
6119   // fold (sext_in_reg (sext x)) -> (sext x)
6120   // fold (sext_in_reg (aext x)) -> (sext x)
6121   // if x is small enough.
6122   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
6123     SDValue N00 = N0.getOperand(0);
6124     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
6125         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
6126       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
6127   }
6128
6129   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
6130   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
6131     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
6132
6133   // fold operands of sext_in_reg based on knowledge that the top bits are not
6134   // demanded.
6135   if (SimplifyDemandedBits(SDValue(N, 0)))
6136     return SDValue(N, 0);
6137
6138   // fold (sext_in_reg (load x)) -> (smaller sextload x)
6139   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
6140   SDValue NarrowLoad = ReduceLoadWidth(N);
6141   if (NarrowLoad.getNode())
6142     return NarrowLoad;
6143
6144   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
6145   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
6146   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
6147   if (N0.getOpcode() == ISD::SRL) {
6148     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
6149       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
6150         // We can turn this into an SRA iff the input to the SRL is already sign
6151         // extended enough.
6152         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
6153         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
6154           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
6155                              N0.getOperand(0), N0.getOperand(1));
6156       }
6157   }
6158
6159   // fold (sext_inreg (extload x)) -> (sextload x)
6160   if (ISD::isEXTLoad(N0.getNode()) &&
6161       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6162       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6163       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6164        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6165     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6166     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6167                                      LN0->getChain(),
6168                                      LN0->getBasePtr(), EVT,
6169                                      LN0->getMemOperand());
6170     CombineTo(N, ExtLoad);
6171     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6172     AddToWorklist(ExtLoad.getNode());
6173     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6174   }
6175   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6176   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6177       N0.hasOneUse() &&
6178       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6179       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6180        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6181     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6182     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6183                                      LN0->getChain(),
6184                                      LN0->getBasePtr(), EVT,
6185                                      LN0->getMemOperand());
6186     CombineTo(N, ExtLoad);
6187     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6188     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6189   }
6190
6191   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6192   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6193     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6194                                        N0.getOperand(1), false);
6195     if (BSwap.getNode())
6196       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6197                          BSwap, N1);
6198   }
6199
6200   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6201   // into a build_vector.
6202   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6203     SmallVector<SDValue, 8> Elts;
6204     unsigned NumElts = N0->getNumOperands();
6205     unsigned ShAmt = VTBits - EVTBits;
6206
6207     for (unsigned i = 0; i != NumElts; ++i) {
6208       SDValue Op = N0->getOperand(i);
6209       if (Op->getOpcode() == ISD::UNDEF) {
6210         Elts.push_back(Op);
6211         continue;
6212       }
6213
6214       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6215       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6216       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6217                                      Op.getValueType()));
6218     }
6219
6220     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6221   }
6222
6223   return SDValue();
6224 }
6225
6226 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6227   SDValue N0 = N->getOperand(0);
6228   EVT VT = N->getValueType(0);
6229   bool isLE = TLI.isLittleEndian();
6230
6231   // noop truncate
6232   if (N0.getValueType() == N->getValueType(0))
6233     return N0;
6234   // fold (truncate c1) -> c1
6235   if (isa<ConstantSDNode>(N0))
6236     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6237   // fold (truncate (truncate x)) -> (truncate x)
6238   if (N0.getOpcode() == ISD::TRUNCATE)
6239     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6240   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6241   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6242       N0.getOpcode() == ISD::SIGN_EXTEND ||
6243       N0.getOpcode() == ISD::ANY_EXTEND) {
6244     if (N0.getOperand(0).getValueType().bitsLT(VT))
6245       // if the source is smaller than the dest, we still need an extend
6246       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6247                          N0.getOperand(0));
6248     if (N0.getOperand(0).getValueType().bitsGT(VT))
6249       // if the source is larger than the dest, than we just need the truncate
6250       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6251     // if the source and dest are the same type, we can drop both the extend
6252     // and the truncate.
6253     return N0.getOperand(0);
6254   }
6255
6256   // Fold extract-and-trunc into a narrow extract. For example:
6257   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6258   //   i32 y = TRUNCATE(i64 x)
6259   //        -- becomes --
6260   //   v16i8 b = BITCAST (v2i64 val)
6261   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6262   //
6263   // Note: We only run this optimization after type legalization (which often
6264   // creates this pattern) and before operation legalization after which
6265   // we need to be more careful about the vector instructions that we generate.
6266   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6267       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6268
6269     EVT VecTy = N0.getOperand(0).getValueType();
6270     EVT ExTy = N0.getValueType();
6271     EVT TrTy = N->getValueType(0);
6272
6273     unsigned NumElem = VecTy.getVectorNumElements();
6274     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6275
6276     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6277     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6278
6279     SDValue EltNo = N0->getOperand(1);
6280     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6281       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6282       EVT IndexTy = TLI.getVectorIdxTy();
6283       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6284
6285       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6286                               NVT, N0.getOperand(0));
6287
6288       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6289                          SDLoc(N), TrTy, V,
6290                          DAG.getConstant(Index, IndexTy));
6291     }
6292   }
6293
6294   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6295   if (N0.getOpcode() == ISD::SELECT) {
6296     EVT SrcVT = N0.getValueType();
6297     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6298         TLI.isTruncateFree(SrcVT, VT)) {
6299       SDLoc SL(N0);
6300       SDValue Cond = N0.getOperand(0);
6301       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6302       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6303       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6304     }
6305   }
6306
6307   // Fold a series of buildvector, bitcast, and truncate if possible.
6308   // For example fold
6309   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6310   //   (2xi32 (buildvector x, y)).
6311   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6312       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6313       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6314       N0.getOperand(0).hasOneUse()) {
6315
6316     SDValue BuildVect = N0.getOperand(0);
6317     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6318     EVT TruncVecEltTy = VT.getVectorElementType();
6319
6320     // Check that the element types match.
6321     if (BuildVectEltTy == TruncVecEltTy) {
6322       // Now we only need to compute the offset of the truncated elements.
6323       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6324       unsigned TruncVecNumElts = VT.getVectorNumElements();
6325       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6326
6327       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6328              "Invalid number of elements");
6329
6330       SmallVector<SDValue, 8> Opnds;
6331       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6332         Opnds.push_back(BuildVect.getOperand(i));
6333
6334       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6335     }
6336   }
6337
6338   // See if we can simplify the input to this truncate through knowledge that
6339   // only the low bits are being used.
6340   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6341   // Currently we only perform this optimization on scalars because vectors
6342   // may have different active low bits.
6343   if (!VT.isVector()) {
6344     SDValue Shorter =
6345       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6346                                                VT.getSizeInBits()));
6347     if (Shorter.getNode())
6348       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6349   }
6350   // fold (truncate (load x)) -> (smaller load x)
6351   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6352   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6353     SDValue Reduced = ReduceLoadWidth(N);
6354     if (Reduced.getNode())
6355       return Reduced;
6356     // Handle the case where the load remains an extending load even
6357     // after truncation.
6358     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6359       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6360       if (!LN0->isVolatile() &&
6361           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6362         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6363                                          VT, LN0->getChain(), LN0->getBasePtr(),
6364                                          LN0->getMemoryVT(),
6365                                          LN0->getMemOperand());
6366         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6367         return NewLoad;
6368       }
6369     }
6370   }
6371   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6372   // where ... are all 'undef'.
6373   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6374     SmallVector<EVT, 8> VTs;
6375     SDValue V;
6376     unsigned Idx = 0;
6377     unsigned NumDefs = 0;
6378
6379     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6380       SDValue X = N0.getOperand(i);
6381       if (X.getOpcode() != ISD::UNDEF) {
6382         V = X;
6383         Idx = i;
6384         NumDefs++;
6385       }
6386       // Stop if more than one members are non-undef.
6387       if (NumDefs > 1)
6388         break;
6389       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6390                                      VT.getVectorElementType(),
6391                                      X.getValueType().getVectorNumElements()));
6392     }
6393
6394     if (NumDefs == 0)
6395       return DAG.getUNDEF(VT);
6396
6397     if (NumDefs == 1) {
6398       assert(V.getNode() && "The single defined operand is empty!");
6399       SmallVector<SDValue, 8> Opnds;
6400       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6401         if (i != Idx) {
6402           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6403           continue;
6404         }
6405         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6406         AddToWorklist(NV.getNode());
6407         Opnds.push_back(NV);
6408       }
6409       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6410     }
6411   }
6412
6413   // Simplify the operands using demanded-bits information.
6414   if (!VT.isVector() &&
6415       SimplifyDemandedBits(SDValue(N, 0)))
6416     return SDValue(N, 0);
6417
6418   return SDValue();
6419 }
6420
6421 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6422   SDValue Elt = N->getOperand(i);
6423   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6424     return Elt.getNode();
6425   return Elt.getOperand(Elt.getResNo()).getNode();
6426 }
6427
6428 /// build_pair (load, load) -> load
6429 /// if load locations are consecutive.
6430 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6431   assert(N->getOpcode() == ISD::BUILD_PAIR);
6432
6433   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6434   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6435   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6436       LD1->getAddressSpace() != LD2->getAddressSpace())
6437     return SDValue();
6438   EVT LD1VT = LD1->getValueType(0);
6439
6440   if (ISD::isNON_EXTLoad(LD2) &&
6441       LD2->hasOneUse() &&
6442       // If both are volatile this would reduce the number of volatile loads.
6443       // If one is volatile it might be ok, but play conservative and bail out.
6444       !LD1->isVolatile() &&
6445       !LD2->isVolatile() &&
6446       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6447     unsigned Align = LD1->getAlignment();
6448     unsigned NewAlign = TLI.getDataLayout()->
6449       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6450
6451     if (NewAlign <= Align &&
6452         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6453       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6454                          LD1->getBasePtr(), LD1->getPointerInfo(),
6455                          false, false, false, Align);
6456   }
6457
6458   return SDValue();
6459 }
6460
6461 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6462   SDValue N0 = N->getOperand(0);
6463   EVT VT = N->getValueType(0);
6464
6465   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6466   // Only do this before legalize, since afterward the target may be depending
6467   // on the bitconvert.
6468   // First check to see if this is all constant.
6469   if (!LegalTypes &&
6470       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6471       VT.isVector()) {
6472     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6473
6474     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6475     assert(!DestEltVT.isVector() &&
6476            "Element type of vector ValueType must not be vector!");
6477     if (isSimple)
6478       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6479   }
6480
6481   // If the input is a constant, let getNode fold it.
6482   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6483     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6484     if (Res.getNode() != N) {
6485       if (!LegalOperations ||
6486           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6487         return Res;
6488
6489       // Folding it resulted in an illegal node, and it's too late to
6490       // do that. Clean up the old node and forego the transformation.
6491       // Ideally this won't happen very often, because instcombine
6492       // and the earlier dagcombine runs (where illegal nodes are
6493       // permitted) should have folded most of them already.
6494       deleteAndRecombine(Res.getNode());
6495     }
6496   }
6497
6498   // (conv (conv x, t1), t2) -> (conv x, t2)
6499   if (N0.getOpcode() == ISD::BITCAST)
6500     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6501                        N0.getOperand(0));
6502
6503   // fold (conv (load x)) -> (load (conv*)x)
6504   // If the resultant load doesn't need a higher alignment than the original!
6505   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6506       // Do not change the width of a volatile load.
6507       !cast<LoadSDNode>(N0)->isVolatile() &&
6508       // Do not remove the cast if the types differ in endian layout.
6509       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6510       TLI.hasBigEndianPartOrdering(VT) &&
6511       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6512       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6513     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6514     unsigned Align = TLI.getDataLayout()->
6515       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6516     unsigned OrigAlign = LN0->getAlignment();
6517
6518     if (Align <= OrigAlign) {
6519       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6520                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6521                                  LN0->isVolatile(), LN0->isNonTemporal(),
6522                                  LN0->isInvariant(), OrigAlign,
6523                                  LN0->getAAInfo());
6524       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6525       return Load;
6526     }
6527   }
6528
6529   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6530   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6531   // This often reduces constant pool loads.
6532   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6533        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6534       N0.getNode()->hasOneUse() && VT.isInteger() &&
6535       !VT.isVector() && !N0.getValueType().isVector()) {
6536     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6537                                   N0.getOperand(0));
6538     AddToWorklist(NewConv.getNode());
6539
6540     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6541     if (N0.getOpcode() == ISD::FNEG)
6542       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6543                          NewConv, DAG.getConstant(SignBit, VT));
6544     assert(N0.getOpcode() == ISD::FABS);
6545     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6546                        NewConv, DAG.getConstant(~SignBit, VT));
6547   }
6548
6549   // fold (bitconvert (fcopysign cst, x)) ->
6550   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6551   // Note that we don't handle (copysign x, cst) because this can always be
6552   // folded to an fneg or fabs.
6553   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6554       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6555       VT.isInteger() && !VT.isVector()) {
6556     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6557     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6558     if (isTypeLegal(IntXVT)) {
6559       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6560                               IntXVT, N0.getOperand(1));
6561       AddToWorklist(X.getNode());
6562
6563       // If X has a different width than the result/lhs, sext it or truncate it.
6564       unsigned VTWidth = VT.getSizeInBits();
6565       if (OrigXWidth < VTWidth) {
6566         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6567         AddToWorklist(X.getNode());
6568       } else if (OrigXWidth > VTWidth) {
6569         // To get the sign bit in the right place, we have to shift it right
6570         // before truncating.
6571         X = DAG.getNode(ISD::SRL, SDLoc(X),
6572                         X.getValueType(), X,
6573                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6574         AddToWorklist(X.getNode());
6575         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6576         AddToWorklist(X.getNode());
6577       }
6578
6579       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6580       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6581                       X, DAG.getConstant(SignBit, VT));
6582       AddToWorklist(X.getNode());
6583
6584       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6585                                 VT, N0.getOperand(0));
6586       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6587                         Cst, DAG.getConstant(~SignBit, VT));
6588       AddToWorklist(Cst.getNode());
6589
6590       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6591     }
6592   }
6593
6594   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6595   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6596     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6597     if (CombineLD.getNode())
6598       return CombineLD;
6599   }
6600
6601   return SDValue();
6602 }
6603
6604 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6605   EVT VT = N->getValueType(0);
6606   return CombineConsecutiveLoads(N, VT);
6607 }
6608
6609 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6610 /// operands. DstEltVT indicates the destination element value type.
6611 SDValue DAGCombiner::
6612 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6613   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6614
6615   // If this is already the right type, we're done.
6616   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6617
6618   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6619   unsigned DstBitSize = DstEltVT.getSizeInBits();
6620
6621   // If this is a conversion of N elements of one type to N elements of another
6622   // type, convert each element.  This handles FP<->INT cases.
6623   if (SrcBitSize == DstBitSize) {
6624     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6625                               BV->getValueType(0).getVectorNumElements());
6626
6627     // Due to the FP element handling below calling this routine recursively,
6628     // we can end up with a scalar-to-vector node here.
6629     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6630       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6631                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6632                                      DstEltVT, BV->getOperand(0)));
6633
6634     SmallVector<SDValue, 8> Ops;
6635     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6636       SDValue Op = BV->getOperand(i);
6637       // If the vector element type is not legal, the BUILD_VECTOR operands
6638       // are promoted and implicitly truncated.  Make that explicit here.
6639       if (Op.getValueType() != SrcEltVT)
6640         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6641       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6642                                 DstEltVT, Op));
6643       AddToWorklist(Ops.back().getNode());
6644     }
6645     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6646   }
6647
6648   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6649   // handle annoying details of growing/shrinking FP values, we convert them to
6650   // int first.
6651   if (SrcEltVT.isFloatingPoint()) {
6652     // Convert the input float vector to a int vector where the elements are the
6653     // same sizes.
6654     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6655     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6656     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6657     SrcEltVT = IntVT;
6658   }
6659
6660   // Now we know the input is an integer vector.  If the output is a FP type,
6661   // convert to integer first, then to FP of the right size.
6662   if (DstEltVT.isFloatingPoint()) {
6663     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6664     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6665     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6666
6667     // Next, convert to FP elements of the same size.
6668     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6669   }
6670
6671   // Okay, we know the src/dst types are both integers of differing types.
6672   // Handling growing first.
6673   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6674   if (SrcBitSize < DstBitSize) {
6675     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6676
6677     SmallVector<SDValue, 8> Ops;
6678     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6679          i += NumInputsPerOutput) {
6680       bool isLE = TLI.isLittleEndian();
6681       APInt NewBits = APInt(DstBitSize, 0);
6682       bool EltIsUndef = true;
6683       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6684         // Shift the previously computed bits over.
6685         NewBits <<= SrcBitSize;
6686         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6687         if (Op.getOpcode() == ISD::UNDEF) continue;
6688         EltIsUndef = false;
6689
6690         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6691                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6692       }
6693
6694       if (EltIsUndef)
6695         Ops.push_back(DAG.getUNDEF(DstEltVT));
6696       else
6697         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6698     }
6699
6700     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6701     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6702   }
6703
6704   // Finally, this must be the case where we are shrinking elements: each input
6705   // turns into multiple outputs.
6706   bool isS2V = ISD::isScalarToVector(BV);
6707   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6708   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6709                             NumOutputsPerInput*BV->getNumOperands());
6710   SmallVector<SDValue, 8> Ops;
6711
6712   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6713     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6714       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6715         Ops.push_back(DAG.getUNDEF(DstEltVT));
6716       continue;
6717     }
6718
6719     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6720                   getAPIntValue().zextOrTrunc(SrcBitSize);
6721
6722     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6723       APInt ThisVal = OpVal.trunc(DstBitSize);
6724       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6725       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6726         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6727         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6728                            Ops[0]);
6729       OpVal = OpVal.lshr(DstBitSize);
6730     }
6731
6732     // For big endian targets, swap the order of the pieces of each element.
6733     if (TLI.isBigEndian())
6734       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6735   }
6736
6737   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6738 }
6739
6740 SDValue DAGCombiner::visitFADD(SDNode *N) {
6741   SDValue N0 = N->getOperand(0);
6742   SDValue N1 = N->getOperand(1);
6743   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6744   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6745   EVT VT = N->getValueType(0);
6746   const TargetOptions &Options = DAG.getTarget().Options;
6747
6748   // fold vector ops
6749   if (VT.isVector()) {
6750     SDValue FoldedVOp = SimplifyVBinOp(N);
6751     if (FoldedVOp.getNode()) return FoldedVOp;
6752   }
6753
6754   // fold (fadd c1, c2) -> c1 + c2
6755   if (N0CFP && N1CFP)
6756     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6757
6758   // canonicalize constant to RHS
6759   if (N0CFP && !N1CFP)
6760     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6761
6762   // fold (fadd A, (fneg B)) -> (fsub A, B)
6763   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6764       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6765     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6766                        GetNegatedExpression(N1, DAG, LegalOperations));
6767
6768   // fold (fadd (fneg A), B) -> (fsub B, A)
6769   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6770       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6771     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6772                        GetNegatedExpression(N0, DAG, LegalOperations));
6773
6774   // If 'unsafe math' is enabled, fold lots of things.
6775   if (Options.UnsafeFPMath) {
6776     // No FP constant should be created after legalization as Instruction
6777     // Selection pass has a hard time dealing with FP constants.
6778     bool AllowNewConst = (Level < AfterLegalizeDAG);
6779
6780     // fold (fadd A, 0) -> A
6781     if (N1CFP && N1CFP->getValueAPF().isZero())
6782       return N0;
6783
6784     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6785     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6786         isa<ConstantFPSDNode>(N0.getOperand(1)))
6787       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6788                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6789                                      N0.getOperand(1), N1));
6790
6791     // If allowed, fold (fadd (fneg x), x) -> 0.0
6792     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6793       return DAG.getConstantFP(0.0, VT);
6794
6795     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6796     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6797       return DAG.getConstantFP(0.0, VT);
6798
6799     // We can fold chains of FADD's of the same value into multiplications.
6800     // This transform is not safe in general because we are reducing the number
6801     // of rounding steps.
6802     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6803       if (N0.getOpcode() == ISD::FMUL) {
6804         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6805         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6806
6807         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6808         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6809           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6810                                        SDValue(CFP01, 0),
6811                                        DAG.getConstantFP(1.0, VT));
6812           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6813         }
6814
6815         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6816         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6817             N1.getOperand(0) == N1.getOperand(1) &&
6818             N0.getOperand(0) == N1.getOperand(0)) {
6819           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6820                                        SDValue(CFP01, 0),
6821                                        DAG.getConstantFP(2.0, VT));
6822           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6823                              N0.getOperand(0), NewCFP);
6824         }
6825       }
6826
6827       if (N1.getOpcode() == ISD::FMUL) {
6828         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6829         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6830
6831         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6832         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6833           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6834                                        SDValue(CFP11, 0),
6835                                        DAG.getConstantFP(1.0, VT));
6836           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6837         }
6838
6839         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6840         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6841             N0.getOperand(0) == N0.getOperand(1) &&
6842             N1.getOperand(0) == N0.getOperand(0)) {
6843           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6844                                        SDValue(CFP11, 0),
6845                                        DAG.getConstantFP(2.0, VT));
6846           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6847         }
6848       }
6849
6850       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6851         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6852         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6853         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6854             (N0.getOperand(0) == N1))
6855           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6856                              N1, DAG.getConstantFP(3.0, VT));
6857       }
6858
6859       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6860         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6861         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6862         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6863             N1.getOperand(0) == N0)
6864           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6865                              N0, DAG.getConstantFP(3.0, VT));
6866       }
6867
6868       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6869       if (AllowNewConst &&
6870           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6871           N0.getOperand(0) == N0.getOperand(1) &&
6872           N1.getOperand(0) == N1.getOperand(1) &&
6873           N0.getOperand(0) == N1.getOperand(0))
6874         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6875                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6876     }
6877   } // enable-unsafe-fp-math
6878
6879   // FADD -> FMA combines:
6880   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6881       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6882       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6883
6884     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6885     if (N0.getOpcode() == ISD::FMUL &&
6886         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6887       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6888                          N0.getOperand(0), N0.getOperand(1), N1);
6889
6890     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6891     // Note: Commutes FADD operands.
6892     if (N1.getOpcode() == ISD::FMUL &&
6893         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6894       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6895                          N1.getOperand(0), N1.getOperand(1), N0);
6896   }
6897
6898   return SDValue();
6899 }
6900
6901 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6902   SDValue N0 = N->getOperand(0);
6903   SDValue N1 = N->getOperand(1);
6904   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6905   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6906   EVT VT = N->getValueType(0);
6907   SDLoc dl(N);
6908   const TargetOptions &Options = DAG.getTarget().Options;
6909
6910   // fold vector ops
6911   if (VT.isVector()) {
6912     SDValue FoldedVOp = SimplifyVBinOp(N);
6913     if (FoldedVOp.getNode()) return FoldedVOp;
6914   }
6915
6916   // fold (fsub c1, c2) -> c1-c2
6917   if (N0CFP && N1CFP)
6918     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6919
6920   // fold (fsub A, (fneg B)) -> (fadd A, B)
6921   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6922     return DAG.getNode(ISD::FADD, dl, VT, N0,
6923                        GetNegatedExpression(N1, DAG, LegalOperations));
6924
6925   // If 'unsafe math' is enabled, fold lots of things.
6926   if (Options.UnsafeFPMath) {
6927     // (fsub A, 0) -> A
6928     if (N1CFP && N1CFP->getValueAPF().isZero())
6929       return N0;
6930
6931     // (fsub 0, B) -> -B
6932     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6933       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6934         return GetNegatedExpression(N1, DAG, LegalOperations);
6935       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6936         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6937     }
6938
6939     // (fsub x, x) -> 0.0
6940     if (N0 == N1)
6941       return DAG.getConstantFP(0.0f, VT);
6942
6943     // (fsub x, (fadd x, y)) -> (fneg y)
6944     // (fsub x, (fadd y, x)) -> (fneg y)
6945     if (N1.getOpcode() == ISD::FADD) {
6946       SDValue N10 = N1->getOperand(0);
6947       SDValue N11 = N1->getOperand(1);
6948
6949       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6950         return GetNegatedExpression(N11, DAG, LegalOperations);
6951
6952       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6953         return GetNegatedExpression(N10, DAG, LegalOperations);
6954     }
6955   }
6956
6957   // FSUB -> FMA combines:
6958   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6959       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6960       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6961
6962     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6963     if (N0.getOpcode() == ISD::FMUL &&
6964         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6965       return DAG.getNode(ISD::FMA, dl, VT,
6966                          N0.getOperand(0), N0.getOperand(1),
6967                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6968
6969     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6970     // Note: Commutes FSUB operands.
6971     if (N1.getOpcode() == ISD::FMUL &&
6972         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6973       return DAG.getNode(ISD::FMA, dl, VT,
6974                          DAG.getNode(ISD::FNEG, dl, VT,
6975                          N1.getOperand(0)),
6976                          N1.getOperand(1), N0);
6977
6978     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6979     if (N0.getOpcode() == ISD::FNEG &&
6980         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6981         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6982             TLI.enableAggressiveFMAFusion(VT))) {
6983       SDValue N00 = N0.getOperand(0).getOperand(0);
6984       SDValue N01 = N0.getOperand(0).getOperand(1);
6985       return DAG.getNode(ISD::FMA, dl, VT,
6986                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6987                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6988     }
6989   }
6990
6991   return SDValue();
6992 }
6993
6994 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6995   SDValue N0 = N->getOperand(0);
6996   SDValue N1 = N->getOperand(1);
6997   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6998   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6999   EVT VT = N->getValueType(0);
7000   const TargetOptions &Options = DAG.getTarget().Options;
7001
7002   // fold vector ops
7003   if (VT.isVector()) {
7004     // This just handles C1 * C2 for vectors. Other vector folds are below.
7005     SDValue FoldedVOp = SimplifyVBinOp(N);
7006     if (FoldedVOp.getNode())
7007       return FoldedVOp;
7008     // Canonicalize vector constant to RHS.
7009     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
7010         N1.getOpcode() != ISD::BUILD_VECTOR)
7011       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
7012         if (BV0->isConstant())
7013           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
7014   }
7015
7016   // fold (fmul c1, c2) -> c1*c2
7017   if (N0CFP && N1CFP)
7018     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
7019
7020   // canonicalize constant to RHS
7021   if (N0CFP && !N1CFP)
7022     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
7023
7024   // fold (fmul A, 1.0) -> A
7025   if (N1CFP && N1CFP->isExactlyValue(1.0))
7026     return N0;
7027
7028   if (Options.UnsafeFPMath) {
7029     // fold (fmul A, 0) -> 0
7030     if (N1CFP && N1CFP->getValueAPF().isZero())
7031       return N1;
7032
7033     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
7034     if (N0.getOpcode() == ISD::FMUL) {
7035       // Fold scalars or any vector constants (not just splats).
7036       // This fold is done in general by InstCombine, but extra fmul insts
7037       // may have been generated during lowering.
7038       SDValue N01 = N0.getOperand(1);
7039       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
7040       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
7041       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
7042           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
7043         SDLoc SL(N);
7044         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
7045         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
7046       }
7047     }
7048
7049     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
7050     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
7051     // during an early run of DAGCombiner can prevent folding with fmuls
7052     // inserted during lowering.
7053     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
7054       SDLoc SL(N);
7055       const SDValue Two = DAG.getConstantFP(2.0, VT);
7056       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
7057       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
7058     }
7059   }
7060
7061   // fold (fmul X, 2.0) -> (fadd X, X)
7062   if (N1CFP && N1CFP->isExactlyValue(+2.0))
7063     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
7064
7065   // fold (fmul X, -1.0) -> (fneg X)
7066   if (N1CFP && N1CFP->isExactlyValue(-1.0))
7067     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7068       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
7069
7070   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
7071   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7072     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7073       // Both can be negated for free, check to see if at least one is cheaper
7074       // negated.
7075       if (LHSNeg == 2 || RHSNeg == 2)
7076         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
7077                            GetNegatedExpression(N0, DAG, LegalOperations),
7078                            GetNegatedExpression(N1, DAG, LegalOperations));
7079     }
7080   }
7081
7082   return SDValue();
7083 }
7084
7085 SDValue DAGCombiner::visitFMA(SDNode *N) {
7086   SDValue N0 = N->getOperand(0);
7087   SDValue N1 = N->getOperand(1);
7088   SDValue N2 = N->getOperand(2);
7089   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7090   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7091   EVT VT = N->getValueType(0);
7092   SDLoc dl(N);
7093   const TargetOptions &Options = DAG.getTarget().Options;
7094
7095   // Constant fold FMA.
7096   if (isa<ConstantFPSDNode>(N0) &&
7097       isa<ConstantFPSDNode>(N1) &&
7098       isa<ConstantFPSDNode>(N2)) {
7099     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
7100   }
7101
7102   if (Options.UnsafeFPMath) {
7103     if (N0CFP && N0CFP->isZero())
7104       return N2;
7105     if (N1CFP && N1CFP->isZero())
7106       return N2;
7107   }
7108   if (N0CFP && N0CFP->isExactlyValue(1.0))
7109     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
7110   if (N1CFP && N1CFP->isExactlyValue(1.0))
7111     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
7112
7113   // Canonicalize (fma c, x, y) -> (fma x, c, y)
7114   if (N0CFP && !N1CFP)
7115     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
7116
7117   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
7118   if (Options.UnsafeFPMath && N1CFP &&
7119       N2.getOpcode() == ISD::FMUL &&
7120       N0 == N2.getOperand(0) &&
7121       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
7122     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7123                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
7124   }
7125
7126
7127   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
7128   if (Options.UnsafeFPMath &&
7129       N0.getOpcode() == ISD::FMUL && N1CFP &&
7130       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
7131     return DAG.getNode(ISD::FMA, dl, VT,
7132                        N0.getOperand(0),
7133                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
7134                        N2);
7135   }
7136
7137   // (fma x, 1, y) -> (fadd x, y)
7138   // (fma x, -1, y) -> (fadd (fneg x), y)
7139   if (N1CFP) {
7140     if (N1CFP->isExactlyValue(1.0))
7141       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
7142
7143     if (N1CFP->isExactlyValue(-1.0) &&
7144         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
7145       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
7146       AddToWorklist(RHSNeg.getNode());
7147       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
7148     }
7149   }
7150
7151   // (fma x, c, x) -> (fmul x, (c+1))
7152   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
7153     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7154                        DAG.getNode(ISD::FADD, dl, VT,
7155                                    N1, DAG.getConstantFP(1.0, VT)));
7156
7157   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
7158   if (Options.UnsafeFPMath && N1CFP &&
7159       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
7160     return DAG.getNode(ISD::FMUL, dl, VT, N0,
7161                        DAG.getNode(ISD::FADD, dl, VT,
7162                                    N1, DAG.getConstantFP(-1.0, VT)));
7163
7164
7165   return SDValue();
7166 }
7167
7168 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7169   SDValue N0 = N->getOperand(0);
7170   SDValue N1 = N->getOperand(1);
7171   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7172   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7173   EVT VT = N->getValueType(0);
7174   SDLoc DL(N);
7175   const TargetOptions &Options = DAG.getTarget().Options;
7176
7177   // fold vector ops
7178   if (VT.isVector()) {
7179     SDValue FoldedVOp = SimplifyVBinOp(N);
7180     if (FoldedVOp.getNode()) return FoldedVOp;
7181   }
7182
7183   // fold (fdiv c1, c2) -> c1/c2
7184   if (N0CFP && N1CFP)
7185     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7186
7187   if (Options.UnsafeFPMath) {
7188     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7189     if (N1CFP) {
7190       // Compute the reciprocal 1.0 / c2.
7191       APFloat N1APF = N1CFP->getValueAPF();
7192       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7193       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7194       // Only do the transform if the reciprocal is a legal fp immediate that
7195       // isn't too nasty (eg NaN, denormal, ...).
7196       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7197           (!LegalOperations ||
7198            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7199            // backend)... we should handle this gracefully after Legalize.
7200            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7201            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7202            TLI.isFPImmLegal(Recip, VT)))
7203         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7204                            DAG.getConstantFP(Recip, VT));
7205     }
7206
7207     // If this FDIV is part of a reciprocal square root, it may be folded
7208     // into a target-specific square root estimate instruction.
7209     if (N1.getOpcode() == ISD::FSQRT) {
7210       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7211         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7212       }
7213     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7214                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7215       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7216         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7217         AddToWorklist(RV.getNode());
7218         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7219       }
7220     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7221                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7222       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7223         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7224         AddToWorklist(RV.getNode());
7225         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7226       }
7227     } else if (N1.getOpcode() == ISD::FMUL) {
7228       // Look through an FMUL. Even though this won't remove the FDIV directly,
7229       // it's still worthwhile to get rid of the FSQRT if possible.
7230       SDValue SqrtOp;
7231       SDValue OtherOp;
7232       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7233         SqrtOp = N1.getOperand(0);
7234         OtherOp = N1.getOperand(1);
7235       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7236         SqrtOp = N1.getOperand(1);
7237         OtherOp = N1.getOperand(0);
7238       }
7239       if (SqrtOp.getNode()) {
7240         // We found a FSQRT, so try to make this fold:
7241         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7242         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7243           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7244           AddToWorklist(RV.getNode());
7245           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7246         }
7247       }
7248     }
7249
7250     // Fold into a reciprocal estimate and multiply instead of a real divide.
7251     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7252       AddToWorklist(RV.getNode());
7253       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7254     }
7255   }
7256
7257   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7258   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7259     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7260       // Both can be negated for free, check to see if at least one is cheaper
7261       // negated.
7262       if (LHSNeg == 2 || RHSNeg == 2)
7263         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7264                            GetNegatedExpression(N0, DAG, LegalOperations),
7265                            GetNegatedExpression(N1, DAG, LegalOperations));
7266     }
7267   }
7268
7269   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7270   // reciprocal.
7271   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7272   // Notice that this is not always beneficial. One reason is different target
7273   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7274   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7275   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7276   if (Options.UnsafeFPMath) {
7277     // Skip if current node is a reciprocal.
7278     if (N0CFP && N0CFP->isExactlyValue(1.0))
7279       return SDValue();
7280
7281     SmallVector<SDNode *, 4> Users;
7282     // Find all FDIV users of the same divisor.
7283     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7284                               UE = N1.getNode()->use_end();
7285          UI != UE; ++UI) {
7286       SDNode *User = UI.getUse().getUser();
7287       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7288         Users.push_back(User);
7289     }
7290
7291     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7292       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7293       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7294
7295       // Dividend / Divisor -> Dividend * Reciprocal
7296       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7297         if ((*I)->getOperand(0) != FPOne) {
7298           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7299                                         (*I)->getOperand(0), Reciprocal);
7300           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7301         }
7302       }
7303       return SDValue();
7304     }
7305   }
7306
7307   return SDValue();
7308 }
7309
7310 SDValue DAGCombiner::visitFREM(SDNode *N) {
7311   SDValue N0 = N->getOperand(0);
7312   SDValue N1 = N->getOperand(1);
7313   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7314   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7315   EVT VT = N->getValueType(0);
7316
7317   // fold (frem c1, c2) -> fmod(c1,c2)
7318   if (N0CFP && N1CFP)
7319     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7320
7321   return SDValue();
7322 }
7323
7324 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7325   if (DAG.getTarget().Options.UnsafeFPMath) {
7326     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7327     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7328       EVT VT = RV.getValueType();
7329       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7330       AddToWorklist(RV.getNode());
7331
7332       // Unfortunately, RV is now NaN if the input was exactly 0.
7333       // Select out this case and force the answer to 0.
7334       SDValue Zero = DAG.getConstantFP(0.0, VT);
7335       SDValue ZeroCmp =
7336         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7337                      N->getOperand(0), Zero, ISD::SETEQ);
7338       AddToWorklist(ZeroCmp.getNode());
7339       AddToWorklist(RV.getNode());
7340
7341       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7342                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7343       return RV;
7344     }
7345   }
7346   return SDValue();
7347 }
7348
7349 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7350   SDValue N0 = N->getOperand(0);
7351   SDValue N1 = N->getOperand(1);
7352   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7353   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7354   EVT VT = N->getValueType(0);
7355
7356   if (N0CFP && N1CFP)  // Constant fold
7357     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7358
7359   if (N1CFP) {
7360     const APFloat& V = N1CFP->getValueAPF();
7361     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7362     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7363     if (!V.isNegative()) {
7364       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7365         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7366     } else {
7367       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7368         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7369                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7370     }
7371   }
7372
7373   // copysign(fabs(x), y) -> copysign(x, y)
7374   // copysign(fneg(x), y) -> copysign(x, y)
7375   // copysign(copysign(x,z), y) -> copysign(x, y)
7376   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7377       N0.getOpcode() == ISD::FCOPYSIGN)
7378     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7379                        N0.getOperand(0), N1);
7380
7381   // copysign(x, abs(y)) -> abs(x)
7382   if (N1.getOpcode() == ISD::FABS)
7383     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7384
7385   // copysign(x, copysign(y,z)) -> copysign(x, z)
7386   if (N1.getOpcode() == ISD::FCOPYSIGN)
7387     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7388                        N0, N1.getOperand(1));
7389
7390   // copysign(x, fp_extend(y)) -> copysign(x, y)
7391   // copysign(x, fp_round(y)) -> copysign(x, y)
7392   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7393     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7394                        N0, N1.getOperand(0));
7395
7396   return SDValue();
7397 }
7398
7399 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7400   SDValue N0 = N->getOperand(0);
7401   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7402   EVT VT = N->getValueType(0);
7403   EVT OpVT = N0.getValueType();
7404
7405   // fold (sint_to_fp c1) -> c1fp
7406   if (N0C &&
7407       // ...but only if the target supports immediate floating-point values
7408       (!LegalOperations ||
7409        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7410     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7411
7412   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7413   // but UINT_TO_FP is legal on this target, try to convert.
7414   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7415       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7416     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7417     if (DAG.SignBitIsZero(N0))
7418       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7419   }
7420
7421   // The next optimizations are desirable only if SELECT_CC can be lowered.
7422   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7423     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7424     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7425         !VT.isVector() &&
7426         (!LegalOperations ||
7427          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7428       SDValue Ops[] =
7429         { N0.getOperand(0), N0.getOperand(1),
7430           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7431           N0.getOperand(2) };
7432       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7433     }
7434
7435     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7436     //      (select_cc x, y, 1.0, 0.0,, cc)
7437     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7438         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7439         (!LegalOperations ||
7440          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7441       SDValue Ops[] =
7442         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7443           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7444           N0.getOperand(0).getOperand(2) };
7445       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7446     }
7447   }
7448
7449   return SDValue();
7450 }
7451
7452 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7453   SDValue N0 = N->getOperand(0);
7454   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7455   EVT VT = N->getValueType(0);
7456   EVT OpVT = N0.getValueType();
7457
7458   // fold (uint_to_fp c1) -> c1fp
7459   if (N0C &&
7460       // ...but only if the target supports immediate floating-point values
7461       (!LegalOperations ||
7462        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7463     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7464
7465   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7466   // but SINT_TO_FP is legal on this target, try to convert.
7467   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7468       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7469     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7470     if (DAG.SignBitIsZero(N0))
7471       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7472   }
7473
7474   // The next optimizations are desirable only if SELECT_CC can be lowered.
7475   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7476     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7477
7478     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7479         (!LegalOperations ||
7480          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7481       SDValue Ops[] =
7482         { N0.getOperand(0), N0.getOperand(1),
7483           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7484           N0.getOperand(2) };
7485       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7486     }
7487   }
7488
7489   return SDValue();
7490 }
7491
7492 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7493   SDValue N0 = N->getOperand(0);
7494   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7495   EVT VT = N->getValueType(0);
7496
7497   // fold (fp_to_sint c1fp) -> c1
7498   if (N0CFP)
7499     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7500
7501   return SDValue();
7502 }
7503
7504 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7505   SDValue N0 = N->getOperand(0);
7506   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7507   EVT VT = N->getValueType(0);
7508
7509   // fold (fp_to_uint c1fp) -> c1
7510   if (N0CFP)
7511     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7512
7513   return SDValue();
7514 }
7515
7516 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7517   SDValue N0 = N->getOperand(0);
7518   SDValue N1 = N->getOperand(1);
7519   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7520   EVT VT = N->getValueType(0);
7521
7522   // fold (fp_round c1fp) -> c1fp
7523   if (N0CFP)
7524     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7525
7526   // fold (fp_round (fp_extend x)) -> x
7527   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7528     return N0.getOperand(0);
7529
7530   // fold (fp_round (fp_round x)) -> (fp_round x)
7531   if (N0.getOpcode() == ISD::FP_ROUND) {
7532     // This is a value preserving truncation if both round's are.
7533     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7534                    N0.getNode()->getConstantOperandVal(1) == 1;
7535     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7536                        DAG.getIntPtrConstant(IsTrunc));
7537   }
7538
7539   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7540   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7541     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7542                               N0.getOperand(0), N1);
7543     AddToWorklist(Tmp.getNode());
7544     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7545                        Tmp, N0.getOperand(1));
7546   }
7547
7548   return SDValue();
7549 }
7550
7551 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7552   SDValue N0 = N->getOperand(0);
7553   EVT VT = N->getValueType(0);
7554   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7555   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7556
7557   // fold (fp_round_inreg c1fp) -> c1fp
7558   if (N0CFP && isTypeLegal(EVT)) {
7559     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7560     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7561   }
7562
7563   return SDValue();
7564 }
7565
7566 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7567   SDValue N0 = N->getOperand(0);
7568   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7569   EVT VT = N->getValueType(0);
7570
7571   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7572   if (N->hasOneUse() &&
7573       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7574     return SDValue();
7575
7576   // fold (fp_extend c1fp) -> c1fp
7577   if (N0CFP)
7578     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7579
7580   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7581   // value of X.
7582   if (N0.getOpcode() == ISD::FP_ROUND
7583       && N0.getNode()->getConstantOperandVal(1) == 1) {
7584     SDValue In = N0.getOperand(0);
7585     if (In.getValueType() == VT) return In;
7586     if (VT.bitsLT(In.getValueType()))
7587       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7588                          In, N0.getOperand(1));
7589     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7590   }
7591
7592   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7593   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7594        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7595     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7596     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7597                                      LN0->getChain(),
7598                                      LN0->getBasePtr(), N0.getValueType(),
7599                                      LN0->getMemOperand());
7600     CombineTo(N, ExtLoad);
7601     CombineTo(N0.getNode(),
7602               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7603                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7604               ExtLoad.getValue(1));
7605     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7606   }
7607
7608   return SDValue();
7609 }
7610
7611 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7612   SDValue N0 = N->getOperand(0);
7613   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7614   EVT VT = N->getValueType(0);
7615
7616   // fold (fceil c1) -> fceil(c1)
7617   if (N0CFP)
7618     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7619
7620   return SDValue();
7621 }
7622
7623 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7624   SDValue N0 = N->getOperand(0);
7625   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7626   EVT VT = N->getValueType(0);
7627
7628   // fold (ftrunc c1) -> ftrunc(c1)
7629   if (N0CFP)
7630     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7631
7632   return SDValue();
7633 }
7634
7635 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7636   SDValue N0 = N->getOperand(0);
7637   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7638   EVT VT = N->getValueType(0);
7639
7640   // fold (ffloor c1) -> ffloor(c1)
7641   if (N0CFP)
7642     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7643
7644   return SDValue();
7645 }
7646
7647 // FIXME: FNEG and FABS have a lot in common; refactor.
7648 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7649   SDValue N0 = N->getOperand(0);
7650   EVT VT = N->getValueType(0);
7651
7652   if (VT.isVector()) {
7653     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7654     if (FoldedVOp.getNode()) return FoldedVOp;
7655   }
7656
7657   // Constant fold FNEG.
7658   if (isa<ConstantFPSDNode>(N0))
7659     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7660
7661   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7662                          &DAG.getTarget().Options))
7663     return GetNegatedExpression(N0, DAG, LegalOperations);
7664
7665   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7666   // constant pool values.
7667   if (!TLI.isFNegFree(VT) &&
7668       N0.getOpcode() == ISD::BITCAST &&
7669       N0.getNode()->hasOneUse()) {
7670     SDValue Int = N0.getOperand(0);
7671     EVT IntVT = Int.getValueType();
7672     if (IntVT.isInteger() && !IntVT.isVector()) {
7673       APInt SignMask;
7674       if (N0.getValueType().isVector()) {
7675         // For a vector, get a mask such as 0x80... per scalar element
7676         // and splat it.
7677         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7678         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7679       } else {
7680         // For a scalar, just generate 0x80...
7681         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7682       }
7683       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7684                         DAG.getConstant(SignMask, IntVT));
7685       AddToWorklist(Int.getNode());
7686       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7687     }
7688   }
7689
7690   // (fneg (fmul c, x)) -> (fmul -c, x)
7691   if (N0.getOpcode() == ISD::FMUL) {
7692     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7693     if (CFP1) {
7694       APFloat CVal = CFP1->getValueAPF();
7695       CVal.changeSign();
7696       if (Level >= AfterLegalizeDAG &&
7697           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7698            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7699         return DAG.getNode(
7700             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7701             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7702     }
7703   }
7704
7705   return SDValue();
7706 }
7707
7708 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7709   SDValue N0 = N->getOperand(0);
7710   SDValue N1 = N->getOperand(1);
7711   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7712   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7713
7714   if (N0CFP && N1CFP) {
7715     const APFloat &C0 = N0CFP->getValueAPF();
7716     const APFloat &C1 = N1CFP->getValueAPF();
7717     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7718   }
7719
7720   if (N0CFP) {
7721     EVT VT = N->getValueType(0);
7722     // Canonicalize to constant on RHS.
7723     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7724   }
7725
7726   return SDValue();
7727 }
7728
7729 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7730   SDValue N0 = N->getOperand(0);
7731   SDValue N1 = N->getOperand(1);
7732   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7733   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7734
7735   if (N0CFP && N1CFP) {
7736     const APFloat &C0 = N0CFP->getValueAPF();
7737     const APFloat &C1 = N1CFP->getValueAPF();
7738     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7739   }
7740
7741   if (N0CFP) {
7742     EVT VT = N->getValueType(0);
7743     // Canonicalize to constant on RHS.
7744     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7745   }
7746
7747   return SDValue();
7748 }
7749
7750 SDValue DAGCombiner::visitFABS(SDNode *N) {
7751   SDValue N0 = N->getOperand(0);
7752   EVT VT = N->getValueType(0);
7753
7754   if (VT.isVector()) {
7755     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7756     if (FoldedVOp.getNode()) return FoldedVOp;
7757   }
7758
7759   // fold (fabs c1) -> fabs(c1)
7760   if (isa<ConstantFPSDNode>(N0))
7761     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7762
7763   // fold (fabs (fabs x)) -> (fabs x)
7764   if (N0.getOpcode() == ISD::FABS)
7765     return N->getOperand(0);
7766
7767   // fold (fabs (fneg x)) -> (fabs x)
7768   // fold (fabs (fcopysign x, y)) -> (fabs x)
7769   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7770     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7771
7772   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7773   // constant pool values.
7774   if (!TLI.isFAbsFree(VT) &&
7775       N0.getOpcode() == ISD::BITCAST &&
7776       N0.getNode()->hasOneUse()) {
7777     SDValue Int = N0.getOperand(0);
7778     EVT IntVT = Int.getValueType();
7779     if (IntVT.isInteger() && !IntVT.isVector()) {
7780       APInt SignMask;
7781       if (N0.getValueType().isVector()) {
7782         // For a vector, get a mask such as 0x7f... per scalar element
7783         // and splat it.
7784         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7785         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7786       } else {
7787         // For a scalar, just generate 0x7f...
7788         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7789       }
7790       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7791                         DAG.getConstant(SignMask, IntVT));
7792       AddToWorklist(Int.getNode());
7793       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7794     }
7795   }
7796
7797   return SDValue();
7798 }
7799
7800 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7801   SDValue Chain = N->getOperand(0);
7802   SDValue N1 = N->getOperand(1);
7803   SDValue N2 = N->getOperand(2);
7804
7805   // If N is a constant we could fold this into a fallthrough or unconditional
7806   // branch. However that doesn't happen very often in normal code, because
7807   // Instcombine/SimplifyCFG should have handled the available opportunities.
7808   // If we did this folding here, it would be necessary to update the
7809   // MachineBasicBlock CFG, which is awkward.
7810
7811   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7812   // on the target.
7813   if (N1.getOpcode() == ISD::SETCC &&
7814       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7815                                    N1.getOperand(0).getValueType())) {
7816     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7817                        Chain, N1.getOperand(2),
7818                        N1.getOperand(0), N1.getOperand(1), N2);
7819   }
7820
7821   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7822       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7823        (N1.getOperand(0).hasOneUse() &&
7824         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7825     SDNode *Trunc = nullptr;
7826     if (N1.getOpcode() == ISD::TRUNCATE) {
7827       // Look pass the truncate.
7828       Trunc = N1.getNode();
7829       N1 = N1.getOperand(0);
7830     }
7831
7832     // Match this pattern so that we can generate simpler code:
7833     //
7834     //   %a = ...
7835     //   %b = and i32 %a, 2
7836     //   %c = srl i32 %b, 1
7837     //   brcond i32 %c ...
7838     //
7839     // into
7840     //
7841     //   %a = ...
7842     //   %b = and i32 %a, 2
7843     //   %c = setcc eq %b, 0
7844     //   brcond %c ...
7845     //
7846     // This applies only when the AND constant value has one bit set and the
7847     // SRL constant is equal to the log2 of the AND constant. The back-end is
7848     // smart enough to convert the result into a TEST/JMP sequence.
7849     SDValue Op0 = N1.getOperand(0);
7850     SDValue Op1 = N1.getOperand(1);
7851
7852     if (Op0.getOpcode() == ISD::AND &&
7853         Op1.getOpcode() == ISD::Constant) {
7854       SDValue AndOp1 = Op0.getOperand(1);
7855
7856       if (AndOp1.getOpcode() == ISD::Constant) {
7857         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7858
7859         if (AndConst.isPowerOf2() &&
7860             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7861           SDValue SetCC =
7862             DAG.getSetCC(SDLoc(N),
7863                          getSetCCResultType(Op0.getValueType()),
7864                          Op0, DAG.getConstant(0, Op0.getValueType()),
7865                          ISD::SETNE);
7866
7867           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7868                                           MVT::Other, Chain, SetCC, N2);
7869           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7870           // will convert it back to (X & C1) >> C2.
7871           CombineTo(N, NewBRCond, false);
7872           // Truncate is dead.
7873           if (Trunc)
7874             deleteAndRecombine(Trunc);
7875           // Replace the uses of SRL with SETCC
7876           WorklistRemover DeadNodes(*this);
7877           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7878           deleteAndRecombine(N1.getNode());
7879           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7880         }
7881       }
7882     }
7883
7884     if (Trunc)
7885       // Restore N1 if the above transformation doesn't match.
7886       N1 = N->getOperand(1);
7887   }
7888
7889   // Transform br(xor(x, y)) -> br(x != y)
7890   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7891   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7892     SDNode *TheXor = N1.getNode();
7893     SDValue Op0 = TheXor->getOperand(0);
7894     SDValue Op1 = TheXor->getOperand(1);
7895     if (Op0.getOpcode() == Op1.getOpcode()) {
7896       // Avoid missing important xor optimizations.
7897       SDValue Tmp = visitXOR(TheXor);
7898       if (Tmp.getNode()) {
7899         if (Tmp.getNode() != TheXor) {
7900           DEBUG(dbgs() << "\nReplacing.8 ";
7901                 TheXor->dump(&DAG);
7902                 dbgs() << "\nWith: ";
7903                 Tmp.getNode()->dump(&DAG);
7904                 dbgs() << '\n');
7905           WorklistRemover DeadNodes(*this);
7906           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7907           deleteAndRecombine(TheXor);
7908           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7909                              MVT::Other, Chain, Tmp, N2);
7910         }
7911
7912         // visitXOR has changed XOR's operands or replaced the XOR completely,
7913         // bail out.
7914         return SDValue(N, 0);
7915       }
7916     }
7917
7918     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7919       bool Equal = false;
7920       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7921         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7922             Op0.getOpcode() == ISD::XOR) {
7923           TheXor = Op0.getNode();
7924           Equal = true;
7925         }
7926
7927       EVT SetCCVT = N1.getValueType();
7928       if (LegalTypes)
7929         SetCCVT = getSetCCResultType(SetCCVT);
7930       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7931                                    SetCCVT,
7932                                    Op0, Op1,
7933                                    Equal ? ISD::SETEQ : ISD::SETNE);
7934       // Replace the uses of XOR with SETCC
7935       WorklistRemover DeadNodes(*this);
7936       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7937       deleteAndRecombine(N1.getNode());
7938       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7939                          MVT::Other, Chain, SetCC, N2);
7940     }
7941   }
7942
7943   return SDValue();
7944 }
7945
7946 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7947 //
7948 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7949   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7950   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7951
7952   // If N is a constant we could fold this into a fallthrough or unconditional
7953   // branch. However that doesn't happen very often in normal code, because
7954   // Instcombine/SimplifyCFG should have handled the available opportunities.
7955   // If we did this folding here, it would be necessary to update the
7956   // MachineBasicBlock CFG, which is awkward.
7957
7958   // Use SimplifySetCC to simplify SETCC's.
7959   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7960                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7961                                false);
7962   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7963
7964   // fold to a simpler setcc
7965   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7966     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7967                        N->getOperand(0), Simp.getOperand(2),
7968                        Simp.getOperand(0), Simp.getOperand(1),
7969                        N->getOperand(4));
7970
7971   return SDValue();
7972 }
7973
7974 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7975 /// and that N may be folded in the load / store addressing mode.
7976 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7977                                     SelectionDAG &DAG,
7978                                     const TargetLowering &TLI) {
7979   EVT VT;
7980   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7981     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7982       return false;
7983     VT = Use->getValueType(0);
7984   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7985     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7986       return false;
7987     VT = ST->getValue().getValueType();
7988   } else
7989     return false;
7990
7991   TargetLowering::AddrMode AM;
7992   if (N->getOpcode() == ISD::ADD) {
7993     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7994     if (Offset)
7995       // [reg +/- imm]
7996       AM.BaseOffs = Offset->getSExtValue();
7997     else
7998       // [reg +/- reg]
7999       AM.Scale = 1;
8000   } else if (N->getOpcode() == ISD::SUB) {
8001     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
8002     if (Offset)
8003       // [reg +/- imm]
8004       AM.BaseOffs = -Offset->getSExtValue();
8005     else
8006       // [reg +/- reg]
8007       AM.Scale = 1;
8008   } else
8009     return false;
8010
8011   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
8012 }
8013
8014 /// Try turning a load/store into a pre-indexed load/store when the base
8015 /// pointer is an add or subtract and it has other uses besides the load/store.
8016 /// After the transformation, the new indexed load/store has effectively folded
8017 /// the add/subtract in and all of its other uses are redirected to the
8018 /// new load/store.
8019 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
8020   if (Level < AfterLegalizeDAG)
8021     return false;
8022
8023   bool isLoad = true;
8024   SDValue Ptr;
8025   EVT VT;
8026   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8027     if (LD->isIndexed())
8028       return false;
8029     VT = LD->getMemoryVT();
8030     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
8031         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
8032       return false;
8033     Ptr = LD->getBasePtr();
8034   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8035     if (ST->isIndexed())
8036       return false;
8037     VT = ST->getMemoryVT();
8038     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
8039         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
8040       return false;
8041     Ptr = ST->getBasePtr();
8042     isLoad = false;
8043   } else {
8044     return false;
8045   }
8046
8047   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
8048   // out.  There is no reason to make this a preinc/predec.
8049   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
8050       Ptr.getNode()->hasOneUse())
8051     return false;
8052
8053   // Ask the target to do addressing mode selection.
8054   SDValue BasePtr;
8055   SDValue Offset;
8056   ISD::MemIndexedMode AM = ISD::UNINDEXED;
8057   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
8058     return false;
8059
8060   // Backends without true r+i pre-indexed forms may need to pass a
8061   // constant base with a variable offset so that constant coercion
8062   // will work with the patterns in canonical form.
8063   bool Swapped = false;
8064   if (isa<ConstantSDNode>(BasePtr)) {
8065     std::swap(BasePtr, Offset);
8066     Swapped = true;
8067   }
8068
8069   // Don't create a indexed load / store with zero offset.
8070   if (isa<ConstantSDNode>(Offset) &&
8071       cast<ConstantSDNode>(Offset)->isNullValue())
8072     return false;
8073
8074   // Try turning it into a pre-indexed load / store except when:
8075   // 1) The new base ptr is a frame index.
8076   // 2) If N is a store and the new base ptr is either the same as or is a
8077   //    predecessor of the value being stored.
8078   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
8079   //    that would create a cycle.
8080   // 4) All uses are load / store ops that use it as old base ptr.
8081
8082   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
8083   // (plus the implicit offset) to a register to preinc anyway.
8084   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8085     return false;
8086
8087   // Check #2.
8088   if (!isLoad) {
8089     SDValue Val = cast<StoreSDNode>(N)->getValue();
8090     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
8091       return false;
8092   }
8093
8094   // If the offset is a constant, there may be other adds of constants that
8095   // can be folded with this one. We should do this to avoid having to keep
8096   // a copy of the original base pointer.
8097   SmallVector<SDNode *, 16> OtherUses;
8098   if (isa<ConstantSDNode>(Offset))
8099     for (SDNode *Use : BasePtr.getNode()->uses()) {
8100       if (Use == Ptr.getNode())
8101         continue;
8102
8103       if (Use->isPredecessorOf(N))
8104         continue;
8105
8106       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
8107         OtherUses.clear();
8108         break;
8109       }
8110
8111       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
8112       if (Op1.getNode() == BasePtr.getNode())
8113         std::swap(Op0, Op1);
8114       assert(Op0.getNode() == BasePtr.getNode() &&
8115              "Use of ADD/SUB but not an operand");
8116
8117       if (!isa<ConstantSDNode>(Op1)) {
8118         OtherUses.clear();
8119         break;
8120       }
8121
8122       // FIXME: In some cases, we can be smarter about this.
8123       if (Op1.getValueType() != Offset.getValueType()) {
8124         OtherUses.clear();
8125         break;
8126       }
8127
8128       OtherUses.push_back(Use);
8129     }
8130
8131   if (Swapped)
8132     std::swap(BasePtr, Offset);
8133
8134   // Now check for #3 and #4.
8135   bool RealUse = false;
8136
8137   // Caches for hasPredecessorHelper
8138   SmallPtrSet<const SDNode *, 32> Visited;
8139   SmallVector<const SDNode *, 16> Worklist;
8140
8141   for (SDNode *Use : Ptr.getNode()->uses()) {
8142     if (Use == N)
8143       continue;
8144     if (N->hasPredecessorHelper(Use, Visited, Worklist))
8145       return false;
8146
8147     // If Ptr may be folded in addressing mode of other use, then it's
8148     // not profitable to do this transformation.
8149     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
8150       RealUse = true;
8151   }
8152
8153   if (!RealUse)
8154     return false;
8155
8156   SDValue Result;
8157   if (isLoad)
8158     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8159                                 BasePtr, Offset, AM);
8160   else
8161     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8162                                  BasePtr, Offset, AM);
8163   ++PreIndexedNodes;
8164   ++NodesCombined;
8165   DEBUG(dbgs() << "\nReplacing.4 ";
8166         N->dump(&DAG);
8167         dbgs() << "\nWith: ";
8168         Result.getNode()->dump(&DAG);
8169         dbgs() << '\n');
8170   WorklistRemover DeadNodes(*this);
8171   if (isLoad) {
8172     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8173     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8174   } else {
8175     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8176   }
8177
8178   // Finally, since the node is now dead, remove it from the graph.
8179   deleteAndRecombine(N);
8180
8181   if (Swapped)
8182     std::swap(BasePtr, Offset);
8183
8184   // Replace other uses of BasePtr that can be updated to use Ptr
8185   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8186     unsigned OffsetIdx = 1;
8187     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8188       OffsetIdx = 0;
8189     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8190            BasePtr.getNode() && "Expected BasePtr operand");
8191
8192     // We need to replace ptr0 in the following expression:
8193     //   x0 * offset0 + y0 * ptr0 = t0
8194     // knowing that
8195     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8196     //
8197     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8198     // indexed load/store and the expresion that needs to be re-written.
8199     //
8200     // Therefore, we have:
8201     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8202
8203     ConstantSDNode *CN =
8204       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8205     int X0, X1, Y0, Y1;
8206     APInt Offset0 = CN->getAPIntValue();
8207     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8208
8209     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8210     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8211     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8212     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8213
8214     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8215
8216     APInt CNV = Offset0;
8217     if (X0 < 0) CNV = -CNV;
8218     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8219     else CNV = CNV - Offset1;
8220
8221     // We can now generate the new expression.
8222     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8223     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8224
8225     SDValue NewUse = DAG.getNode(Opcode,
8226                                  SDLoc(OtherUses[i]),
8227                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8228     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8229     deleteAndRecombine(OtherUses[i]);
8230   }
8231
8232   // Replace the uses of Ptr with uses of the updated base value.
8233   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8234   deleteAndRecombine(Ptr.getNode());
8235
8236   return true;
8237 }
8238
8239 /// Try to combine a load/store with a add/sub of the base pointer node into a
8240 /// post-indexed load/store. The transformation folded the add/subtract into the
8241 /// new indexed load/store effectively and all of its uses are redirected to the
8242 /// new load/store.
8243 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8244   if (Level < AfterLegalizeDAG)
8245     return false;
8246
8247   bool isLoad = true;
8248   SDValue Ptr;
8249   EVT VT;
8250   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8251     if (LD->isIndexed())
8252       return false;
8253     VT = LD->getMemoryVT();
8254     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8255         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8256       return false;
8257     Ptr = LD->getBasePtr();
8258   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8259     if (ST->isIndexed())
8260       return false;
8261     VT = ST->getMemoryVT();
8262     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8263         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8264       return false;
8265     Ptr = ST->getBasePtr();
8266     isLoad = false;
8267   } else {
8268     return false;
8269   }
8270
8271   if (Ptr.getNode()->hasOneUse())
8272     return false;
8273
8274   for (SDNode *Op : Ptr.getNode()->uses()) {
8275     if (Op == N ||
8276         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8277       continue;
8278
8279     SDValue BasePtr;
8280     SDValue Offset;
8281     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8282     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8283       // Don't create a indexed load / store with zero offset.
8284       if (isa<ConstantSDNode>(Offset) &&
8285           cast<ConstantSDNode>(Offset)->isNullValue())
8286         continue;
8287
8288       // Try turning it into a post-indexed load / store except when
8289       // 1) All uses are load / store ops that use it as base ptr (and
8290       //    it may be folded as addressing mmode).
8291       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8292       //    nor a successor of N. Otherwise, if Op is folded that would
8293       //    create a cycle.
8294
8295       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8296         continue;
8297
8298       // Check for #1.
8299       bool TryNext = false;
8300       for (SDNode *Use : BasePtr.getNode()->uses()) {
8301         if (Use == Ptr.getNode())
8302           continue;
8303
8304         // If all the uses are load / store addresses, then don't do the
8305         // transformation.
8306         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8307           bool RealUse = false;
8308           for (SDNode *UseUse : Use->uses()) {
8309             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8310               RealUse = true;
8311           }
8312
8313           if (!RealUse) {
8314             TryNext = true;
8315             break;
8316           }
8317         }
8318       }
8319
8320       if (TryNext)
8321         continue;
8322
8323       // Check for #2
8324       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8325         SDValue Result = isLoad
8326           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8327                                BasePtr, Offset, AM)
8328           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8329                                 BasePtr, Offset, AM);
8330         ++PostIndexedNodes;
8331         ++NodesCombined;
8332         DEBUG(dbgs() << "\nReplacing.5 ";
8333               N->dump(&DAG);
8334               dbgs() << "\nWith: ";
8335               Result.getNode()->dump(&DAG);
8336               dbgs() << '\n');
8337         WorklistRemover DeadNodes(*this);
8338         if (isLoad) {
8339           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8340           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8341         } else {
8342           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8343         }
8344
8345         // Finally, since the node is now dead, remove it from the graph.
8346         deleteAndRecombine(N);
8347
8348         // Replace the uses of Use with uses of the updated base value.
8349         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8350                                       Result.getValue(isLoad ? 1 : 0));
8351         deleteAndRecombine(Op);
8352         return true;
8353       }
8354     }
8355   }
8356
8357   return false;
8358 }
8359
8360 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8361 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8362   ISD::MemIndexedMode AM = LD->getAddressingMode();
8363   assert(AM != ISD::UNINDEXED);
8364   SDValue BP = LD->getOperand(1);
8365   SDValue Inc = LD->getOperand(2);
8366
8367   // Some backends use TargetConstants for load offsets, but don't expect
8368   // TargetConstants in general ADD nodes. We can convert these constants into
8369   // regular Constants (if the constant is not opaque).
8370   assert((Inc.getOpcode() != ISD::TargetConstant ||
8371           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8372          "Cannot split out indexing using opaque target constants");
8373   if (Inc.getOpcode() == ISD::TargetConstant) {
8374     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8375     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8376                           ConstInc->getValueType(0));
8377   }
8378
8379   unsigned Opc =
8380       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8381   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8382 }
8383
8384 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8385   LoadSDNode *LD  = cast<LoadSDNode>(N);
8386   SDValue Chain = LD->getChain();
8387   SDValue Ptr   = LD->getBasePtr();
8388
8389   // If load is not volatile and there are no uses of the loaded value (and
8390   // the updated indexed value in case of indexed loads), change uses of the
8391   // chain value into uses of the chain input (i.e. delete the dead load).
8392   if (!LD->isVolatile()) {
8393     if (N->getValueType(1) == MVT::Other) {
8394       // Unindexed loads.
8395       if (!N->hasAnyUseOfValue(0)) {
8396         // It's not safe to use the two value CombineTo variant here. e.g.
8397         // v1, chain2 = load chain1, loc
8398         // v2, chain3 = load chain2, loc
8399         // v3         = add v2, c
8400         // Now we replace use of chain2 with chain1.  This makes the second load
8401         // isomorphic to the one we are deleting, and thus makes this load live.
8402         DEBUG(dbgs() << "\nReplacing.6 ";
8403               N->dump(&DAG);
8404               dbgs() << "\nWith chain: ";
8405               Chain.getNode()->dump(&DAG);
8406               dbgs() << "\n");
8407         WorklistRemover DeadNodes(*this);
8408         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8409
8410         if (N->use_empty())
8411           deleteAndRecombine(N);
8412
8413         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8414       }
8415     } else {
8416       // Indexed loads.
8417       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8418
8419       // If this load has an opaque TargetConstant offset, then we cannot split
8420       // the indexing into an add/sub directly (that TargetConstant may not be
8421       // valid for a different type of node, and we cannot convert an opaque
8422       // target constant into a regular constant).
8423       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8424                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8425
8426       if (!N->hasAnyUseOfValue(0) &&
8427           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8428         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8429         SDValue Index;
8430         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8431           Index = SplitIndexingFromLoad(LD);
8432           // Try to fold the base pointer arithmetic into subsequent loads and
8433           // stores.
8434           AddUsersToWorklist(N);
8435         } else
8436           Index = DAG.getUNDEF(N->getValueType(1));
8437         DEBUG(dbgs() << "\nReplacing.7 ";
8438               N->dump(&DAG);
8439               dbgs() << "\nWith: ";
8440               Undef.getNode()->dump(&DAG);
8441               dbgs() << " and 2 other values\n");
8442         WorklistRemover DeadNodes(*this);
8443         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8444         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8445         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8446         deleteAndRecombine(N);
8447         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8448       }
8449     }
8450   }
8451
8452   // If this load is directly stored, replace the load value with the stored
8453   // value.
8454   // TODO: Handle store large -> read small portion.
8455   // TODO: Handle TRUNCSTORE/LOADEXT
8456   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8457     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8458       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8459       if (PrevST->getBasePtr() == Ptr &&
8460           PrevST->getValue().getValueType() == N->getValueType(0))
8461       return CombineTo(N, Chain.getOperand(1), Chain);
8462     }
8463   }
8464
8465   // Try to infer better alignment information than the load already has.
8466   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8467     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8468       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8469         SDValue NewLoad =
8470                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8471                               LD->getValueType(0),
8472                               Chain, Ptr, LD->getPointerInfo(),
8473                               LD->getMemoryVT(),
8474                               LD->isVolatile(), LD->isNonTemporal(),
8475                               LD->isInvariant(), Align, LD->getAAInfo());
8476         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8477       }
8478     }
8479   }
8480
8481   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8482                                                   : DAG.getSubtarget().useAA();
8483 #ifndef NDEBUG
8484   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8485       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8486     UseAA = false;
8487 #endif
8488   if (UseAA && LD->isUnindexed()) {
8489     // Walk up chain skipping non-aliasing memory nodes.
8490     SDValue BetterChain = FindBetterChain(N, Chain);
8491
8492     // If there is a better chain.
8493     if (Chain != BetterChain) {
8494       SDValue ReplLoad;
8495
8496       // Replace the chain to void dependency.
8497       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8498         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8499                                BetterChain, Ptr, LD->getMemOperand());
8500       } else {
8501         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8502                                   LD->getValueType(0),
8503                                   BetterChain, Ptr, LD->getMemoryVT(),
8504                                   LD->getMemOperand());
8505       }
8506
8507       // Create token factor to keep old chain connected.
8508       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8509                                   MVT::Other, Chain, ReplLoad.getValue(1));
8510
8511       // Make sure the new and old chains are cleaned up.
8512       AddToWorklist(Token.getNode());
8513
8514       // Replace uses with load result and token factor. Don't add users
8515       // to work list.
8516       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8517     }
8518   }
8519
8520   // Try transforming N to an indexed load.
8521   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8522     return SDValue(N, 0);
8523
8524   // Try to slice up N to more direct loads if the slices are mapped to
8525   // different register banks or pairing can take place.
8526   if (SliceUpLoad(N))
8527     return SDValue(N, 0);
8528
8529   return SDValue();
8530 }
8531
8532 namespace {
8533 /// \brief Helper structure used to slice a load in smaller loads.
8534 /// Basically a slice is obtained from the following sequence:
8535 /// Origin = load Ty1, Base
8536 /// Shift = srl Ty1 Origin, CstTy Amount
8537 /// Inst = trunc Shift to Ty2
8538 ///
8539 /// Then, it will be rewriten into:
8540 /// Slice = load SliceTy, Base + SliceOffset
8541 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8542 ///
8543 /// SliceTy is deduced from the number of bits that are actually used to
8544 /// build Inst.
8545 struct LoadedSlice {
8546   /// \brief Helper structure used to compute the cost of a slice.
8547   struct Cost {
8548     /// Are we optimizing for code size.
8549     bool ForCodeSize;
8550     /// Various cost.
8551     unsigned Loads;
8552     unsigned Truncates;
8553     unsigned CrossRegisterBanksCopies;
8554     unsigned ZExts;
8555     unsigned Shift;
8556
8557     Cost(bool ForCodeSize = false)
8558         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8559           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8560
8561     /// \brief Get the cost of one isolated slice.
8562     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8563         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8564           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8565       EVT TruncType = LS.Inst->getValueType(0);
8566       EVT LoadedType = LS.getLoadedType();
8567       if (TruncType != LoadedType &&
8568           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8569         ZExts = 1;
8570     }
8571
8572     /// \brief Account for slicing gain in the current cost.
8573     /// Slicing provide a few gains like removing a shift or a
8574     /// truncate. This method allows to grow the cost of the original
8575     /// load with the gain from this slice.
8576     void addSliceGain(const LoadedSlice &LS) {
8577       // Each slice saves a truncate.
8578       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8579       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8580                               LS.Inst->getOperand(0).getValueType()))
8581         ++Truncates;
8582       // If there is a shift amount, this slice gets rid of it.
8583       if (LS.Shift)
8584         ++Shift;
8585       // If this slice can merge a cross register bank copy, account for it.
8586       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8587         ++CrossRegisterBanksCopies;
8588     }
8589
8590     Cost &operator+=(const Cost &RHS) {
8591       Loads += RHS.Loads;
8592       Truncates += RHS.Truncates;
8593       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8594       ZExts += RHS.ZExts;
8595       Shift += RHS.Shift;
8596       return *this;
8597     }
8598
8599     bool operator==(const Cost &RHS) const {
8600       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8601              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8602              ZExts == RHS.ZExts && Shift == RHS.Shift;
8603     }
8604
8605     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8606
8607     bool operator<(const Cost &RHS) const {
8608       // Assume cross register banks copies are as expensive as loads.
8609       // FIXME: Do we want some more target hooks?
8610       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8611       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8612       // Unless we are optimizing for code size, consider the
8613       // expensive operation first.
8614       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8615         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8616       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8617              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8618     }
8619
8620     bool operator>(const Cost &RHS) const { return RHS < *this; }
8621
8622     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8623
8624     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8625   };
8626   // The last instruction that represent the slice. This should be a
8627   // truncate instruction.
8628   SDNode *Inst;
8629   // The original load instruction.
8630   LoadSDNode *Origin;
8631   // The right shift amount in bits from the original load.
8632   unsigned Shift;
8633   // The DAG from which Origin came from.
8634   // This is used to get some contextual information about legal types, etc.
8635   SelectionDAG *DAG;
8636
8637   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8638               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8639       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8640
8641   LoadedSlice(const LoadedSlice &LS)
8642       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8643
8644   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8645   /// \return Result is \p BitWidth and has used bits set to 1 and
8646   ///         not used bits set to 0.
8647   APInt getUsedBits() const {
8648     // Reproduce the trunc(lshr) sequence:
8649     // - Start from the truncated value.
8650     // - Zero extend to the desired bit width.
8651     // - Shift left.
8652     assert(Origin && "No original load to compare against.");
8653     unsigned BitWidth = Origin->getValueSizeInBits(0);
8654     assert(Inst && "This slice is not bound to an instruction");
8655     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8656            "Extracted slice is bigger than the whole type!");
8657     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8658     UsedBits.setAllBits();
8659     UsedBits = UsedBits.zext(BitWidth);
8660     UsedBits <<= Shift;
8661     return UsedBits;
8662   }
8663
8664   /// \brief Get the size of the slice to be loaded in bytes.
8665   unsigned getLoadedSize() const {
8666     unsigned SliceSize = getUsedBits().countPopulation();
8667     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8668     return SliceSize / 8;
8669   }
8670
8671   /// \brief Get the type that will be loaded for this slice.
8672   /// Note: This may not be the final type for the slice.
8673   EVT getLoadedType() const {
8674     assert(DAG && "Missing context");
8675     LLVMContext &Ctxt = *DAG->getContext();
8676     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8677   }
8678
8679   /// \brief Get the alignment of the load used for this slice.
8680   unsigned getAlignment() const {
8681     unsigned Alignment = Origin->getAlignment();
8682     unsigned Offset = getOffsetFromBase();
8683     if (Offset != 0)
8684       Alignment = MinAlign(Alignment, Alignment + Offset);
8685     return Alignment;
8686   }
8687
8688   /// \brief Check if this slice can be rewritten with legal operations.
8689   bool isLegal() const {
8690     // An invalid slice is not legal.
8691     if (!Origin || !Inst || !DAG)
8692       return false;
8693
8694     // Offsets are for indexed load only, we do not handle that.
8695     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8696       return false;
8697
8698     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8699
8700     // Check that the type is legal.
8701     EVT SliceType = getLoadedType();
8702     if (!TLI.isTypeLegal(SliceType))
8703       return false;
8704
8705     // Check that the load is legal for this type.
8706     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8707       return false;
8708
8709     // Check that the offset can be computed.
8710     // 1. Check its type.
8711     EVT PtrType = Origin->getBasePtr().getValueType();
8712     if (PtrType == MVT::Untyped || PtrType.isExtended())
8713       return false;
8714
8715     // 2. Check that it fits in the immediate.
8716     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8717       return false;
8718
8719     // 3. Check that the computation is legal.
8720     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8721       return false;
8722
8723     // Check that the zext is legal if it needs one.
8724     EVT TruncateType = Inst->getValueType(0);
8725     if (TruncateType != SliceType &&
8726         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8727       return false;
8728
8729     return true;
8730   }
8731
8732   /// \brief Get the offset in bytes of this slice in the original chunk of
8733   /// bits.
8734   /// \pre DAG != nullptr.
8735   uint64_t getOffsetFromBase() const {
8736     assert(DAG && "Missing context.");
8737     bool IsBigEndian =
8738         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8739     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8740     uint64_t Offset = Shift / 8;
8741     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8742     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8743            "The size of the original loaded type is not a multiple of a"
8744            " byte.");
8745     // If Offset is bigger than TySizeInBytes, it means we are loading all
8746     // zeros. This should have been optimized before in the process.
8747     assert(TySizeInBytes > Offset &&
8748            "Invalid shift amount for given loaded size");
8749     if (IsBigEndian)
8750       Offset = TySizeInBytes - Offset - getLoadedSize();
8751     return Offset;
8752   }
8753
8754   /// \brief Generate the sequence of instructions to load the slice
8755   /// represented by this object and redirect the uses of this slice to
8756   /// this new sequence of instructions.
8757   /// \pre this->Inst && this->Origin are valid Instructions and this
8758   /// object passed the legal check: LoadedSlice::isLegal returned true.
8759   /// \return The last instruction of the sequence used to load the slice.
8760   SDValue loadSlice() const {
8761     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8762     const SDValue &OldBaseAddr = Origin->getBasePtr();
8763     SDValue BaseAddr = OldBaseAddr;
8764     // Get the offset in that chunk of bytes w.r.t. the endianess.
8765     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8766     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8767     if (Offset) {
8768       // BaseAddr = BaseAddr + Offset.
8769       EVT ArithType = BaseAddr.getValueType();
8770       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8771                               DAG->getConstant(Offset, ArithType));
8772     }
8773
8774     // Create the type of the loaded slice according to its size.
8775     EVT SliceType = getLoadedType();
8776
8777     // Create the load for the slice.
8778     SDValue LastInst = DAG->getLoad(
8779         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8780         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8781         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8782     // If the final type is not the same as the loaded type, this means that
8783     // we have to pad with zero. Create a zero extend for that.
8784     EVT FinalType = Inst->getValueType(0);
8785     if (SliceType != FinalType)
8786       LastInst =
8787           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8788     return LastInst;
8789   }
8790
8791   /// \brief Check if this slice can be merged with an expensive cross register
8792   /// bank copy. E.g.,
8793   /// i = load i32
8794   /// f = bitcast i32 i to float
8795   bool canMergeExpensiveCrossRegisterBankCopy() const {
8796     if (!Inst || !Inst->hasOneUse())
8797       return false;
8798     SDNode *Use = *Inst->use_begin();
8799     if (Use->getOpcode() != ISD::BITCAST)
8800       return false;
8801     assert(DAG && "Missing context");
8802     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8803     EVT ResVT = Use->getValueType(0);
8804     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8805     const TargetRegisterClass *ArgRC =
8806         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8807     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8808       return false;
8809
8810     // At this point, we know that we perform a cross-register-bank copy.
8811     // Check if it is expensive.
8812     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8813     // Assume bitcasts are cheap, unless both register classes do not
8814     // explicitly share a common sub class.
8815     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8816       return false;
8817
8818     // Check if it will be merged with the load.
8819     // 1. Check the alignment constraint.
8820     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8821         ResVT.getTypeForEVT(*DAG->getContext()));
8822
8823     if (RequiredAlignment > getAlignment())
8824       return false;
8825
8826     // 2. Check that the load is a legal operation for that type.
8827     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8828       return false;
8829
8830     // 3. Check that we do not have a zext in the way.
8831     if (Inst->getValueType(0) != getLoadedType())
8832       return false;
8833
8834     return true;
8835   }
8836 };
8837 }
8838
8839 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8840 /// \p UsedBits looks like 0..0 1..1 0..0.
8841 static bool areUsedBitsDense(const APInt &UsedBits) {
8842   // If all the bits are one, this is dense!
8843   if (UsedBits.isAllOnesValue())
8844     return true;
8845
8846   // Get rid of the unused bits on the right.
8847   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8848   // Get rid of the unused bits on the left.
8849   if (NarrowedUsedBits.countLeadingZeros())
8850     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8851   // Check that the chunk of bits is completely used.
8852   return NarrowedUsedBits.isAllOnesValue();
8853 }
8854
8855 /// \brief Check whether or not \p First and \p Second are next to each other
8856 /// in memory. This means that there is no hole between the bits loaded
8857 /// by \p First and the bits loaded by \p Second.
8858 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8859                                      const LoadedSlice &Second) {
8860   assert(First.Origin == Second.Origin && First.Origin &&
8861          "Unable to match different memory origins.");
8862   APInt UsedBits = First.getUsedBits();
8863   assert((UsedBits & Second.getUsedBits()) == 0 &&
8864          "Slices are not supposed to overlap.");
8865   UsedBits |= Second.getUsedBits();
8866   return areUsedBitsDense(UsedBits);
8867 }
8868
8869 /// \brief Adjust the \p GlobalLSCost according to the target
8870 /// paring capabilities and the layout of the slices.
8871 /// \pre \p GlobalLSCost should account for at least as many loads as
8872 /// there is in the slices in \p LoadedSlices.
8873 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8874                                  LoadedSlice::Cost &GlobalLSCost) {
8875   unsigned NumberOfSlices = LoadedSlices.size();
8876   // If there is less than 2 elements, no pairing is possible.
8877   if (NumberOfSlices < 2)
8878     return;
8879
8880   // Sort the slices so that elements that are likely to be next to each
8881   // other in memory are next to each other in the list.
8882   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8883             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8884     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8885     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8886   });
8887   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8888   // First (resp. Second) is the first (resp. Second) potentially candidate
8889   // to be placed in a paired load.
8890   const LoadedSlice *First = nullptr;
8891   const LoadedSlice *Second = nullptr;
8892   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8893                 // Set the beginning of the pair.
8894                                                            First = Second) {
8895
8896     Second = &LoadedSlices[CurrSlice];
8897
8898     // If First is NULL, it means we start a new pair.
8899     // Get to the next slice.
8900     if (!First)
8901       continue;
8902
8903     EVT LoadedType = First->getLoadedType();
8904
8905     // If the types of the slices are different, we cannot pair them.
8906     if (LoadedType != Second->getLoadedType())
8907       continue;
8908
8909     // Check if the target supplies paired loads for this type.
8910     unsigned RequiredAlignment = 0;
8911     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8912       // move to the next pair, this type is hopeless.
8913       Second = nullptr;
8914       continue;
8915     }
8916     // Check if we meet the alignment requirement.
8917     if (RequiredAlignment > First->getAlignment())
8918       continue;
8919
8920     // Check that both loads are next to each other in memory.
8921     if (!areSlicesNextToEachOther(*First, *Second))
8922       continue;
8923
8924     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8925     --GlobalLSCost.Loads;
8926     // Move to the next pair.
8927     Second = nullptr;
8928   }
8929 }
8930
8931 /// \brief Check the profitability of all involved LoadedSlice.
8932 /// Currently, it is considered profitable if there is exactly two
8933 /// involved slices (1) which are (2) next to each other in memory, and
8934 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8935 ///
8936 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8937 /// the elements themselves.
8938 ///
8939 /// FIXME: When the cost model will be mature enough, we can relax
8940 /// constraints (1) and (2).
8941 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8942                                 const APInt &UsedBits, bool ForCodeSize) {
8943   unsigned NumberOfSlices = LoadedSlices.size();
8944   if (StressLoadSlicing)
8945     return NumberOfSlices > 1;
8946
8947   // Check (1).
8948   if (NumberOfSlices != 2)
8949     return false;
8950
8951   // Check (2).
8952   if (!areUsedBitsDense(UsedBits))
8953     return false;
8954
8955   // Check (3).
8956   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8957   // The original code has one big load.
8958   OrigCost.Loads = 1;
8959   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8960     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8961     // Accumulate the cost of all the slices.
8962     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8963     GlobalSlicingCost += SliceCost;
8964
8965     // Account as cost in the original configuration the gain obtained
8966     // with the current slices.
8967     OrigCost.addSliceGain(LS);
8968   }
8969
8970   // If the target supports paired load, adjust the cost accordingly.
8971   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8972   return OrigCost > GlobalSlicingCost;
8973 }
8974
8975 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8976 /// operations, split it in the various pieces being extracted.
8977 ///
8978 /// This sort of thing is introduced by SROA.
8979 /// This slicing takes care not to insert overlapping loads.
8980 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8981 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8982   if (Level < AfterLegalizeDAG)
8983     return false;
8984
8985   LoadSDNode *LD = cast<LoadSDNode>(N);
8986   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8987       !LD->getValueType(0).isInteger())
8988     return false;
8989
8990   // Keep track of already used bits to detect overlapping values.
8991   // In that case, we will just abort the transformation.
8992   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8993
8994   SmallVector<LoadedSlice, 4> LoadedSlices;
8995
8996   // Check if this load is used as several smaller chunks of bits.
8997   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8998   // of computation for each trunc.
8999   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
9000        UI != UIEnd; ++UI) {
9001     // Skip the uses of the chain.
9002     if (UI.getUse().getResNo() != 0)
9003       continue;
9004
9005     SDNode *User = *UI;
9006     unsigned Shift = 0;
9007
9008     // Check if this is a trunc(lshr).
9009     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
9010         isa<ConstantSDNode>(User->getOperand(1))) {
9011       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
9012       User = *User->use_begin();
9013     }
9014
9015     // At this point, User is a Truncate, iff we encountered, trunc or
9016     // trunc(lshr).
9017     if (User->getOpcode() != ISD::TRUNCATE)
9018       return false;
9019
9020     // The width of the type must be a power of 2 and greater than 8-bits.
9021     // Otherwise the load cannot be represented in LLVM IR.
9022     // Moreover, if we shifted with a non-8-bits multiple, the slice
9023     // will be across several bytes. We do not support that.
9024     unsigned Width = User->getValueSizeInBits(0);
9025     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
9026       return 0;
9027
9028     // Build the slice for this chain of computations.
9029     LoadedSlice LS(User, LD, Shift, &DAG);
9030     APInt CurrentUsedBits = LS.getUsedBits();
9031
9032     // Check if this slice overlaps with another.
9033     if ((CurrentUsedBits & UsedBits) != 0)
9034       return false;
9035     // Update the bits used globally.
9036     UsedBits |= CurrentUsedBits;
9037
9038     // Check if the new slice would be legal.
9039     if (!LS.isLegal())
9040       return false;
9041
9042     // Record the slice.
9043     LoadedSlices.push_back(LS);
9044   }
9045
9046   // Abort slicing if it does not seem to be profitable.
9047   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
9048     return false;
9049
9050   ++SlicedLoads;
9051
9052   // Rewrite each chain to use an independent load.
9053   // By construction, each chain can be represented by a unique load.
9054
9055   // Prepare the argument for the new token factor for all the slices.
9056   SmallVector<SDValue, 8> ArgChains;
9057   for (SmallVectorImpl<LoadedSlice>::const_iterator
9058            LSIt = LoadedSlices.begin(),
9059            LSItEnd = LoadedSlices.end();
9060        LSIt != LSItEnd; ++LSIt) {
9061     SDValue SliceInst = LSIt->loadSlice();
9062     CombineTo(LSIt->Inst, SliceInst, true);
9063     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
9064       SliceInst = SliceInst.getOperand(0);
9065     assert(SliceInst->getOpcode() == ISD::LOAD &&
9066            "It takes more than a zext to get to the loaded slice!!");
9067     ArgChains.push_back(SliceInst.getValue(1));
9068   }
9069
9070   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
9071                               ArgChains);
9072   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
9073   return true;
9074 }
9075
9076 /// Check to see if V is (and load (ptr), imm), where the load is having
9077 /// specific bytes cleared out.  If so, return the byte size being masked out
9078 /// and the shift amount.
9079 static std::pair<unsigned, unsigned>
9080 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
9081   std::pair<unsigned, unsigned> Result(0, 0);
9082
9083   // Check for the structure we're looking for.
9084   if (V->getOpcode() != ISD::AND ||
9085       !isa<ConstantSDNode>(V->getOperand(1)) ||
9086       !ISD::isNormalLoad(V->getOperand(0).getNode()))
9087     return Result;
9088
9089   // Check the chain and pointer.
9090   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
9091   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
9092
9093   // The store should be chained directly to the load or be an operand of a
9094   // tokenfactor.
9095   if (LD == Chain.getNode())
9096     ; // ok.
9097   else if (Chain->getOpcode() != ISD::TokenFactor)
9098     return Result; // Fail.
9099   else {
9100     bool isOk = false;
9101     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
9102       if (Chain->getOperand(i).getNode() == LD) {
9103         isOk = true;
9104         break;
9105       }
9106     if (!isOk) return Result;
9107   }
9108
9109   // This only handles simple types.
9110   if (V.getValueType() != MVT::i16 &&
9111       V.getValueType() != MVT::i32 &&
9112       V.getValueType() != MVT::i64)
9113     return Result;
9114
9115   // Check the constant mask.  Invert it so that the bits being masked out are
9116   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
9117   // follow the sign bit for uniformity.
9118   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
9119   unsigned NotMaskLZ = countLeadingZeros(NotMask);
9120   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
9121   unsigned NotMaskTZ = countTrailingZeros(NotMask);
9122   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
9123   if (NotMaskLZ == 64) return Result;  // All zero mask.
9124
9125   // See if we have a continuous run of bits.  If so, we have 0*1+0*
9126   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
9127     return Result;
9128
9129   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
9130   if (V.getValueType() != MVT::i64 && NotMaskLZ)
9131     NotMaskLZ -= 64-V.getValueSizeInBits();
9132
9133   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
9134   switch (MaskedBytes) {
9135   case 1:
9136   case 2:
9137   case 4: break;
9138   default: return Result; // All one mask, or 5-byte mask.
9139   }
9140
9141   // Verify that the first bit starts at a multiple of mask so that the access
9142   // is aligned the same as the access width.
9143   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
9144
9145   Result.first = MaskedBytes;
9146   Result.second = NotMaskTZ/8;
9147   return Result;
9148 }
9149
9150
9151 /// Check to see if IVal is something that provides a value as specified by
9152 /// MaskInfo. If so, replace the specified store with a narrower store of
9153 /// truncated IVal.
9154 static SDNode *
9155 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
9156                                 SDValue IVal, StoreSDNode *St,
9157                                 DAGCombiner *DC) {
9158   unsigned NumBytes = MaskInfo.first;
9159   unsigned ByteShift = MaskInfo.second;
9160   SelectionDAG &DAG = DC->getDAG();
9161
9162   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9163   // that uses this.  If not, this is not a replacement.
9164   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9165                                   ByteShift*8, (ByteShift+NumBytes)*8);
9166   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9167
9168   // Check that it is legal on the target to do this.  It is legal if the new
9169   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9170   // legalization.
9171   MVT VT = MVT::getIntegerVT(NumBytes*8);
9172   if (!DC->isTypeLegal(VT))
9173     return nullptr;
9174
9175   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9176   // shifted by ByteShift and truncated down to NumBytes.
9177   if (ByteShift)
9178     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9179                        DAG.getConstant(ByteShift*8,
9180                                     DC->getShiftAmountTy(IVal.getValueType())));
9181
9182   // Figure out the offset for the store and the alignment of the access.
9183   unsigned StOffset;
9184   unsigned NewAlign = St->getAlignment();
9185
9186   if (DAG.getTargetLoweringInfo().isLittleEndian())
9187     StOffset = ByteShift;
9188   else
9189     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9190
9191   SDValue Ptr = St->getBasePtr();
9192   if (StOffset) {
9193     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9194                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9195     NewAlign = MinAlign(NewAlign, StOffset);
9196   }
9197
9198   // Truncate down to the new size.
9199   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9200
9201   ++OpsNarrowed;
9202   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9203                       St->getPointerInfo().getWithOffset(StOffset),
9204                       false, false, NewAlign).getNode();
9205 }
9206
9207
9208 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9209 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9210 /// narrowing the load and store if it would end up being a win for performance
9211 /// or code size.
9212 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9213   StoreSDNode *ST  = cast<StoreSDNode>(N);
9214   if (ST->isVolatile())
9215     return SDValue();
9216
9217   SDValue Chain = ST->getChain();
9218   SDValue Value = ST->getValue();
9219   SDValue Ptr   = ST->getBasePtr();
9220   EVT VT = Value.getValueType();
9221
9222   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9223     return SDValue();
9224
9225   unsigned Opc = Value.getOpcode();
9226
9227   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9228   // is a byte mask indicating a consecutive number of bytes, check to see if
9229   // Y is known to provide just those bytes.  If so, we try to replace the
9230   // load + replace + store sequence with a single (narrower) store, which makes
9231   // the load dead.
9232   if (Opc == ISD::OR) {
9233     std::pair<unsigned, unsigned> MaskedLoad;
9234     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9235     if (MaskedLoad.first)
9236       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9237                                                   Value.getOperand(1), ST,this))
9238         return SDValue(NewST, 0);
9239
9240     // Or is commutative, so try swapping X and Y.
9241     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9242     if (MaskedLoad.first)
9243       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9244                                                   Value.getOperand(0), ST,this))
9245         return SDValue(NewST, 0);
9246   }
9247
9248   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9249       Value.getOperand(1).getOpcode() != ISD::Constant)
9250     return SDValue();
9251
9252   SDValue N0 = Value.getOperand(0);
9253   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9254       Chain == SDValue(N0.getNode(), 1)) {
9255     LoadSDNode *LD = cast<LoadSDNode>(N0);
9256     if (LD->getBasePtr() != Ptr ||
9257         LD->getPointerInfo().getAddrSpace() !=
9258         ST->getPointerInfo().getAddrSpace())
9259       return SDValue();
9260
9261     // Find the type to narrow it the load / op / store to.
9262     SDValue N1 = Value.getOperand(1);
9263     unsigned BitWidth = N1.getValueSizeInBits();
9264     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9265     if (Opc == ISD::AND)
9266       Imm ^= APInt::getAllOnesValue(BitWidth);
9267     if (Imm == 0 || Imm.isAllOnesValue())
9268       return SDValue();
9269     unsigned ShAmt = Imm.countTrailingZeros();
9270     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9271     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9272     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9273     while (NewBW < BitWidth &&
9274            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9275              TLI.isNarrowingProfitable(VT, NewVT))) {
9276       NewBW = NextPowerOf2(NewBW);
9277       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9278     }
9279     if (NewBW >= BitWidth)
9280       return SDValue();
9281
9282     // If the lsb changed does not start at the type bitwidth boundary,
9283     // start at the previous one.
9284     if (ShAmt % NewBW)
9285       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9286     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9287                                    std::min(BitWidth, ShAmt + NewBW));
9288     if ((Imm & Mask) == Imm) {
9289       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9290       if (Opc == ISD::AND)
9291         NewImm ^= APInt::getAllOnesValue(NewBW);
9292       uint64_t PtrOff = ShAmt / 8;
9293       // For big endian targets, we need to adjust the offset to the pointer to
9294       // load the correct bytes.
9295       if (TLI.isBigEndian())
9296         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9297
9298       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9299       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9300       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9301         return SDValue();
9302
9303       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9304                                    Ptr.getValueType(), Ptr,
9305                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9306       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9307                                   LD->getChain(), NewPtr,
9308                                   LD->getPointerInfo().getWithOffset(PtrOff),
9309                                   LD->isVolatile(), LD->isNonTemporal(),
9310                                   LD->isInvariant(), NewAlign,
9311                                   LD->getAAInfo());
9312       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9313                                    DAG.getConstant(NewImm, NewVT));
9314       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9315                                    NewVal, NewPtr,
9316                                    ST->getPointerInfo().getWithOffset(PtrOff),
9317                                    false, false, NewAlign);
9318
9319       AddToWorklist(NewPtr.getNode());
9320       AddToWorklist(NewLD.getNode());
9321       AddToWorklist(NewVal.getNode());
9322       WorklistRemover DeadNodes(*this);
9323       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9324       ++OpsNarrowed;
9325       return NewST;
9326     }
9327   }
9328
9329   return SDValue();
9330 }
9331
9332 /// For a given floating point load / store pair, if the load value isn't used
9333 /// by any other operations, then consider transforming the pair to integer
9334 /// load / store operations if the target deems the transformation profitable.
9335 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9336   StoreSDNode *ST  = cast<StoreSDNode>(N);
9337   SDValue Chain = ST->getChain();
9338   SDValue Value = ST->getValue();
9339   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9340       Value.hasOneUse() &&
9341       Chain == SDValue(Value.getNode(), 1)) {
9342     LoadSDNode *LD = cast<LoadSDNode>(Value);
9343     EVT VT = LD->getMemoryVT();
9344     if (!VT.isFloatingPoint() ||
9345         VT != ST->getMemoryVT() ||
9346         LD->isNonTemporal() ||
9347         ST->isNonTemporal() ||
9348         LD->getPointerInfo().getAddrSpace() != 0 ||
9349         ST->getPointerInfo().getAddrSpace() != 0)
9350       return SDValue();
9351
9352     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9353     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9354         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9355         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9356         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9357       return SDValue();
9358
9359     unsigned LDAlign = LD->getAlignment();
9360     unsigned STAlign = ST->getAlignment();
9361     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9362     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9363     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9364       return SDValue();
9365
9366     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9367                                 LD->getChain(), LD->getBasePtr(),
9368                                 LD->getPointerInfo(),
9369                                 false, false, false, LDAlign);
9370
9371     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9372                                  NewLD, ST->getBasePtr(),
9373                                  ST->getPointerInfo(),
9374                                  false, false, STAlign);
9375
9376     AddToWorklist(NewLD.getNode());
9377     AddToWorklist(NewST.getNode());
9378     WorklistRemover DeadNodes(*this);
9379     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9380     ++LdStFP2Int;
9381     return NewST;
9382   }
9383
9384   return SDValue();
9385 }
9386
9387 /// Helper struct to parse and store a memory address as base + index + offset.
9388 /// We ignore sign extensions when it is safe to do so.
9389 /// The following two expressions are not equivalent. To differentiate we need
9390 /// to store whether there was a sign extension involved in the index
9391 /// computation.
9392 ///  (load (i64 add (i64 copyfromreg %c)
9393 ///                 (i64 signextend (add (i8 load %index)
9394 ///                                      (i8 1))))
9395 /// vs
9396 ///
9397 /// (load (i64 add (i64 copyfromreg %c)
9398 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9399 ///                                         (i32 1)))))
9400 struct BaseIndexOffset {
9401   SDValue Base;
9402   SDValue Index;
9403   int64_t Offset;
9404   bool IsIndexSignExt;
9405
9406   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9407
9408   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9409                   bool IsIndexSignExt) :
9410     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9411
9412   bool equalBaseIndex(const BaseIndexOffset &Other) {
9413     return Other.Base == Base && Other.Index == Index &&
9414       Other.IsIndexSignExt == IsIndexSignExt;
9415   }
9416
9417   /// Parses tree in Ptr for base, index, offset addresses.
9418   static BaseIndexOffset match(SDValue Ptr) {
9419     bool IsIndexSignExt = false;
9420
9421     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9422     // instruction, then it could be just the BASE or everything else we don't
9423     // know how to handle. Just use Ptr as BASE and give up.
9424     if (Ptr->getOpcode() != ISD::ADD)
9425       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9426
9427     // We know that we have at least an ADD instruction. Try to pattern match
9428     // the simple case of BASE + OFFSET.
9429     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9430       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9431       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9432                               IsIndexSignExt);
9433     }
9434
9435     // Inside a loop the current BASE pointer is calculated using an ADD and a
9436     // MUL instruction. In this case Ptr is the actual BASE pointer.
9437     // (i64 add (i64 %array_ptr)
9438     //          (i64 mul (i64 %induction_var)
9439     //                   (i64 %element_size)))
9440     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9441       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9442
9443     // Look at Base + Index + Offset cases.
9444     SDValue Base = Ptr->getOperand(0);
9445     SDValue IndexOffset = Ptr->getOperand(1);
9446
9447     // Skip signextends.
9448     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9449       IndexOffset = IndexOffset->getOperand(0);
9450       IsIndexSignExt = true;
9451     }
9452
9453     // Either the case of Base + Index (no offset) or something else.
9454     if (IndexOffset->getOpcode() != ISD::ADD)
9455       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9456
9457     // Now we have the case of Base + Index + offset.
9458     SDValue Index = IndexOffset->getOperand(0);
9459     SDValue Offset = IndexOffset->getOperand(1);
9460
9461     if (!isa<ConstantSDNode>(Offset))
9462       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9463
9464     // Ignore signextends.
9465     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9466       Index = Index->getOperand(0);
9467       IsIndexSignExt = true;
9468     } else IsIndexSignExt = false;
9469
9470     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9471     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9472   }
9473 };
9474
9475 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9476 /// is located in a sequence of memory operations connected by a chain.
9477 struct MemOpLink {
9478   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9479     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9480   // Ptr to the mem node.
9481   LSBaseSDNode *MemNode;
9482   // Offset from the base ptr.
9483   int64_t OffsetFromBase;
9484   // What is the sequence number of this mem node.
9485   // Lowest mem operand in the DAG starts at zero.
9486   unsigned SequenceNum;
9487 };
9488
9489 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9490   EVT MemVT = St->getMemoryVT();
9491   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9492   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9493     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9494
9495   // Don't merge vectors into wider inputs.
9496   if (MemVT.isVector() || !MemVT.isSimple())
9497     return false;
9498
9499   // Perform an early exit check. Do not bother looking at stored values that
9500   // are not constants or loads.
9501   SDValue StoredVal = St->getValue();
9502   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9503   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9504       !IsLoadSrc)
9505     return false;
9506
9507   // Only look at ends of store sequences.
9508   SDValue Chain = SDValue(St, 0);
9509   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9510     return false;
9511
9512   // This holds the base pointer, index, and the offset in bytes from the base
9513   // pointer.
9514   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9515
9516   // We must have a base and an offset.
9517   if (!BasePtr.Base.getNode())
9518     return false;
9519
9520   // Do not handle stores to undef base pointers.
9521   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9522     return false;
9523
9524   // Save the LoadSDNodes that we find in the chain.
9525   // We need to make sure that these nodes do not interfere with
9526   // any of the store nodes.
9527   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9528
9529   // Save the StoreSDNodes that we find in the chain.
9530   SmallVector<MemOpLink, 8> StoreNodes;
9531
9532   // Walk up the chain and look for nodes with offsets from the same
9533   // base pointer. Stop when reaching an instruction with a different kind
9534   // or instruction which has a different base pointer.
9535   unsigned Seq = 0;
9536   StoreSDNode *Index = St;
9537   while (Index) {
9538     // If the chain has more than one use, then we can't reorder the mem ops.
9539     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9540       break;
9541
9542     // Find the base pointer and offset for this memory node.
9543     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9544
9545     // Check that the base pointer is the same as the original one.
9546     if (!Ptr.equalBaseIndex(BasePtr))
9547       break;
9548
9549     // Check that the alignment is the same.
9550     if (Index->getAlignment() != St->getAlignment())
9551       break;
9552
9553     // The memory operands must not be volatile.
9554     if (Index->isVolatile() || Index->isIndexed())
9555       break;
9556
9557     // No truncation.
9558     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9559       if (St->isTruncatingStore())
9560         break;
9561
9562     // The stored memory type must be the same.
9563     if (Index->getMemoryVT() != MemVT)
9564       break;
9565
9566     // We do not allow unaligned stores because we want to prevent overriding
9567     // stores.
9568     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9569       break;
9570
9571     // We found a potential memory operand to merge.
9572     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9573
9574     // Find the next memory operand in the chain. If the next operand in the
9575     // chain is a store then move up and continue the scan with the next
9576     // memory operand. If the next operand is a load save it and use alias
9577     // information to check if it interferes with anything.
9578     SDNode *NextInChain = Index->getChain().getNode();
9579     while (1) {
9580       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9581         // We found a store node. Use it for the next iteration.
9582         Index = STn;
9583         break;
9584       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9585         if (Ldn->isVolatile()) {
9586           Index = nullptr;
9587           break;
9588         }
9589
9590         // Save the load node for later. Continue the scan.
9591         AliasLoadNodes.push_back(Ldn);
9592         NextInChain = Ldn->getChain().getNode();
9593         continue;
9594       } else {
9595         Index = nullptr;
9596         break;
9597       }
9598     }
9599   }
9600
9601   // Check if there is anything to merge.
9602   if (StoreNodes.size() < 2)
9603     return false;
9604
9605   // Sort the memory operands according to their distance from the base pointer.
9606   std::sort(StoreNodes.begin(), StoreNodes.end(),
9607             [](MemOpLink LHS, MemOpLink RHS) {
9608     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9609            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9610             LHS.SequenceNum > RHS.SequenceNum);
9611   });
9612
9613   // Scan the memory operations on the chain and find the first non-consecutive
9614   // store memory address.
9615   unsigned LastConsecutiveStore = 0;
9616   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9617   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9618
9619     // Check that the addresses are consecutive starting from the second
9620     // element in the list of stores.
9621     if (i > 0) {
9622       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9623       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9624         break;
9625     }
9626
9627     bool Alias = false;
9628     // Check if this store interferes with any of the loads that we found.
9629     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9630       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9631         Alias = true;
9632         break;
9633       }
9634     // We found a load that alias with this store. Stop the sequence.
9635     if (Alias)
9636       break;
9637
9638     // Mark this node as useful.
9639     LastConsecutiveStore = i;
9640   }
9641
9642   // The node with the lowest store address.
9643   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9644
9645   // Store the constants into memory as one consecutive store.
9646   if (!IsLoadSrc) {
9647     unsigned LastLegalType = 0;
9648     unsigned LastLegalVectorType = 0;
9649     bool NonZero = false;
9650     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9651       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9652       SDValue StoredVal = St->getValue();
9653
9654       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9655         NonZero |= !C->isNullValue();
9656       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9657         NonZero |= !C->getConstantFPValue()->isNullValue();
9658       } else {
9659         // Non-constant.
9660         break;
9661       }
9662
9663       // Find a legal type for the constant store.
9664       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9665       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9666       if (TLI.isTypeLegal(StoreTy))
9667         LastLegalType = i+1;
9668       // Or check whether a truncstore is legal.
9669       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9670                TargetLowering::TypePromoteInteger) {
9671         EVT LegalizedStoredValueTy =
9672           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9673         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9674           LastLegalType = i+1;
9675       }
9676
9677       // Find a legal type for the vector store.
9678       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9679       if (TLI.isTypeLegal(Ty))
9680         LastLegalVectorType = i + 1;
9681     }
9682
9683     // We only use vectors if the constant is known to be zero and the
9684     // function is not marked with the noimplicitfloat attribute.
9685     if (NonZero || NoVectors)
9686       LastLegalVectorType = 0;
9687
9688     // Check if we found a legal integer type to store.
9689     if (LastLegalType == 0 && LastLegalVectorType == 0)
9690       return false;
9691
9692     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9693     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9694
9695     // Make sure we have something to merge.
9696     if (NumElem < 2)
9697       return false;
9698
9699     unsigned EarliestNodeUsed = 0;
9700     for (unsigned i=0; i < NumElem; ++i) {
9701       // Find a chain for the new wide-store operand. Notice that some
9702       // of the store nodes that we found may not be selected for inclusion
9703       // in the wide store. The chain we use needs to be the chain of the
9704       // earliest store node which is *used* and replaced by the wide store.
9705       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9706         EarliestNodeUsed = i;
9707     }
9708
9709     // The earliest Node in the DAG.
9710     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9711     SDLoc DL(StoreNodes[0].MemNode);
9712
9713     SDValue StoredVal;
9714     if (UseVector) {
9715       // Find a legal type for the vector store.
9716       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9717       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9718       StoredVal = DAG.getConstant(0, Ty);
9719     } else {
9720       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9721       APInt StoreInt(StoreBW, 0);
9722
9723       // Construct a single integer constant which is made of the smaller
9724       // constant inputs.
9725       bool IsLE = TLI.isLittleEndian();
9726       for (unsigned i = 0; i < NumElem ; ++i) {
9727         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9728         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9729         SDValue Val = St->getValue();
9730         StoreInt<<=ElementSizeBytes*8;
9731         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9732           StoreInt|=C->getAPIntValue().zext(StoreBW);
9733         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9734           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9735         } else {
9736           assert(false && "Invalid constant element type");
9737         }
9738       }
9739
9740       // Create the new Load and Store operations.
9741       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9742       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9743     }
9744
9745     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9746                                     FirstInChain->getBasePtr(),
9747                                     FirstInChain->getPointerInfo(),
9748                                     false, false,
9749                                     FirstInChain->getAlignment());
9750
9751     // Replace the first store with the new store
9752     CombineTo(EarliestOp, NewStore);
9753     // Erase all other stores.
9754     for (unsigned i = 0; i < NumElem ; ++i) {
9755       if (StoreNodes[i].MemNode == EarliestOp)
9756         continue;
9757       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9758       // ReplaceAllUsesWith will replace all uses that existed when it was
9759       // called, but graph optimizations may cause new ones to appear. For
9760       // example, the case in pr14333 looks like
9761       //
9762       //  St's chain -> St -> another store -> X
9763       //
9764       // And the only difference from St to the other store is the chain.
9765       // When we change it's chain to be St's chain they become identical,
9766       // get CSEed and the net result is that X is now a use of St.
9767       // Since we know that St is redundant, just iterate.
9768       while (!St->use_empty())
9769         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9770       deleteAndRecombine(St);
9771     }
9772
9773     return true;
9774   }
9775
9776   // Below we handle the case of multiple consecutive stores that
9777   // come from multiple consecutive loads. We merge them into a single
9778   // wide load and a single wide store.
9779
9780   // Look for load nodes which are used by the stored values.
9781   SmallVector<MemOpLink, 8> LoadNodes;
9782
9783   // Find acceptable loads. Loads need to have the same chain (token factor),
9784   // must not be zext, volatile, indexed, and they must be consecutive.
9785   BaseIndexOffset LdBasePtr;
9786   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9787     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9788     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9789     if (!Ld) break;
9790
9791     // Loads must only have one use.
9792     if (!Ld->hasNUsesOfValue(1, 0))
9793       break;
9794
9795     // Check that the alignment is the same as the stores.
9796     if (Ld->getAlignment() != St->getAlignment())
9797       break;
9798
9799     // The memory operands must not be volatile.
9800     if (Ld->isVolatile() || Ld->isIndexed())
9801       break;
9802
9803     // We do not accept ext loads.
9804     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9805       break;
9806
9807     // The stored memory type must be the same.
9808     if (Ld->getMemoryVT() != MemVT)
9809       break;
9810
9811     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9812     // If this is not the first ptr that we check.
9813     if (LdBasePtr.Base.getNode()) {
9814       // The base ptr must be the same.
9815       if (!LdPtr.equalBaseIndex(LdBasePtr))
9816         break;
9817     } else {
9818       // Check that all other base pointers are the same as this one.
9819       LdBasePtr = LdPtr;
9820     }
9821
9822     // We found a potential memory operand to merge.
9823     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9824   }
9825
9826   if (LoadNodes.size() < 2)
9827     return false;
9828
9829   // If we have load/store pair instructions and we only have two values,
9830   // don't bother.
9831   unsigned RequiredAlignment;
9832   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9833       St->getAlignment() >= RequiredAlignment)
9834     return false;
9835
9836   // Scan the memory operations on the chain and find the first non-consecutive
9837   // load memory address. These variables hold the index in the store node
9838   // array.
9839   unsigned LastConsecutiveLoad = 0;
9840   // This variable refers to the size and not index in the array.
9841   unsigned LastLegalVectorType = 0;
9842   unsigned LastLegalIntegerType = 0;
9843   StartAddress = LoadNodes[0].OffsetFromBase;
9844   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9845   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9846     // All loads much share the same chain.
9847     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9848       break;
9849
9850     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9851     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9852       break;
9853     LastConsecutiveLoad = i;
9854
9855     // Find a legal type for the vector store.
9856     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9857     if (TLI.isTypeLegal(StoreTy))
9858       LastLegalVectorType = i + 1;
9859
9860     // Find a legal type for the integer store.
9861     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9862     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9863     if (TLI.isTypeLegal(StoreTy))
9864       LastLegalIntegerType = i + 1;
9865     // Or check whether a truncstore and extload is legal.
9866     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9867              TargetLowering::TypePromoteInteger) {
9868       EVT LegalizedStoredValueTy =
9869         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9870       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9871           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9872           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9873           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9874         LastLegalIntegerType = i+1;
9875     }
9876   }
9877
9878   // Only use vector types if the vector type is larger than the integer type.
9879   // If they are the same, use integers.
9880   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9881   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9882
9883   // We add +1 here because the LastXXX variables refer to location while
9884   // the NumElem refers to array/index size.
9885   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9886   NumElem = std::min(LastLegalType, NumElem);
9887
9888   if (NumElem < 2)
9889     return false;
9890
9891   // The earliest Node in the DAG.
9892   unsigned EarliestNodeUsed = 0;
9893   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9894   for (unsigned i=1; i<NumElem; ++i) {
9895     // Find a chain for the new wide-store operand. Notice that some
9896     // of the store nodes that we found may not be selected for inclusion
9897     // in the wide store. The chain we use needs to be the chain of the
9898     // earliest store node which is *used* and replaced by the wide store.
9899     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9900       EarliestNodeUsed = i;
9901   }
9902
9903   // Find if it is better to use vectors or integers to load and store
9904   // to memory.
9905   EVT JointMemOpVT;
9906   if (UseVectorTy) {
9907     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9908   } else {
9909     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9910     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9911   }
9912
9913   SDLoc LoadDL(LoadNodes[0].MemNode);
9914   SDLoc StoreDL(StoreNodes[0].MemNode);
9915
9916   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9917   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9918                                 FirstLoad->getChain(),
9919                                 FirstLoad->getBasePtr(),
9920                                 FirstLoad->getPointerInfo(),
9921                                 false, false, false,
9922                                 FirstLoad->getAlignment());
9923
9924   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9925                                   FirstInChain->getBasePtr(),
9926                                   FirstInChain->getPointerInfo(), false, false,
9927                                   FirstInChain->getAlignment());
9928
9929   // Replace one of the loads with the new load.
9930   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9931   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9932                                 SDValue(NewLoad.getNode(), 1));
9933
9934   // Remove the rest of the load chains.
9935   for (unsigned i = 1; i < NumElem ; ++i) {
9936     // Replace all chain users of the old load nodes with the chain of the new
9937     // load node.
9938     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9939     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9940   }
9941
9942   // Replace the first store with the new store.
9943   CombineTo(EarliestOp, NewStore);
9944   // Erase all other stores.
9945   for (unsigned i = 0; i < NumElem ; ++i) {
9946     // Remove all Store nodes.
9947     if (StoreNodes[i].MemNode == EarliestOp)
9948       continue;
9949     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9950     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9951     deleteAndRecombine(St);
9952   }
9953
9954   return true;
9955 }
9956
9957 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9958   StoreSDNode *ST  = cast<StoreSDNode>(N);
9959   SDValue Chain = ST->getChain();
9960   SDValue Value = ST->getValue();
9961   SDValue Ptr   = ST->getBasePtr();
9962
9963   // If this is a store of a bit convert, store the input value if the
9964   // resultant store does not need a higher alignment than the original.
9965   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9966       ST->isUnindexed()) {
9967     unsigned OrigAlign = ST->getAlignment();
9968     EVT SVT = Value.getOperand(0).getValueType();
9969     unsigned Align = TLI.getDataLayout()->
9970       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9971     if (Align <= OrigAlign &&
9972         ((!LegalOperations && !ST->isVolatile()) ||
9973          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9974       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9975                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9976                           ST->isNonTemporal(), OrigAlign,
9977                           ST->getAAInfo());
9978   }
9979
9980   // Turn 'store undef, Ptr' -> nothing.
9981   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9982     return Chain;
9983
9984   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9985   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9986     // NOTE: If the original store is volatile, this transform must not increase
9987     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9988     // processor operation but an i64 (which is not legal) requires two.  So the
9989     // transform should not be done in this case.
9990     if (Value.getOpcode() != ISD::TargetConstantFP) {
9991       SDValue Tmp;
9992       switch (CFP->getSimpleValueType(0).SimpleTy) {
9993       default: llvm_unreachable("Unknown FP type");
9994       case MVT::f16:    // We don't do this for these yet.
9995       case MVT::f80:
9996       case MVT::f128:
9997       case MVT::ppcf128:
9998         break;
9999       case MVT::f32:
10000         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
10001             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10002           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
10003                               bitcastToAPInt().getZExtValue(), MVT::i32);
10004           return DAG.getStore(Chain, SDLoc(N), Tmp,
10005                               Ptr, ST->getMemOperand());
10006         }
10007         break;
10008       case MVT::f64:
10009         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
10010              !ST->isVolatile()) ||
10011             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
10012           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
10013                                 getZExtValue(), MVT::i64);
10014           return DAG.getStore(Chain, SDLoc(N), Tmp,
10015                               Ptr, ST->getMemOperand());
10016         }
10017
10018         if (!ST->isVolatile() &&
10019             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
10020           // Many FP stores are not made apparent until after legalize, e.g. for
10021           // argument passing.  Since this is so common, custom legalize the
10022           // 64-bit integer store into two 32-bit stores.
10023           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
10024           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
10025           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
10026           if (TLI.isBigEndian()) std::swap(Lo, Hi);
10027
10028           unsigned Alignment = ST->getAlignment();
10029           bool isVolatile = ST->isVolatile();
10030           bool isNonTemporal = ST->isNonTemporal();
10031           AAMDNodes AAInfo = ST->getAAInfo();
10032
10033           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
10034                                      Ptr, ST->getPointerInfo(),
10035                                      isVolatile, isNonTemporal,
10036                                      ST->getAlignment(), AAInfo);
10037           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
10038                             DAG.getConstant(4, Ptr.getValueType()));
10039           Alignment = MinAlign(Alignment, 4U);
10040           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
10041                                      Ptr, ST->getPointerInfo().getWithOffset(4),
10042                                      isVolatile, isNonTemporal,
10043                                      Alignment, AAInfo);
10044           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
10045                              St0, St1);
10046         }
10047
10048         break;
10049       }
10050     }
10051   }
10052
10053   // Try to infer better alignment information than the store already has.
10054   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
10055     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
10056       if (Align > ST->getAlignment())
10057         return DAG.getTruncStore(Chain, SDLoc(N), Value,
10058                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
10059                                  ST->isVolatile(), ST->isNonTemporal(), Align,
10060                                  ST->getAAInfo());
10061     }
10062   }
10063
10064   // Try transforming a pair floating point load / store ops to integer
10065   // load / store ops.
10066   SDValue NewST = TransformFPLoadStorePair(N);
10067   if (NewST.getNode())
10068     return NewST;
10069
10070   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
10071                                                   : DAG.getSubtarget().useAA();
10072 #ifndef NDEBUG
10073   if (CombinerAAOnlyFunc.getNumOccurrences() &&
10074       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
10075     UseAA = false;
10076 #endif
10077   if (UseAA && ST->isUnindexed()) {
10078     // Walk up chain skipping non-aliasing memory nodes.
10079     SDValue BetterChain = FindBetterChain(N, Chain);
10080
10081     // If there is a better chain.
10082     if (Chain != BetterChain) {
10083       SDValue ReplStore;
10084
10085       // Replace the chain to avoid dependency.
10086       if (ST->isTruncatingStore()) {
10087         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
10088                                       ST->getMemoryVT(), ST->getMemOperand());
10089       } else {
10090         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
10091                                  ST->getMemOperand());
10092       }
10093
10094       // Create token to keep both nodes around.
10095       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
10096                                   MVT::Other, Chain, ReplStore);
10097
10098       // Make sure the new and old chains are cleaned up.
10099       AddToWorklist(Token.getNode());
10100
10101       // Don't add users to work list.
10102       return CombineTo(N, Token, false);
10103     }
10104   }
10105
10106   // Try transforming N to an indexed store.
10107   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
10108     return SDValue(N, 0);
10109
10110   // FIXME: is there such a thing as a truncating indexed store?
10111   if (ST->isTruncatingStore() && ST->isUnindexed() &&
10112       Value.getValueType().isInteger()) {
10113     // See if we can simplify the input to this truncstore with knowledge that
10114     // only the low bits are being used.  For example:
10115     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
10116     SDValue Shorter =
10117       GetDemandedBits(Value,
10118                       APInt::getLowBitsSet(
10119                         Value.getValueType().getScalarType().getSizeInBits(),
10120                         ST->getMemoryVT().getScalarType().getSizeInBits()));
10121     AddToWorklist(Value.getNode());
10122     if (Shorter.getNode())
10123       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
10124                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
10125
10126     // Otherwise, see if we can simplify the operation with
10127     // SimplifyDemandedBits, which only works if the value has a single use.
10128     if (SimplifyDemandedBits(Value,
10129                         APInt::getLowBitsSet(
10130                           Value.getValueType().getScalarType().getSizeInBits(),
10131                           ST->getMemoryVT().getScalarType().getSizeInBits())))
10132       return SDValue(N, 0);
10133   }
10134
10135   // If this is a load followed by a store to the same location, then the store
10136   // is dead/noop.
10137   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
10138     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
10139         ST->isUnindexed() && !ST->isVolatile() &&
10140         // There can't be any side effects between the load and store, such as
10141         // a call or store.
10142         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
10143       // The store is dead, remove it.
10144       return Chain;
10145     }
10146   }
10147
10148   // If this is a store followed by a store with the same value to the same
10149   // location, then the store is dead/noop.
10150   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
10151     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
10152         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
10153         ST1->isUnindexed() && !ST1->isVolatile()) {
10154       // The store is dead, remove it.
10155       return Chain;
10156     }
10157   }
10158
10159   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
10160   // truncating store.  We can do this even if this is already a truncstore.
10161   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10162       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10163       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10164                             ST->getMemoryVT())) {
10165     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10166                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10167   }
10168
10169   // Only perform this optimization before the types are legal, because we
10170   // don't want to perform this optimization on every DAGCombine invocation.
10171   if (!LegalTypes) {
10172     bool EverChanged = false;
10173
10174     do {
10175       // There can be multiple store sequences on the same chain.
10176       // Keep trying to merge store sequences until we are unable to do so
10177       // or until we merge the last store on the chain.
10178       bool Changed = MergeConsecutiveStores(ST);
10179       EverChanged |= Changed;
10180       if (!Changed) break;
10181     } while (ST->getOpcode() != ISD::DELETED_NODE);
10182
10183     if (EverChanged)
10184       return SDValue(N, 0);
10185   }
10186
10187   return ReduceLoadOpStoreWidth(N);
10188 }
10189
10190 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10191   SDValue InVec = N->getOperand(0);
10192   SDValue InVal = N->getOperand(1);
10193   SDValue EltNo = N->getOperand(2);
10194   SDLoc dl(N);
10195
10196   // If the inserted element is an UNDEF, just use the input vector.
10197   if (InVal.getOpcode() == ISD::UNDEF)
10198     return InVec;
10199
10200   EVT VT = InVec.getValueType();
10201
10202   // If we can't generate a legal BUILD_VECTOR, exit
10203   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10204     return SDValue();
10205
10206   // Check that we know which element is being inserted
10207   if (!isa<ConstantSDNode>(EltNo))
10208     return SDValue();
10209   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10210
10211   // Canonicalize insert_vector_elt dag nodes.
10212   // Example:
10213   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10214   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10215   //
10216   // Do this only if the child insert_vector node has one use; also
10217   // do this only if indices are both constants and Idx1 < Idx0.
10218   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10219       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10220     unsigned OtherElt =
10221       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10222     if (Elt < OtherElt) {
10223       // Swap nodes.
10224       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10225                                   InVec.getOperand(0), InVal, EltNo);
10226       AddToWorklist(NewOp.getNode());
10227       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10228                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10229     }
10230   }
10231
10232   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10233   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10234   // vector elements.
10235   SmallVector<SDValue, 8> Ops;
10236   // Do not combine these two vectors if the output vector will not replace
10237   // the input vector.
10238   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10239     Ops.append(InVec.getNode()->op_begin(),
10240                InVec.getNode()->op_end());
10241   } else if (InVec.getOpcode() == ISD::UNDEF) {
10242     unsigned NElts = VT.getVectorNumElements();
10243     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10244   } else {
10245     return SDValue();
10246   }
10247
10248   // Insert the element
10249   if (Elt < Ops.size()) {
10250     // All the operands of BUILD_VECTOR must have the same type;
10251     // we enforce that here.
10252     EVT OpVT = Ops[0].getValueType();
10253     if (InVal.getValueType() != OpVT)
10254       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10255                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10256                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10257     Ops[Elt] = InVal;
10258   }
10259
10260   // Return the new vector
10261   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10262 }
10263
10264 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10265     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10266   EVT ResultVT = EVE->getValueType(0);
10267   EVT VecEltVT = InVecVT.getVectorElementType();
10268   unsigned Align = OriginalLoad->getAlignment();
10269   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10270       VecEltVT.getTypeForEVT(*DAG.getContext()));
10271
10272   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10273     return SDValue();
10274
10275   Align = NewAlign;
10276
10277   SDValue NewPtr = OriginalLoad->getBasePtr();
10278   SDValue Offset;
10279   EVT PtrType = NewPtr.getValueType();
10280   MachinePointerInfo MPI;
10281   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10282     int Elt = ConstEltNo->getZExtValue();
10283     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10284     if (TLI.isBigEndian())
10285       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10286     Offset = DAG.getConstant(PtrOff, PtrType);
10287     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10288   } else {
10289     Offset = DAG.getNode(
10290         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10291         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10292     if (TLI.isBigEndian())
10293       Offset = DAG.getNode(
10294           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10295           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10296     MPI = OriginalLoad->getPointerInfo();
10297   }
10298   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10299
10300   // The replacement we need to do here is a little tricky: we need to
10301   // replace an extractelement of a load with a load.
10302   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10303   // Note that this replacement assumes that the extractvalue is the only
10304   // use of the load; that's okay because we don't want to perform this
10305   // transformation in other cases anyway.
10306   SDValue Load;
10307   SDValue Chain;
10308   if (ResultVT.bitsGT(VecEltVT)) {
10309     // If the result type of vextract is wider than the load, then issue an
10310     // extending load instead.
10311     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10312                                    ? ISD::ZEXTLOAD
10313                                    : ISD::EXTLOAD;
10314     Load = DAG.getExtLoad(
10315         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10316         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10317         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10318     Chain = Load.getValue(1);
10319   } else {
10320     Load = DAG.getLoad(
10321         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10322         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10323         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10324     Chain = Load.getValue(1);
10325     if (ResultVT.bitsLT(VecEltVT))
10326       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10327     else
10328       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10329   }
10330   WorklistRemover DeadNodes(*this);
10331   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10332   SDValue To[] = { Load, Chain };
10333   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10334   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10335   // worklist explicitly as well.
10336   AddToWorklist(Load.getNode());
10337   AddUsersToWorklist(Load.getNode()); // Add users too
10338   // Make sure to revisit this node to clean it up; it will usually be dead.
10339   AddToWorklist(EVE);
10340   ++OpsNarrowed;
10341   return SDValue(EVE, 0);
10342 }
10343
10344 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10345   // (vextract (scalar_to_vector val, 0) -> val
10346   SDValue InVec = N->getOperand(0);
10347   EVT VT = InVec.getValueType();
10348   EVT NVT = N->getValueType(0);
10349
10350   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10351     // Check if the result type doesn't match the inserted element type. A
10352     // SCALAR_TO_VECTOR may truncate the inserted element and the
10353     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10354     SDValue InOp = InVec.getOperand(0);
10355     if (InOp.getValueType() != NVT) {
10356       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10357       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10358     }
10359     return InOp;
10360   }
10361
10362   SDValue EltNo = N->getOperand(1);
10363   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10364
10365   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10366   // We only perform this optimization before the op legalization phase because
10367   // we may introduce new vector instructions which are not backed by TD
10368   // patterns. For example on AVX, extracting elements from a wide vector
10369   // without using extract_subvector. However, if we can find an underlying
10370   // scalar value, then we can always use that.
10371   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10372       && ConstEltNo) {
10373     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10374     int NumElem = VT.getVectorNumElements();
10375     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10376     // Find the new index to extract from.
10377     int OrigElt = SVOp->getMaskElt(Elt);
10378
10379     // Extracting an undef index is undef.
10380     if (OrigElt == -1)
10381       return DAG.getUNDEF(NVT);
10382
10383     // Select the right vector half to extract from.
10384     SDValue SVInVec;
10385     if (OrigElt < NumElem) {
10386       SVInVec = InVec->getOperand(0);
10387     } else {
10388       SVInVec = InVec->getOperand(1);
10389       OrigElt -= NumElem;
10390     }
10391
10392     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10393       SDValue InOp = SVInVec.getOperand(OrigElt);
10394       if (InOp.getValueType() != NVT) {
10395         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10396         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10397       }
10398
10399       return InOp;
10400     }
10401
10402     // FIXME: We should handle recursing on other vector shuffles and
10403     // scalar_to_vector here as well.
10404
10405     if (!LegalOperations) {
10406       EVT IndexTy = TLI.getVectorIdxTy();
10407       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10408                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10409     }
10410   }
10411
10412   bool BCNumEltsChanged = false;
10413   EVT ExtVT = VT.getVectorElementType();
10414   EVT LVT = ExtVT;
10415
10416   // If the result of load has to be truncated, then it's not necessarily
10417   // profitable.
10418   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10419     return SDValue();
10420
10421   if (InVec.getOpcode() == ISD::BITCAST) {
10422     // Don't duplicate a load with other uses.
10423     if (!InVec.hasOneUse())
10424       return SDValue();
10425
10426     EVT BCVT = InVec.getOperand(0).getValueType();
10427     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10428       return SDValue();
10429     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10430       BCNumEltsChanged = true;
10431     InVec = InVec.getOperand(0);
10432     ExtVT = BCVT.getVectorElementType();
10433   }
10434
10435   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10436   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10437       ISD::isNormalLoad(InVec.getNode()) &&
10438       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10439     SDValue Index = N->getOperand(1);
10440     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10441       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10442                                                            OrigLoad);
10443   }
10444
10445   // Perform only after legalization to ensure build_vector / vector_shuffle
10446   // optimizations have already been done.
10447   if (!LegalOperations) return SDValue();
10448
10449   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10450   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10451   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10452
10453   if (ConstEltNo) {
10454     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10455
10456     LoadSDNode *LN0 = nullptr;
10457     const ShuffleVectorSDNode *SVN = nullptr;
10458     if (ISD::isNormalLoad(InVec.getNode())) {
10459       LN0 = cast<LoadSDNode>(InVec);
10460     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10461                InVec.getOperand(0).getValueType() == ExtVT &&
10462                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10463       // Don't duplicate a load with other uses.
10464       if (!InVec.hasOneUse())
10465         return SDValue();
10466
10467       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10468     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10469       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10470       // =>
10471       // (load $addr+1*size)
10472
10473       // Don't duplicate a load with other uses.
10474       if (!InVec.hasOneUse())
10475         return SDValue();
10476
10477       // If the bit convert changed the number of elements, it is unsafe
10478       // to examine the mask.
10479       if (BCNumEltsChanged)
10480         return SDValue();
10481
10482       // Select the input vector, guarding against out of range extract vector.
10483       unsigned NumElems = VT.getVectorNumElements();
10484       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10485       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10486
10487       if (InVec.getOpcode() == ISD::BITCAST) {
10488         // Don't duplicate a load with other uses.
10489         if (!InVec.hasOneUse())
10490           return SDValue();
10491
10492         InVec = InVec.getOperand(0);
10493       }
10494       if (ISD::isNormalLoad(InVec.getNode())) {
10495         LN0 = cast<LoadSDNode>(InVec);
10496         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10497         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10498       }
10499     }
10500
10501     // Make sure we found a non-volatile load and the extractelement is
10502     // the only use.
10503     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10504       return SDValue();
10505
10506     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10507     if (Elt == -1)
10508       return DAG.getUNDEF(LVT);
10509
10510     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10511   }
10512
10513   return SDValue();
10514 }
10515
10516 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10517 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10518   // We perform this optimization post type-legalization because
10519   // the type-legalizer often scalarizes integer-promoted vectors.
10520   // Performing this optimization before may create bit-casts which
10521   // will be type-legalized to complex code sequences.
10522   // We perform this optimization only before the operation legalizer because we
10523   // may introduce illegal operations.
10524   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10525     return SDValue();
10526
10527   unsigned NumInScalars = N->getNumOperands();
10528   SDLoc dl(N);
10529   EVT VT = N->getValueType(0);
10530
10531   // Check to see if this is a BUILD_VECTOR of a bunch of values
10532   // which come from any_extend or zero_extend nodes. If so, we can create
10533   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10534   // optimizations. We do not handle sign-extend because we can't fill the sign
10535   // using shuffles.
10536   EVT SourceType = MVT::Other;
10537   bool AllAnyExt = true;
10538
10539   for (unsigned i = 0; i != NumInScalars; ++i) {
10540     SDValue In = N->getOperand(i);
10541     // Ignore undef inputs.
10542     if (In.getOpcode() == ISD::UNDEF) continue;
10543
10544     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10545     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10546
10547     // Abort if the element is not an extension.
10548     if (!ZeroExt && !AnyExt) {
10549       SourceType = MVT::Other;
10550       break;
10551     }
10552
10553     // The input is a ZeroExt or AnyExt. Check the original type.
10554     EVT InTy = In.getOperand(0).getValueType();
10555
10556     // Check that all of the widened source types are the same.
10557     if (SourceType == MVT::Other)
10558       // First time.
10559       SourceType = InTy;
10560     else if (InTy != SourceType) {
10561       // Multiple income types. Abort.
10562       SourceType = MVT::Other;
10563       break;
10564     }
10565
10566     // Check if all of the extends are ANY_EXTENDs.
10567     AllAnyExt &= AnyExt;
10568   }
10569
10570   // In order to have valid types, all of the inputs must be extended from the
10571   // same source type and all of the inputs must be any or zero extend.
10572   // Scalar sizes must be a power of two.
10573   EVT OutScalarTy = VT.getScalarType();
10574   bool ValidTypes = SourceType != MVT::Other &&
10575                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10576                  isPowerOf2_32(SourceType.getSizeInBits());
10577
10578   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10579   // turn into a single shuffle instruction.
10580   if (!ValidTypes)
10581     return SDValue();
10582
10583   bool isLE = TLI.isLittleEndian();
10584   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10585   assert(ElemRatio > 1 && "Invalid element size ratio");
10586   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10587                                DAG.getConstant(0, SourceType);
10588
10589   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10590   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10591
10592   // Populate the new build_vector
10593   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10594     SDValue Cast = N->getOperand(i);
10595     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10596             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10597             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10598     SDValue In;
10599     if (Cast.getOpcode() == ISD::UNDEF)
10600       In = DAG.getUNDEF(SourceType);
10601     else
10602       In = Cast->getOperand(0);
10603     unsigned Index = isLE ? (i * ElemRatio) :
10604                             (i * ElemRatio + (ElemRatio - 1));
10605
10606     assert(Index < Ops.size() && "Invalid index");
10607     Ops[Index] = In;
10608   }
10609
10610   // The type of the new BUILD_VECTOR node.
10611   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10612   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10613          "Invalid vector size");
10614   // Check if the new vector type is legal.
10615   if (!isTypeLegal(VecVT)) return SDValue();
10616
10617   // Make the new BUILD_VECTOR.
10618   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10619
10620   // The new BUILD_VECTOR node has the potential to be further optimized.
10621   AddToWorklist(BV.getNode());
10622   // Bitcast to the desired type.
10623   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10624 }
10625
10626 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10627   EVT VT = N->getValueType(0);
10628
10629   unsigned NumInScalars = N->getNumOperands();
10630   SDLoc dl(N);
10631
10632   EVT SrcVT = MVT::Other;
10633   unsigned Opcode = ISD::DELETED_NODE;
10634   unsigned NumDefs = 0;
10635
10636   for (unsigned i = 0; i != NumInScalars; ++i) {
10637     SDValue In = N->getOperand(i);
10638     unsigned Opc = In.getOpcode();
10639
10640     if (Opc == ISD::UNDEF)
10641       continue;
10642
10643     // If all scalar values are floats and converted from integers.
10644     if (Opcode == ISD::DELETED_NODE &&
10645         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10646       Opcode = Opc;
10647     }
10648
10649     if (Opc != Opcode)
10650       return SDValue();
10651
10652     EVT InVT = In.getOperand(0).getValueType();
10653
10654     // If all scalar values are typed differently, bail out. It's chosen to
10655     // simplify BUILD_VECTOR of integer types.
10656     if (SrcVT == MVT::Other)
10657       SrcVT = InVT;
10658     if (SrcVT != InVT)
10659       return SDValue();
10660     NumDefs++;
10661   }
10662
10663   // If the vector has just one element defined, it's not worth to fold it into
10664   // a vectorized one.
10665   if (NumDefs < 2)
10666     return SDValue();
10667
10668   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10669          && "Should only handle conversion from integer to float.");
10670   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10671
10672   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10673
10674   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10675     return SDValue();
10676
10677   SmallVector<SDValue, 8> Opnds;
10678   for (unsigned i = 0; i != NumInScalars; ++i) {
10679     SDValue In = N->getOperand(i);
10680
10681     if (In.getOpcode() == ISD::UNDEF)
10682       Opnds.push_back(DAG.getUNDEF(SrcVT));
10683     else
10684       Opnds.push_back(In.getOperand(0));
10685   }
10686   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10687   AddToWorklist(BV.getNode());
10688
10689   return DAG.getNode(Opcode, dl, VT, BV);
10690 }
10691
10692 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10693   unsigned NumInScalars = N->getNumOperands();
10694   SDLoc dl(N);
10695   EVT VT = N->getValueType(0);
10696
10697   // A vector built entirely of undefs is undef.
10698   if (ISD::allOperandsUndef(N))
10699     return DAG.getUNDEF(VT);
10700
10701   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10702   if (V.getNode())
10703     return V;
10704
10705   V = reduceBuildVecConvertToConvertBuildVec(N);
10706   if (V.getNode())
10707     return V;
10708
10709   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10710   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10711   // at most two distinct vectors, turn this into a shuffle node.
10712
10713   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10714   if (!isTypeLegal(VT))
10715     return SDValue();
10716
10717   // May only combine to shuffle after legalize if shuffle is legal.
10718   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10719     return SDValue();
10720
10721   SDValue VecIn1, VecIn2;
10722   bool UsesZeroVector = false;
10723   for (unsigned i = 0; i != NumInScalars; ++i) {
10724     SDValue Op = N->getOperand(i);
10725     // Ignore undef inputs.
10726     if (Op.getOpcode() == ISD::UNDEF) continue;
10727
10728     // See if we can combine this build_vector into a blend with a zero vector.
10729     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10730         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10731         (Op.getOpcode() == ISD::ConstantFP &&
10732         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10733       UsesZeroVector = true;
10734       continue;
10735     }
10736
10737     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10738     // constant index, bail out.
10739     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10740         !isa<ConstantSDNode>(Op.getOperand(1))) {
10741       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10742       break;
10743     }
10744
10745     // We allow up to two distinct input vectors.
10746     SDValue ExtractedFromVec = Op.getOperand(0);
10747     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10748       continue;
10749
10750     if (!VecIn1.getNode()) {
10751       VecIn1 = ExtractedFromVec;
10752     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10753       VecIn2 = ExtractedFromVec;
10754     } else {
10755       // Too many inputs.
10756       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10757       break;
10758     }
10759   }
10760
10761   // If everything is good, we can make a shuffle operation.
10762   if (VecIn1.getNode()) {
10763     SmallVector<int, 8> Mask;
10764     for (unsigned i = 0; i != NumInScalars; ++i) {
10765       unsigned Opcode = N->getOperand(i).getOpcode();
10766       if (Opcode == ISD::UNDEF) {
10767         Mask.push_back(-1);
10768         continue;
10769       }
10770
10771       // Operands can also be zero.
10772       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10773         assert(UsesZeroVector &&
10774                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10775                "Unexpected node found!");
10776         Mask.push_back(NumInScalars+i);
10777         continue;
10778       }
10779
10780       // If extracting from the first vector, just use the index directly.
10781       SDValue Extract = N->getOperand(i);
10782       SDValue ExtVal = Extract.getOperand(1);
10783       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10784       if (Extract.getOperand(0) == VecIn1) {
10785         if (ExtIndex > VT.getVectorNumElements())
10786           return SDValue();
10787
10788         Mask.push_back(ExtIndex);
10789         continue;
10790       }
10791
10792       // Otherwise, use InIdx + VecSize
10793       Mask.push_back(NumInScalars+ExtIndex);
10794     }
10795
10796     // Avoid introducing illegal shuffles with zero.
10797     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10798       return SDValue();
10799
10800     // We can't generate a shuffle node with mismatched input and output types.
10801     // Attempt to transform a single input vector to the correct type.
10802     if ((VT != VecIn1.getValueType())) {
10803       // We don't support shuffeling between TWO values of different types.
10804       if (VecIn2.getNode())
10805         return SDValue();
10806
10807       // We only support widening of vectors which are half the size of the
10808       // output registers. For example XMM->YMM widening on X86 with AVX.
10809       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10810         return SDValue();
10811
10812       // If the input vector type has a different base type to the output
10813       // vector type, bail out.
10814       if (VecIn1.getValueType().getVectorElementType() !=
10815           VT.getVectorElementType())
10816         return SDValue();
10817
10818       // Widen the input vector by adding undef values.
10819       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10820                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10821     }
10822
10823     if (UsesZeroVector)
10824       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10825                                 DAG.getConstantFP(0.0, VT);
10826     else
10827       // If VecIn2 is unused then change it to undef.
10828       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10829
10830     // Check that we were able to transform all incoming values to the same
10831     // type.
10832     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10833         VecIn1.getValueType() != VT)
10834           return SDValue();
10835
10836     // Return the new VECTOR_SHUFFLE node.
10837     SDValue Ops[2];
10838     Ops[0] = VecIn1;
10839     Ops[1] = VecIn2;
10840     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10841   }
10842
10843   return SDValue();
10844 }
10845
10846 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10847   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10848   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10849   // inputs come from at most two distinct vectors, turn this into a shuffle
10850   // node.
10851
10852   // If we only have one input vector, we don't need to do any concatenation.
10853   if (N->getNumOperands() == 1)
10854     return N->getOperand(0);
10855
10856   // Check if all of the operands are undefs.
10857   EVT VT = N->getValueType(0);
10858   if (ISD::allOperandsUndef(N))
10859     return DAG.getUNDEF(VT);
10860
10861   // Optimize concat_vectors where one of the vectors is undef.
10862   if (N->getNumOperands() == 2 &&
10863       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10864     SDValue In = N->getOperand(0);
10865     assert(In.getValueType().isVector() && "Must concat vectors");
10866
10867     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10868     if (In->getOpcode() == ISD::BITCAST &&
10869         !In->getOperand(0)->getValueType(0).isVector()) {
10870       SDValue Scalar = In->getOperand(0);
10871       EVT SclTy = Scalar->getValueType(0);
10872
10873       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10874         return SDValue();
10875
10876       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10877                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10878       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10879         return SDValue();
10880
10881       SDLoc dl = SDLoc(N);
10882       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10883       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10884     }
10885   }
10886
10887   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10888   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10889   if (N->getNumOperands() == 2 &&
10890       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10891       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10892     EVT VT = N->getValueType(0);
10893     SDValue N0 = N->getOperand(0);
10894     SDValue N1 = N->getOperand(1);
10895     SmallVector<SDValue, 8> Opnds;
10896     unsigned BuildVecNumElts =  N0.getNumOperands();
10897
10898     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10899     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10900     if (SclTy0.isFloatingPoint()) {
10901       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10902         Opnds.push_back(N0.getOperand(i));
10903       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10904         Opnds.push_back(N1.getOperand(i));
10905     } else {
10906       // If BUILD_VECTOR are from built from integer, they may have different
10907       // operand types. Get the smaller type and truncate all operands to it.
10908       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10909       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10910         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10911                         N0.getOperand(i)));
10912       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10913         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10914                         N1.getOperand(i)));
10915     }
10916
10917     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10918   }
10919
10920   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10921   // nodes often generate nop CONCAT_VECTOR nodes.
10922   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10923   // place the incoming vectors at the exact same location.
10924   SDValue SingleSource = SDValue();
10925   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10926
10927   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10928     SDValue Op = N->getOperand(i);
10929
10930     if (Op.getOpcode() == ISD::UNDEF)
10931       continue;
10932
10933     // Check if this is the identity extract:
10934     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10935       return SDValue();
10936
10937     // Find the single incoming vector for the extract_subvector.
10938     if (SingleSource.getNode()) {
10939       if (Op.getOperand(0) != SingleSource)
10940         return SDValue();
10941     } else {
10942       SingleSource = Op.getOperand(0);
10943
10944       // Check the source type is the same as the type of the result.
10945       // If not, this concat may extend the vector, so we can not
10946       // optimize it away.
10947       if (SingleSource.getValueType() != N->getValueType(0))
10948         return SDValue();
10949     }
10950
10951     unsigned IdentityIndex = i * PartNumElem;
10952     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10953     // The extract index must be constant.
10954     if (!CS)
10955       return SDValue();
10956
10957     // Check that we are reading from the identity index.
10958     if (CS->getZExtValue() != IdentityIndex)
10959       return SDValue();
10960   }
10961
10962   if (SingleSource.getNode())
10963     return SingleSource;
10964
10965   return SDValue();
10966 }
10967
10968 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10969   EVT NVT = N->getValueType(0);
10970   SDValue V = N->getOperand(0);
10971
10972   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10973     // Combine:
10974     //    (extract_subvec (concat V1, V2, ...), i)
10975     // Into:
10976     //    Vi if possible
10977     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10978     // type.
10979     if (V->getOperand(0).getValueType() != NVT)
10980       return SDValue();
10981     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10982     unsigned NumElems = NVT.getVectorNumElements();
10983     assert((Idx % NumElems) == 0 &&
10984            "IDX in concat is not a multiple of the result vector length.");
10985     return V->getOperand(Idx / NumElems);
10986   }
10987
10988   // Skip bitcasting
10989   if (V->getOpcode() == ISD::BITCAST)
10990     V = V.getOperand(0);
10991
10992   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10993     SDLoc dl(N);
10994     // Handle only simple case where vector being inserted and vector
10995     // being extracted are of same type, and are half size of larger vectors.
10996     EVT BigVT = V->getOperand(0).getValueType();
10997     EVT SmallVT = V->getOperand(1).getValueType();
10998     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10999       return SDValue();
11000
11001     // Only handle cases where both indexes are constants with the same type.
11002     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
11003     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
11004
11005     if (InsIdx && ExtIdx &&
11006         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
11007         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
11008       // Combine:
11009       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
11010       // Into:
11011       //    indices are equal or bit offsets are equal => V1
11012       //    otherwise => (extract_subvec V1, ExtIdx)
11013       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
11014           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
11015         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
11016       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
11017                          DAG.getNode(ISD::BITCAST, dl,
11018                                      N->getOperand(0).getValueType(),
11019                                      V->getOperand(0)), N->getOperand(1));
11020     }
11021   }
11022
11023   return SDValue();
11024 }
11025
11026 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
11027                                                  SDValue V, SelectionDAG &DAG) {
11028   SDLoc DL(V);
11029   EVT VT = V.getValueType();
11030
11031   switch (V.getOpcode()) {
11032   default:
11033     return V;
11034
11035   case ISD::CONCAT_VECTORS: {
11036     EVT OpVT = V->getOperand(0).getValueType();
11037     int OpSize = OpVT.getVectorNumElements();
11038     SmallBitVector OpUsedElements(OpSize, false);
11039     bool FoundSimplification = false;
11040     SmallVector<SDValue, 4> NewOps;
11041     NewOps.reserve(V->getNumOperands());
11042     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
11043       SDValue Op = V->getOperand(i);
11044       bool OpUsed = false;
11045       for (int j = 0; j < OpSize; ++j)
11046         if (UsedElements[i * OpSize + j]) {
11047           OpUsedElements[j] = true;
11048           OpUsed = true;
11049         }
11050       NewOps.push_back(
11051           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
11052                  : DAG.getUNDEF(OpVT));
11053       FoundSimplification |= Op == NewOps.back();
11054       OpUsedElements.reset();
11055     }
11056     if (FoundSimplification)
11057       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
11058     return V;
11059   }
11060
11061   case ISD::INSERT_SUBVECTOR: {
11062     SDValue BaseV = V->getOperand(0);
11063     SDValue SubV = V->getOperand(1);
11064     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
11065     if (!IdxN)
11066       return V;
11067
11068     int SubSize = SubV.getValueType().getVectorNumElements();
11069     int Idx = IdxN->getZExtValue();
11070     bool SubVectorUsed = false;
11071     SmallBitVector SubUsedElements(SubSize, false);
11072     for (int i = 0; i < SubSize; ++i)
11073       if (UsedElements[i + Idx]) {
11074         SubVectorUsed = true;
11075         SubUsedElements[i] = true;
11076         UsedElements[i + Idx] = false;
11077       }
11078
11079     // Now recurse on both the base and sub vectors.
11080     SDValue SimplifiedSubV =
11081         SubVectorUsed
11082             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
11083             : DAG.getUNDEF(SubV.getValueType());
11084     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
11085     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
11086       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
11087                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
11088     return V;
11089   }
11090   }
11091 }
11092
11093 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
11094                                        SDValue N1, SelectionDAG &DAG) {
11095   EVT VT = SVN->getValueType(0);
11096   int NumElts = VT.getVectorNumElements();
11097   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
11098   for (int M : SVN->getMask())
11099     if (M >= 0 && M < NumElts)
11100       N0UsedElements[M] = true;
11101     else if (M >= NumElts)
11102       N1UsedElements[M - NumElts] = true;
11103
11104   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
11105   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
11106   if (S0 == N0 && S1 == N1)
11107     return SDValue();
11108
11109   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
11110 }
11111
11112 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
11113 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
11114   EVT VT = N->getValueType(0);
11115   unsigned NumElts = VT.getVectorNumElements();
11116
11117   SDValue N0 = N->getOperand(0);
11118   SDValue N1 = N->getOperand(1);
11119   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11120
11121   SmallVector<SDValue, 4> Ops;
11122   EVT ConcatVT = N0.getOperand(0).getValueType();
11123   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
11124   unsigned NumConcats = NumElts / NumElemsPerConcat;
11125
11126   // Look at every vector that's inserted. We're looking for exact
11127   // subvector-sized copies from a concatenated vector
11128   for (unsigned I = 0; I != NumConcats; ++I) {
11129     // Make sure we're dealing with a copy.
11130     unsigned Begin = I * NumElemsPerConcat;
11131     bool AllUndef = true, NoUndef = true;
11132     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
11133       if (SVN->getMaskElt(J) >= 0)
11134         AllUndef = false;
11135       else
11136         NoUndef = false;
11137     }
11138
11139     if (NoUndef) {
11140       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
11141         return SDValue();
11142
11143       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
11144         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
11145           return SDValue();
11146
11147       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
11148       if (FirstElt < N0.getNumOperands())
11149         Ops.push_back(N0.getOperand(FirstElt));
11150       else
11151         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
11152
11153     } else if (AllUndef) {
11154       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
11155     } else { // Mixed with general masks and undefs, can't do optimization.
11156       return SDValue();
11157     }
11158   }
11159
11160   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
11161 }
11162
11163 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11164   EVT VT = N->getValueType(0);
11165   unsigned NumElts = VT.getVectorNumElements();
11166
11167   SDValue N0 = N->getOperand(0);
11168   SDValue N1 = N->getOperand(1);
11169
11170   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11171
11172   // Canonicalize shuffle undef, undef -> undef
11173   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11174     return DAG.getUNDEF(VT);
11175
11176   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11177
11178   // Canonicalize shuffle v, v -> v, undef
11179   if (N0 == N1) {
11180     SmallVector<int, 8> NewMask;
11181     for (unsigned i = 0; i != NumElts; ++i) {
11182       int Idx = SVN->getMaskElt(i);
11183       if (Idx >= (int)NumElts) Idx -= NumElts;
11184       NewMask.push_back(Idx);
11185     }
11186     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11187                                 &NewMask[0]);
11188   }
11189
11190   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11191   if (N0.getOpcode() == ISD::UNDEF) {
11192     SmallVector<int, 8> NewMask;
11193     for (unsigned i = 0; i != NumElts; ++i) {
11194       int Idx = SVN->getMaskElt(i);
11195       if (Idx >= 0) {
11196         if (Idx >= (int)NumElts)
11197           Idx -= NumElts;
11198         else
11199           Idx = -1; // remove reference to lhs
11200       }
11201       NewMask.push_back(Idx);
11202     }
11203     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11204                                 &NewMask[0]);
11205   }
11206
11207   // Remove references to rhs if it is undef
11208   if (N1.getOpcode() == ISD::UNDEF) {
11209     bool Changed = false;
11210     SmallVector<int, 8> NewMask;
11211     for (unsigned i = 0; i != NumElts; ++i) {
11212       int Idx = SVN->getMaskElt(i);
11213       if (Idx >= (int)NumElts) {
11214         Idx = -1;
11215         Changed = true;
11216       }
11217       NewMask.push_back(Idx);
11218     }
11219     if (Changed)
11220       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11221   }
11222
11223   // If it is a splat, check if the argument vector is another splat or a
11224   // build_vector with all scalar elements the same.
11225   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11226     SDNode *V = N0.getNode();
11227
11228     // If this is a bit convert that changes the element type of the vector but
11229     // not the number of vector elements, look through it.  Be careful not to
11230     // look though conversions that change things like v4f32 to v2f64.
11231     if (V->getOpcode() == ISD::BITCAST) {
11232       SDValue ConvInput = V->getOperand(0);
11233       if (ConvInput.getValueType().isVector() &&
11234           ConvInput.getValueType().getVectorNumElements() == NumElts)
11235         V = ConvInput.getNode();
11236     }
11237
11238     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11239       assert(V->getNumOperands() == NumElts &&
11240              "BUILD_VECTOR has wrong number of operands");
11241       SDValue Base;
11242       bool AllSame = true;
11243       for (unsigned i = 0; i != NumElts; ++i) {
11244         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11245           Base = V->getOperand(i);
11246           break;
11247         }
11248       }
11249       // Splat of <u, u, u, u>, return <u, u, u, u>
11250       if (!Base.getNode())
11251         return N0;
11252       for (unsigned i = 0; i != NumElts; ++i) {
11253         if (V->getOperand(i) != Base) {
11254           AllSame = false;
11255           break;
11256         }
11257       }
11258       // Splat of <x, x, x, x>, return <x, x, x, x>
11259       if (AllSame)
11260         return N0;
11261     }
11262   }
11263
11264   // There are various patterns used to build up a vector from smaller vectors,
11265   // subvectors, or elements. Scan chains of these and replace unused insertions
11266   // or components with undef.
11267   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11268     return S;
11269
11270   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11271       Level < AfterLegalizeVectorOps &&
11272       (N1.getOpcode() == ISD::UNDEF ||
11273       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11274        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11275     SDValue V = partitionShuffleOfConcats(N, DAG);
11276
11277     if (V.getNode())
11278       return V;
11279   }
11280
11281   // Canonicalize shuffles according to rules:
11282   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11283   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11284   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11285   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11286       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11287       TLI.isTypeLegal(VT)) {
11288     // The incoming shuffle must be of the same type as the result of the
11289     // current shuffle.
11290     assert(N1->getOperand(0).getValueType() == VT &&
11291            "Shuffle types don't match");
11292
11293     SDValue SV0 = N1->getOperand(0);
11294     SDValue SV1 = N1->getOperand(1);
11295     bool HasSameOp0 = N0 == SV0;
11296     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11297     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11298       // Commute the operands of this shuffle so that next rule
11299       // will trigger.
11300       return DAG.getCommutedVectorShuffle(*SVN);
11301   }
11302
11303   // Try to fold according to rules:
11304   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11305   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11306   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11307   // Don't try to fold shuffles with illegal type.
11308   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11309       TLI.isTypeLegal(VT)) {
11310     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11311
11312     // The incoming shuffle must be of the same type as the result of the
11313     // current shuffle.
11314     assert(OtherSV->getOperand(0).getValueType() == VT &&
11315            "Shuffle types don't match");
11316
11317     SDValue SV0, SV1;
11318     SmallVector<int, 4> Mask;
11319     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11320     // operand, and SV1 as the second operand.
11321     for (unsigned i = 0; i != NumElts; ++i) {
11322       int Idx = SVN->getMaskElt(i);
11323       if (Idx < 0) {
11324         // Propagate Undef.
11325         Mask.push_back(Idx);
11326         continue;
11327       }
11328
11329       SDValue CurrentVec;
11330       if (Idx < (int)NumElts) {
11331         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11332         // shuffle mask to identify which vector is actually referenced.
11333         Idx = OtherSV->getMaskElt(Idx);
11334         if (Idx < 0) {
11335           // Propagate Undef.
11336           Mask.push_back(Idx);
11337           continue;
11338         }
11339
11340         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11341                                            : OtherSV->getOperand(1);
11342       } else {
11343         // This shuffle index references an element within N1.
11344         CurrentVec = N1;
11345       }
11346
11347       // Simple case where 'CurrentVec' is UNDEF.
11348       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11349         Mask.push_back(-1);
11350         continue;
11351       }
11352
11353       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11354       // will be the first or second operand of the combined shuffle.
11355       Idx = Idx % NumElts;
11356       if (!SV0.getNode() || SV0 == CurrentVec) {
11357         // Ok. CurrentVec is the left hand side.
11358         // Update the mask accordingly.
11359         SV0 = CurrentVec;
11360         Mask.push_back(Idx);
11361         continue;
11362       }
11363
11364       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11365       if (SV1.getNode() && SV1 != CurrentVec)
11366         return SDValue();
11367
11368       // Ok. CurrentVec is the right hand side.
11369       // Update the mask accordingly.
11370       SV1 = CurrentVec;
11371       Mask.push_back(Idx + NumElts);
11372     }
11373
11374     // Check if all indices in Mask are Undef. In case, propagate Undef.
11375     bool isUndefMask = true;
11376     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11377       isUndefMask &= Mask[i] < 0;
11378
11379     if (isUndefMask)
11380       return DAG.getUNDEF(VT);
11381
11382     if (!SV0.getNode())
11383       SV0 = DAG.getUNDEF(VT);
11384     if (!SV1.getNode())
11385       SV1 = DAG.getUNDEF(VT);
11386
11387     // Avoid introducing shuffles with illegal mask.
11388     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11389       // Compute the commuted shuffle mask and test again.
11390       for (unsigned i = 0; i != NumElts; ++i) {
11391         int idx = Mask[i];
11392         if (idx < 0)
11393           continue;
11394         else if (idx < (int)NumElts)
11395           Mask[i] = idx + NumElts;
11396         else
11397           Mask[i] = idx - NumElts;
11398       }
11399
11400       if (!TLI.isShuffleMaskLegal(Mask, VT))
11401         return SDValue();
11402  
11403       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11404       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11405       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11406       std::swap(SV0, SV1);
11407     }
11408
11409     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11410     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11411     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11412     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11413   }
11414
11415   return SDValue();
11416 }
11417
11418 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11419   SDValue N0 = N->getOperand(0);
11420   SDValue N2 = N->getOperand(2);
11421
11422   // If the input vector is a concatenation, and the insert replaces
11423   // one of the halves, we can optimize into a single concat_vectors.
11424   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11425       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11426     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11427     EVT VT = N->getValueType(0);
11428
11429     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11430     // (concat_vectors Z, Y)
11431     if (InsIdx == 0)
11432       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11433                          N->getOperand(1), N0.getOperand(1));
11434
11435     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11436     // (concat_vectors X, Z)
11437     if (InsIdx == VT.getVectorNumElements()/2)
11438       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11439                          N0.getOperand(0), N->getOperand(1));
11440   }
11441
11442   return SDValue();
11443 }
11444
11445 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11446 /// with the destination vector and a zero vector.
11447 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11448 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11449 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11450   EVT VT = N->getValueType(0);
11451   SDLoc dl(N);
11452   SDValue LHS = N->getOperand(0);
11453   SDValue RHS = N->getOperand(1);
11454   if (N->getOpcode() == ISD::AND) {
11455     if (RHS.getOpcode() == ISD::BITCAST)
11456       RHS = RHS.getOperand(0);
11457     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11458       SmallVector<int, 8> Indices;
11459       unsigned NumElts = RHS.getNumOperands();
11460       for (unsigned i = 0; i != NumElts; ++i) {
11461         SDValue Elt = RHS.getOperand(i);
11462         if (!isa<ConstantSDNode>(Elt))
11463           return SDValue();
11464
11465         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11466           Indices.push_back(i);
11467         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11468           Indices.push_back(NumElts+i);
11469         else
11470           return SDValue();
11471       }
11472
11473       // Let's see if the target supports this vector_shuffle.
11474       EVT RVT = RHS.getValueType();
11475       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11476         return SDValue();
11477
11478       // Return the new VECTOR_SHUFFLE node.
11479       EVT EltVT = RVT.getVectorElementType();
11480       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11481                                      DAG.getConstant(0, EltVT));
11482       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11483       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11484       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11485       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11486     }
11487   }
11488
11489   return SDValue();
11490 }
11491
11492 /// Visit a binary vector operation, like ADD.
11493 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11494   assert(N->getValueType(0).isVector() &&
11495          "SimplifyVBinOp only works on vectors!");
11496
11497   SDValue LHS = N->getOperand(0);
11498   SDValue RHS = N->getOperand(1);
11499   SDValue Shuffle = XformToShuffleWithZero(N);
11500   if (Shuffle.getNode()) return Shuffle;
11501
11502   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11503   // this operation.
11504   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11505       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11506     // Check if both vectors are constants. If not bail out.
11507     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11508           cast<BuildVectorSDNode>(RHS)->isConstant()))
11509       return SDValue();
11510
11511     SmallVector<SDValue, 8> Ops;
11512     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11513       SDValue LHSOp = LHS.getOperand(i);
11514       SDValue RHSOp = RHS.getOperand(i);
11515
11516       // Can't fold divide by zero.
11517       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11518           N->getOpcode() == ISD::FDIV) {
11519         if ((RHSOp.getOpcode() == ISD::Constant &&
11520              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11521             (RHSOp.getOpcode() == ISD::ConstantFP &&
11522              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11523           break;
11524       }
11525
11526       EVT VT = LHSOp.getValueType();
11527       EVT RVT = RHSOp.getValueType();
11528       if (RVT != VT) {
11529         // Integer BUILD_VECTOR operands may have types larger than the element
11530         // size (e.g., when the element type is not legal).  Prior to type
11531         // legalization, the types may not match between the two BUILD_VECTORS.
11532         // Truncate one of the operands to make them match.
11533         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11534           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11535         } else {
11536           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11537           VT = RVT;
11538         }
11539       }
11540       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11541                                    LHSOp, RHSOp);
11542       if (FoldOp.getOpcode() != ISD::UNDEF &&
11543           FoldOp.getOpcode() != ISD::Constant &&
11544           FoldOp.getOpcode() != ISD::ConstantFP)
11545         break;
11546       Ops.push_back(FoldOp);
11547       AddToWorklist(FoldOp.getNode());
11548     }
11549
11550     if (Ops.size() == LHS.getNumOperands())
11551       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11552   }
11553
11554   // Type legalization might introduce new shuffles in the DAG.
11555   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11556   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11557   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11558       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11559       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11560       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11561     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11562     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11563
11564     if (SVN0->getMask().equals(SVN1->getMask())) {
11565       EVT VT = N->getValueType(0);
11566       SDValue UndefVector = LHS.getOperand(1);
11567       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11568                                      LHS.getOperand(0), RHS.getOperand(0));
11569       AddUsersToWorklist(N);
11570       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11571                                   &SVN0->getMask()[0]);
11572     }
11573   }
11574
11575   return SDValue();
11576 }
11577
11578 /// Visit a binary vector operation, like FABS/FNEG.
11579 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11580   assert(N->getValueType(0).isVector() &&
11581          "SimplifyVUnaryOp only works on vectors!");
11582
11583   SDValue N0 = N->getOperand(0);
11584
11585   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11586     return SDValue();
11587
11588   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11589   SmallVector<SDValue, 8> Ops;
11590   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11591     SDValue Op = N0.getOperand(i);
11592     if (Op.getOpcode() != ISD::UNDEF &&
11593         Op.getOpcode() != ISD::ConstantFP)
11594       break;
11595     EVT EltVT = Op.getValueType();
11596     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11597     if (FoldOp.getOpcode() != ISD::UNDEF &&
11598         FoldOp.getOpcode() != ISD::ConstantFP)
11599       break;
11600     Ops.push_back(FoldOp);
11601     AddToWorklist(FoldOp.getNode());
11602   }
11603
11604   if (Ops.size() != N0.getNumOperands())
11605     return SDValue();
11606
11607   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11608 }
11609
11610 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11611                                     SDValue N1, SDValue N2){
11612   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11613
11614   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11615                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11616
11617   // If we got a simplified select_cc node back from SimplifySelectCC, then
11618   // break it down into a new SETCC node, and a new SELECT node, and then return
11619   // the SELECT node, since we were called with a SELECT node.
11620   if (SCC.getNode()) {
11621     // Check to see if we got a select_cc back (to turn into setcc/select).
11622     // Otherwise, just return whatever node we got back, like fabs.
11623     if (SCC.getOpcode() == ISD::SELECT_CC) {
11624       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11625                                   N0.getValueType(),
11626                                   SCC.getOperand(0), SCC.getOperand(1),
11627                                   SCC.getOperand(4));
11628       AddToWorklist(SETCC.getNode());
11629       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11630                            SCC.getOperand(2), SCC.getOperand(3));
11631     }
11632
11633     return SCC;
11634   }
11635   return SDValue();
11636 }
11637
11638 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11639 /// being selected between, see if we can simplify the select.  Callers of this
11640 /// should assume that TheSelect is deleted if this returns true.  As such, they
11641 /// should return the appropriate thing (e.g. the node) back to the top-level of
11642 /// the DAG combiner loop to avoid it being looked at.
11643 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11644                                     SDValue RHS) {
11645
11646   // Cannot simplify select with vector condition
11647   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11648
11649   // If this is a select from two identical things, try to pull the operation
11650   // through the select.
11651   if (LHS.getOpcode() != RHS.getOpcode() ||
11652       !LHS.hasOneUse() || !RHS.hasOneUse())
11653     return false;
11654
11655   // If this is a load and the token chain is identical, replace the select
11656   // of two loads with a load through a select of the address to load from.
11657   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11658   // constants have been dropped into the constant pool.
11659   if (LHS.getOpcode() == ISD::LOAD) {
11660     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11661     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11662
11663     // Token chains must be identical.
11664     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11665         // Do not let this transformation reduce the number of volatile loads.
11666         LLD->isVolatile() || RLD->isVolatile() ||
11667         // If this is an EXTLOAD, the VT's must match.
11668         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11669         // If this is an EXTLOAD, the kind of extension must match.
11670         (LLD->getExtensionType() != RLD->getExtensionType() &&
11671          // The only exception is if one of the extensions is anyext.
11672          LLD->getExtensionType() != ISD::EXTLOAD &&
11673          RLD->getExtensionType() != ISD::EXTLOAD) ||
11674         // FIXME: this discards src value information.  This is
11675         // over-conservative. It would be beneficial to be able to remember
11676         // both potential memory locations.  Since we are discarding
11677         // src value info, don't do the transformation if the memory
11678         // locations are not in the default address space.
11679         LLD->getPointerInfo().getAddrSpace() != 0 ||
11680         RLD->getPointerInfo().getAddrSpace() != 0 ||
11681         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11682                                       LLD->getBasePtr().getValueType()))
11683       return false;
11684
11685     // Check that the select condition doesn't reach either load.  If so,
11686     // folding this will induce a cycle into the DAG.  If not, this is safe to
11687     // xform, so create a select of the addresses.
11688     SDValue Addr;
11689     if (TheSelect->getOpcode() == ISD::SELECT) {
11690       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11691       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11692           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11693         return false;
11694       // The loads must not depend on one another.
11695       if (LLD->isPredecessorOf(RLD) ||
11696           RLD->isPredecessorOf(LLD))
11697         return false;
11698       Addr = DAG.getSelect(SDLoc(TheSelect),
11699                            LLD->getBasePtr().getValueType(),
11700                            TheSelect->getOperand(0), LLD->getBasePtr(),
11701                            RLD->getBasePtr());
11702     } else {  // Otherwise SELECT_CC
11703       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11704       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11705
11706       if ((LLD->hasAnyUseOfValue(1) &&
11707            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11708           (RLD->hasAnyUseOfValue(1) &&
11709            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11710         return false;
11711
11712       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11713                          LLD->getBasePtr().getValueType(),
11714                          TheSelect->getOperand(0),
11715                          TheSelect->getOperand(1),
11716                          LLD->getBasePtr(), RLD->getBasePtr(),
11717                          TheSelect->getOperand(4));
11718     }
11719
11720     SDValue Load;
11721     // It is safe to replace the two loads if they have different alignments,
11722     // but the new load must be the minimum (most restrictive) alignment of the
11723     // inputs.
11724     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11725     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11726     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11727       Load = DAG.getLoad(TheSelect->getValueType(0),
11728                          SDLoc(TheSelect),
11729                          // FIXME: Discards pointer and AA info.
11730                          LLD->getChain(), Addr, MachinePointerInfo(),
11731                          LLD->isVolatile(), LLD->isNonTemporal(),
11732                          isInvariant, Alignment);
11733     } else {
11734       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11735                             RLD->getExtensionType() : LLD->getExtensionType(),
11736                             SDLoc(TheSelect),
11737                             TheSelect->getValueType(0),
11738                             // FIXME: Discards pointer and AA info.
11739                             LLD->getChain(), Addr, MachinePointerInfo(),
11740                             LLD->getMemoryVT(), LLD->isVolatile(),
11741                             LLD->isNonTemporal(), isInvariant, Alignment);
11742     }
11743
11744     // Users of the select now use the result of the load.
11745     CombineTo(TheSelect, Load);
11746
11747     // Users of the old loads now use the new load's chain.  We know the
11748     // old-load value is dead now.
11749     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11750     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11751     return true;
11752   }
11753
11754   return false;
11755 }
11756
11757 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11758 /// where 'cond' is the comparison specified by CC.
11759 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11760                                       SDValue N2, SDValue N3,
11761                                       ISD::CondCode CC, bool NotExtCompare) {
11762   // (x ? y : y) -> y.
11763   if (N2 == N3) return N2;
11764
11765   EVT VT = N2.getValueType();
11766   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11767   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11768   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11769
11770   // Determine if the condition we're dealing with is constant
11771   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11772                               N0, N1, CC, DL, false);
11773   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11774   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11775
11776   // fold select_cc true, x, y -> x
11777   if (SCCC && !SCCC->isNullValue())
11778     return N2;
11779   // fold select_cc false, x, y -> y
11780   if (SCCC && SCCC->isNullValue())
11781     return N3;
11782
11783   // Check to see if we can simplify the select into an fabs node
11784   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11785     // Allow either -0.0 or 0.0
11786     if (CFP->getValueAPF().isZero()) {
11787       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11788       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11789           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11790           N2 == N3.getOperand(0))
11791         return DAG.getNode(ISD::FABS, DL, VT, N0);
11792
11793       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11794       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11795           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11796           N2.getOperand(0) == N3)
11797         return DAG.getNode(ISD::FABS, DL, VT, N3);
11798     }
11799   }
11800
11801   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11802   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11803   // in it.  This is a win when the constant is not otherwise available because
11804   // it replaces two constant pool loads with one.  We only do this if the FP
11805   // type is known to be legal, because if it isn't, then we are before legalize
11806   // types an we want the other legalization to happen first (e.g. to avoid
11807   // messing with soft float) and if the ConstantFP is not legal, because if
11808   // it is legal, we may not need to store the FP constant in a constant pool.
11809   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11810     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11811       if (TLI.isTypeLegal(N2.getValueType()) &&
11812           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11813                TargetLowering::Legal &&
11814            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11815            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11816           // If both constants have multiple uses, then we won't need to do an
11817           // extra load, they are likely around in registers for other users.
11818           (TV->hasOneUse() || FV->hasOneUse())) {
11819         Constant *Elts[] = {
11820           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11821           const_cast<ConstantFP*>(TV->getConstantFPValue())
11822         };
11823         Type *FPTy = Elts[0]->getType();
11824         const DataLayout &TD = *TLI.getDataLayout();
11825
11826         // Create a ConstantArray of the two constants.
11827         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11828         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11829                                             TD.getPrefTypeAlignment(FPTy));
11830         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11831
11832         // Get the offsets to the 0 and 1 element of the array so that we can
11833         // select between them.
11834         SDValue Zero = DAG.getIntPtrConstant(0);
11835         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11836         SDValue One = DAG.getIntPtrConstant(EltSize);
11837
11838         SDValue Cond = DAG.getSetCC(DL,
11839                                     getSetCCResultType(N0.getValueType()),
11840                                     N0, N1, CC);
11841         AddToWorklist(Cond.getNode());
11842         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11843                                           Cond, One, Zero);
11844         AddToWorklist(CstOffset.getNode());
11845         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11846                             CstOffset);
11847         AddToWorklist(CPIdx.getNode());
11848         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11849                            MachinePointerInfo::getConstantPool(), false,
11850                            false, false, Alignment);
11851
11852       }
11853     }
11854
11855   // Check to see if we can perform the "gzip trick", transforming
11856   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11857   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11858       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11859        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11860     EVT XType = N0.getValueType();
11861     EVT AType = N2.getValueType();
11862     if (XType.bitsGE(AType)) {
11863       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11864       // single-bit constant.
11865       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11866         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11867         ShCtV = XType.getSizeInBits()-ShCtV-1;
11868         SDValue ShCt = DAG.getConstant(ShCtV,
11869                                        getShiftAmountTy(N0.getValueType()));
11870         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11871                                     XType, N0, ShCt);
11872         AddToWorklist(Shift.getNode());
11873
11874         if (XType.bitsGT(AType)) {
11875           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11876           AddToWorklist(Shift.getNode());
11877         }
11878
11879         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11880       }
11881
11882       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11883                                   XType, N0,
11884                                   DAG.getConstant(XType.getSizeInBits()-1,
11885                                          getShiftAmountTy(N0.getValueType())));
11886       AddToWorklist(Shift.getNode());
11887
11888       if (XType.bitsGT(AType)) {
11889         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11890         AddToWorklist(Shift.getNode());
11891       }
11892
11893       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11894     }
11895   }
11896
11897   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11898   // where y is has a single bit set.
11899   // A plaintext description would be, we can turn the SELECT_CC into an AND
11900   // when the condition can be materialized as an all-ones register.  Any
11901   // single bit-test can be materialized as an all-ones register with
11902   // shift-left and shift-right-arith.
11903   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11904       N0->getValueType(0) == VT &&
11905       N1C && N1C->isNullValue() &&
11906       N2C && N2C->isNullValue()) {
11907     SDValue AndLHS = N0->getOperand(0);
11908     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11909     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11910       // Shift the tested bit over the sign bit.
11911       APInt AndMask = ConstAndRHS->getAPIntValue();
11912       SDValue ShlAmt =
11913         DAG.getConstant(AndMask.countLeadingZeros(),
11914                         getShiftAmountTy(AndLHS.getValueType()));
11915       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11916
11917       // Now arithmetic right shift it all the way over, so the result is either
11918       // all-ones, or zero.
11919       SDValue ShrAmt =
11920         DAG.getConstant(AndMask.getBitWidth()-1,
11921                         getShiftAmountTy(Shl.getValueType()));
11922       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11923
11924       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11925     }
11926   }
11927
11928   // fold select C, 16, 0 -> shl C, 4
11929   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11930       TLI.getBooleanContents(N0.getValueType()) ==
11931           TargetLowering::ZeroOrOneBooleanContent) {
11932
11933     // If the caller doesn't want us to simplify this into a zext of a compare,
11934     // don't do it.
11935     if (NotExtCompare && N2C->getAPIntValue() == 1)
11936       return SDValue();
11937
11938     // Get a SetCC of the condition
11939     // NOTE: Don't create a SETCC if it's not legal on this target.
11940     if (!LegalOperations ||
11941         TLI.isOperationLegal(ISD::SETCC,
11942           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11943       SDValue Temp, SCC;
11944       // cast from setcc result type to select result type
11945       if (LegalTypes) {
11946         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11947                             N0, N1, CC);
11948         if (N2.getValueType().bitsLT(SCC.getValueType()))
11949           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11950                                         N2.getValueType());
11951         else
11952           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11953                              N2.getValueType(), SCC);
11954       } else {
11955         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11956         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11957                            N2.getValueType(), SCC);
11958       }
11959
11960       AddToWorklist(SCC.getNode());
11961       AddToWorklist(Temp.getNode());
11962
11963       if (N2C->getAPIntValue() == 1)
11964         return Temp;
11965
11966       // shl setcc result by log2 n2c
11967       return DAG.getNode(
11968           ISD::SHL, DL, N2.getValueType(), Temp,
11969           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11970                           getShiftAmountTy(Temp.getValueType())));
11971     }
11972   }
11973
11974   // Check to see if this is the equivalent of setcc
11975   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11976   // otherwise, go ahead with the folds.
11977   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11978     EVT XType = N0.getValueType();
11979     if (!LegalOperations ||
11980         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11981       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11982       if (Res.getValueType() != VT)
11983         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11984       return Res;
11985     }
11986
11987     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11988     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11989         (!LegalOperations ||
11990          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11991       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11992       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11993                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11994                                        getShiftAmountTy(Ctlz.getValueType())));
11995     }
11996     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11997     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11998       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11999                                   XType, DAG.getConstant(0, XType), N0);
12000       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
12001       return DAG.getNode(ISD::SRL, DL, XType,
12002                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
12003                          DAG.getConstant(XType.getSizeInBits()-1,
12004                                          getShiftAmountTy(XType)));
12005     }
12006     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
12007     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
12008       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
12009                                  DAG.getConstant(XType.getSizeInBits()-1,
12010                                          getShiftAmountTy(N0.getValueType())));
12011       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
12012     }
12013   }
12014
12015   // Check to see if this is an integer abs.
12016   // select_cc setg[te] X,  0,  X, -X ->
12017   // select_cc setgt    X, -1,  X, -X ->
12018   // select_cc setl[te] X,  0, -X,  X ->
12019   // select_cc setlt    X,  1, -X,  X ->
12020   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
12021   if (N1C) {
12022     ConstantSDNode *SubC = nullptr;
12023     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
12024          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
12025         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
12026       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
12027     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
12028               (N1C->isOne() && CC == ISD::SETLT)) &&
12029              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
12030       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
12031
12032     EVT XType = N0.getValueType();
12033     if (SubC && SubC->isNullValue() && XType.isInteger()) {
12034       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
12035                                   N0,
12036                                   DAG.getConstant(XType.getSizeInBits()-1,
12037                                          getShiftAmountTy(N0.getValueType())));
12038       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
12039                                 XType, N0, Shift);
12040       AddToWorklist(Shift.getNode());
12041       AddToWorklist(Add.getNode());
12042       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
12043     }
12044   }
12045
12046   return SDValue();
12047 }
12048
12049 /// This is a stub for TargetLowering::SimplifySetCC.
12050 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
12051                                    SDValue N1, ISD::CondCode Cond,
12052                                    SDLoc DL, bool foldBooleans) {
12053   TargetLowering::DAGCombinerInfo
12054     DagCombineInfo(DAG, Level, false, this);
12055   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
12056 }
12057
12058 /// Given an ISD::SDIV node expressing a divide by constant, return
12059 /// a DAG expression to select that will generate the same value by multiplying
12060 /// by a magic number.
12061 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12062 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
12063   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12064   if (!C)
12065     return SDValue();
12066
12067   // Avoid division by zero.
12068   if (!C->getAPIntValue())
12069     return SDValue();
12070
12071   std::vector<SDNode*> Built;
12072   SDValue S =
12073       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12074
12075   for (SDNode *N : Built)
12076     AddToWorklist(N);
12077   return S;
12078 }
12079
12080 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
12081 /// DAG expression that will generate the same value by right shifting.
12082 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
12083   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12084   if (!C)
12085     return SDValue();
12086
12087   // Avoid division by zero.
12088   if (!C->getAPIntValue())
12089     return SDValue();
12090
12091   std::vector<SDNode *> Built;
12092   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
12093
12094   for (SDNode *N : Built)
12095     AddToWorklist(N);
12096   return S;
12097 }
12098
12099 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
12100 /// expression that will generate the same value by multiplying by a magic
12101 /// number.
12102 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
12103 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
12104   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
12105   if (!C)
12106     return SDValue();
12107
12108   // Avoid division by zero.
12109   if (!C->getAPIntValue())
12110     return SDValue();
12111
12112   std::vector<SDNode*> Built;
12113   SDValue S =
12114       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
12115
12116   for (SDNode *N : Built)
12117     AddToWorklist(N);
12118   return S;
12119 }
12120
12121 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
12122   if (Level >= AfterLegalizeDAG)
12123     return SDValue();
12124
12125   // Expose the DAG combiner to the target combiner implementations.
12126   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12127
12128   unsigned Iterations = 0;
12129   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
12130     if (Iterations) {
12131       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12132       // For the reciprocal, we need to find the zero of the function:
12133       //   F(X) = A X - 1 [which has a zero at X = 1/A]
12134       //     =>
12135       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
12136       //     does not require additional intermediate precision]
12137       EVT VT = Op.getValueType();
12138       SDLoc DL(Op);
12139       SDValue FPOne = DAG.getConstantFP(1.0, VT);
12140
12141       AddToWorklist(Est.getNode());
12142
12143       // Newton iterations: Est = Est + Est (1 - Arg * Est)
12144       for (unsigned i = 0; i < Iterations; ++i) {
12145         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
12146         AddToWorklist(NewEst.getNode());
12147
12148         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
12149         AddToWorklist(NewEst.getNode());
12150
12151         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12152         AddToWorklist(NewEst.getNode());
12153
12154         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
12155         AddToWorklist(Est.getNode());
12156       }
12157     }
12158     return Est;
12159   }
12160
12161   return SDValue();
12162 }
12163
12164 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12165 /// For the reciprocal sqrt, we need to find the zero of the function:
12166 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12167 ///     =>
12168 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12169 /// As a result, we precompute A/2 prior to the iteration loop.
12170 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12171                                           unsigned Iterations) {
12172   EVT VT = Arg.getValueType();
12173   SDLoc DL(Arg);
12174   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12175
12176   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12177   // this entire sequence requires only one FP constant.
12178   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12179   AddToWorklist(HalfArg.getNode());
12180
12181   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12182   AddToWorklist(HalfArg.getNode());
12183
12184   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12185   for (unsigned i = 0; i < Iterations; ++i) {
12186     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12187     AddToWorklist(NewEst.getNode());
12188
12189     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12190     AddToWorklist(NewEst.getNode());
12191
12192     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12193     AddToWorklist(NewEst.getNode());
12194
12195     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12196     AddToWorklist(Est.getNode());
12197   }
12198   return Est;
12199 }
12200
12201 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12202 /// For the reciprocal sqrt, we need to find the zero of the function:
12203 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12204 ///     =>
12205 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12206 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12207                                           unsigned Iterations) {
12208   EVT VT = Arg.getValueType();
12209   SDLoc DL(Arg);
12210   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12211   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12212
12213   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12214   for (unsigned i = 0; i < Iterations; ++i) {
12215     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12216     AddToWorklist(HalfEst.getNode());
12217
12218     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12219     AddToWorklist(Est.getNode());
12220
12221     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12222     AddToWorklist(Est.getNode());
12223
12224     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12225     AddToWorklist(Est.getNode());
12226
12227     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12228     AddToWorklist(Est.getNode());
12229   }
12230   return Est;
12231 }
12232
12233 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12234   if (Level >= AfterLegalizeDAG)
12235     return SDValue();
12236
12237   // Expose the DAG combiner to the target combiner implementations.
12238   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12239   unsigned Iterations = 0;
12240   bool UseOneConstNR = false;
12241   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12242     AddToWorklist(Est.getNode());
12243     if (Iterations) {
12244       Est = UseOneConstNR ?
12245         BuildRsqrtNROneConst(Op, Est, Iterations) :
12246         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12247     }
12248     return Est;
12249   }
12250
12251   return SDValue();
12252 }
12253
12254 /// Return true if base is a frame index, which is known not to alias with
12255 /// anything but itself.  Provides base object and offset as results.
12256 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12257                            const GlobalValue *&GV, const void *&CV) {
12258   // Assume it is a primitive operation.
12259   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12260
12261   // If it's an adding a simple constant then integrate the offset.
12262   if (Base.getOpcode() == ISD::ADD) {
12263     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12264       Base = Base.getOperand(0);
12265       Offset += C->getZExtValue();
12266     }
12267   }
12268
12269   // Return the underlying GlobalValue, and update the Offset.  Return false
12270   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12271   // by multiple nodes with different offsets.
12272   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12273     GV = G->getGlobal();
12274     Offset += G->getOffset();
12275     return false;
12276   }
12277
12278   // Return the underlying Constant value, and update the Offset.  Return false
12279   // for ConstantSDNodes since the same constant pool entry may be represented
12280   // by multiple nodes with different offsets.
12281   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12282     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12283                                          : (const void *)C->getConstVal();
12284     Offset += C->getOffset();
12285     return false;
12286   }
12287   // If it's any of the following then it can't alias with anything but itself.
12288   return isa<FrameIndexSDNode>(Base);
12289 }
12290
12291 /// Return true if there is any possibility that the two addresses overlap.
12292 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12293   // If they are the same then they must be aliases.
12294   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12295
12296   // If they are both volatile then they cannot be reordered.
12297   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12298
12299   // Gather base node and offset information.
12300   SDValue Base1, Base2;
12301   int64_t Offset1, Offset2;
12302   const GlobalValue *GV1, *GV2;
12303   const void *CV1, *CV2;
12304   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12305                                       Base1, Offset1, GV1, CV1);
12306   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12307                                       Base2, Offset2, GV2, CV2);
12308
12309   // If they have a same base address then check to see if they overlap.
12310   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12311     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12312              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12313
12314   // It is possible for different frame indices to alias each other, mostly
12315   // when tail call optimization reuses return address slots for arguments.
12316   // To catch this case, look up the actual index of frame indices to compute
12317   // the real alias relationship.
12318   if (isFrameIndex1 && isFrameIndex2) {
12319     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12320     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12321     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12322     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12323              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12324   }
12325
12326   // Otherwise, if we know what the bases are, and they aren't identical, then
12327   // we know they cannot alias.
12328   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12329     return false;
12330
12331   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12332   // compared to the size and offset of the access, we may be able to prove they
12333   // do not alias.  This check is conservative for now to catch cases created by
12334   // splitting vector types.
12335   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12336       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12337       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12338        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12339       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12340     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12341     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12342
12343     // There is no overlap between these relatively aligned accesses of similar
12344     // size, return no alias.
12345     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12346         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12347       return false;
12348   }
12349
12350   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12351                    ? CombinerGlobalAA
12352                    : DAG.getSubtarget().useAA();
12353 #ifndef NDEBUG
12354   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12355       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12356     UseAA = false;
12357 #endif
12358   if (UseAA &&
12359       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12360     // Use alias analysis information.
12361     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12362                                  Op1->getSrcValueOffset());
12363     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12364         Op0->getSrcValueOffset() - MinOffset;
12365     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12366         Op1->getSrcValueOffset() - MinOffset;
12367     AliasAnalysis::AliasResult AAResult =
12368         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12369                                          Overlap1,
12370                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12371                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12372                                          Overlap2,
12373                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12374     if (AAResult == AliasAnalysis::NoAlias)
12375       return false;
12376   }
12377
12378   // Otherwise we have to assume they alias.
12379   return true;
12380 }
12381
12382 /// Walk up chain skipping non-aliasing memory nodes,
12383 /// looking for aliasing nodes and adding them to the Aliases vector.
12384 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12385                                    SmallVectorImpl<SDValue> &Aliases) {
12386   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12387   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12388
12389   // Get alias information for node.
12390   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12391
12392   // Starting off.
12393   Chains.push_back(OriginalChain);
12394   unsigned Depth = 0;
12395
12396   // Look at each chain and determine if it is an alias.  If so, add it to the
12397   // aliases list.  If not, then continue up the chain looking for the next
12398   // candidate.
12399   while (!Chains.empty()) {
12400     SDValue Chain = Chains.back();
12401     Chains.pop_back();
12402
12403     // For TokenFactor nodes, look at each operand and only continue up the
12404     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12405     // find more and revert to original chain since the xform is unlikely to be
12406     // profitable.
12407     //
12408     // FIXME: The depth check could be made to return the last non-aliasing
12409     // chain we found before we hit a tokenfactor rather than the original
12410     // chain.
12411     if (Depth > 6 || Aliases.size() == 2) {
12412       Aliases.clear();
12413       Aliases.push_back(OriginalChain);
12414       return;
12415     }
12416
12417     // Don't bother if we've been before.
12418     if (!Visited.insert(Chain.getNode()).second)
12419       continue;
12420
12421     switch (Chain.getOpcode()) {
12422     case ISD::EntryToken:
12423       // Entry token is ideal chain operand, but handled in FindBetterChain.
12424       break;
12425
12426     case ISD::LOAD:
12427     case ISD::STORE: {
12428       // Get alias information for Chain.
12429       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12430           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12431
12432       // If chain is alias then stop here.
12433       if (!(IsLoad && IsOpLoad) &&
12434           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12435         Aliases.push_back(Chain);
12436       } else {
12437         // Look further up the chain.
12438         Chains.push_back(Chain.getOperand(0));
12439         ++Depth;
12440       }
12441       break;
12442     }
12443
12444     case ISD::TokenFactor:
12445       // We have to check each of the operands of the token factor for "small"
12446       // token factors, so we queue them up.  Adding the operands to the queue
12447       // (stack) in reverse order maintains the original order and increases the
12448       // likelihood that getNode will find a matching token factor (CSE.)
12449       if (Chain.getNumOperands() > 16) {
12450         Aliases.push_back(Chain);
12451         break;
12452       }
12453       for (unsigned n = Chain.getNumOperands(); n;)
12454         Chains.push_back(Chain.getOperand(--n));
12455       ++Depth;
12456       break;
12457
12458     default:
12459       // For all other instructions we will just have to take what we can get.
12460       Aliases.push_back(Chain);
12461       break;
12462     }
12463   }
12464
12465   // We need to be careful here to also search for aliases through the
12466   // value operand of a store, etc. Consider the following situation:
12467   //   Token1 = ...
12468   //   L1 = load Token1, %52
12469   //   S1 = store Token1, L1, %51
12470   //   L2 = load Token1, %52+8
12471   //   S2 = store Token1, L2, %51+8
12472   //   Token2 = Token(S1, S2)
12473   //   L3 = load Token2, %53
12474   //   S3 = store Token2, L3, %52
12475   //   L4 = load Token2, %53+8
12476   //   S4 = store Token2, L4, %52+8
12477   // If we search for aliases of S3 (which loads address %52), and we look
12478   // only through the chain, then we'll miss the trivial dependence on L1
12479   // (which also loads from %52). We then might change all loads and
12480   // stores to use Token1 as their chain operand, which could result in
12481   // copying %53 into %52 before copying %52 into %51 (which should
12482   // happen first).
12483   //
12484   // The problem is, however, that searching for such data dependencies
12485   // can become expensive, and the cost is not directly related to the
12486   // chain depth. Instead, we'll rule out such configurations here by
12487   // insisting that we've visited all chain users (except for users
12488   // of the original chain, which is not necessary). When doing this,
12489   // we need to look through nodes we don't care about (otherwise, things
12490   // like register copies will interfere with trivial cases).
12491
12492   SmallVector<const SDNode *, 16> Worklist;
12493   for (const SDNode *N : Visited)
12494     if (N != OriginalChain.getNode())
12495       Worklist.push_back(N);
12496
12497   while (!Worklist.empty()) {
12498     const SDNode *M = Worklist.pop_back_val();
12499
12500     // We have already visited M, and want to make sure we've visited any uses
12501     // of M that we care about. For uses that we've not visisted, and don't
12502     // care about, queue them to the worklist.
12503
12504     for (SDNode::use_iterator UI = M->use_begin(),
12505          UIE = M->use_end(); UI != UIE; ++UI)
12506       if (UI.getUse().getValueType() == MVT::Other &&
12507           Visited.insert(*UI).second) {
12508         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12509           // We've not visited this use, and we care about it (it could have an
12510           // ordering dependency with the original node).
12511           Aliases.clear();
12512           Aliases.push_back(OriginalChain);
12513           return;
12514         }
12515
12516         // We've not visited this use, but we don't care about it. Mark it as
12517         // visited and enqueue it to the worklist.
12518         Worklist.push_back(*UI);
12519       }
12520   }
12521 }
12522
12523 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12524 /// (aliasing node.)
12525 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12526   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12527
12528   // Accumulate all the aliases to this node.
12529   GatherAllAliases(N, OldChain, Aliases);
12530
12531   // If no operands then chain to entry token.
12532   if (Aliases.size() == 0)
12533     return DAG.getEntryNode();
12534
12535   // If a single operand then chain to it.  We don't need to revisit it.
12536   if (Aliases.size() == 1)
12537     return Aliases[0];
12538
12539   // Construct a custom tailored token factor.
12540   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12541 }
12542
12543 /// This is the entry point for the file.
12544 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12545                            CodeGenOpt::Level OptLevel) {
12546   /// This is the main entry point to this class.
12547   DAGCombiner(*this, AA, OptLevel).Run(Level);
12548 }