Revert "Masked Vector Load and Store Intrinsics."
[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
307     SDValue XformToShuffleWithZero(SDNode *N);
308     SDValue ReassociateOps(unsigned Opc, SDLoc DL, SDValue LHS, SDValue RHS);
309
310     SDValue visitShiftByConstant(SDNode *N, ConstantSDNode *Amt);
311
312     bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
313     SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
314     SDValue SimplifySelect(SDLoc DL, SDValue N0, SDValue N1, SDValue N2);
315     SDValue SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1, SDValue N2,
316                              SDValue N3, ISD::CondCode CC,
317                              bool NotExtCompare = false);
318     SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
319                           SDLoc DL, bool foldBooleans = true);
320
321     bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
322                            SDValue &CC) const;
323     bool isOneUseSetCC(SDValue N) const;
324
325     SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
326                                          unsigned HiOp);
327     SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
328     SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
329     SDValue BuildSDIV(SDNode *N);
330     SDValue BuildSDIVPow2(SDNode *N);
331     SDValue BuildUDIV(SDNode *N);
332     SDValue BuildReciprocalEstimate(SDValue Op);
333     SDValue BuildRsqrtEstimate(SDValue Op);
334     SDValue BuildRsqrtNROneConst(SDValue Op, SDValue Est, unsigned Iterations);
335     SDValue BuildRsqrtNRTwoConst(SDValue Op, SDValue Est, unsigned Iterations);
336     SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
337                                bool DemandHighBits = true);
338     SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
339     SDNode *MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
340                               SDValue InnerPos, SDValue InnerNeg,
341                               unsigned PosOpcode, unsigned NegOpcode,
342                               SDLoc DL);
343     SDNode *MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL);
344     SDValue ReduceLoadWidth(SDNode *N);
345     SDValue ReduceLoadOpStoreWidth(SDNode *N);
346     SDValue TransformFPLoadStorePair(SDNode *N);
347     SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
348     SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
349
350     SDValue GetDemandedBits(SDValue V, const APInt &Mask);
351
352     /// Walk up chain skipping non-aliasing memory nodes,
353     /// looking for aliasing nodes and adding them to the Aliases vector.
354     void GatherAllAliases(SDNode *N, SDValue OriginalChain,
355                           SmallVectorImpl<SDValue> &Aliases);
356
357     /// Return true if there is any possibility that the two addresses overlap.
358     bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const;
359
360     /// Walk up chain skipping non-aliasing memory nodes, looking for a better
361     /// chain (aliasing node.)
362     SDValue FindBetterChain(SDNode *N, SDValue Chain);
363
364     /// Merge consecutive store operations into a wide store.
365     /// This optimization uses wide integers or vectors when possible.
366     /// \return True if some memory operations were changed.
367     bool MergeConsecutiveStores(StoreSDNode *N);
368
369     /// \brief Try to transform a truncation where C is a constant:
370     ///     (trunc (and X, C)) -> (and (trunc X), (trunc C))
371     ///
372     /// \p N needs to be a truncation and its first operand an AND. Other
373     /// requirements are checked by the function (e.g. that trunc is
374     /// single-use) and if missed an empty SDValue is returned.
375     SDValue distributeTruncateThroughAnd(SDNode *N);
376
377   public:
378     DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
379         : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
380           OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {
381       AttributeSet FnAttrs =
382           DAG.getMachineFunction().getFunction()->getAttributes();
383       ForCodeSize =
384           FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
385                                Attribute::OptimizeForSize) ||
386           FnAttrs.hasAttribute(AttributeSet::FunctionIndex, Attribute::MinSize);
387     }
388
389     /// Runs the dag combiner on all nodes in the work list
390     void Run(CombineLevel AtLevel);
391
392     SelectionDAG &getDAG() const { return DAG; }
393
394     /// Returns a type large enough to hold any valid shift amount - before type
395     /// legalization these can be huge.
396     EVT getShiftAmountTy(EVT LHSTy) {
397       assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
398       if (LHSTy.isVector())
399         return LHSTy;
400       return LegalTypes ? TLI.getScalarShiftAmountTy(LHSTy)
401                         : TLI.getPointerTy();
402     }
403
404     /// This method returns true if we are running before type legalization or
405     /// if the specified VT is legal.
406     bool isTypeLegal(const EVT &VT) {
407       if (!LegalTypes) return true;
408       return TLI.isTypeLegal(VT);
409     }
410
411     /// Convenience wrapper around TargetLowering::getSetCCResultType
412     EVT getSetCCResultType(EVT VT) const {
413       return TLI.getSetCCResultType(*DAG.getContext(), VT);
414     }
415   };
416 }
417
418
419 namespace {
420 /// This class is a DAGUpdateListener that removes any deleted
421 /// nodes from the worklist.
422 class WorklistRemover : public SelectionDAG::DAGUpdateListener {
423   DAGCombiner &DC;
424 public:
425   explicit WorklistRemover(DAGCombiner &dc)
426     : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
427
428   void NodeDeleted(SDNode *N, SDNode *E) override {
429     DC.removeFromWorklist(N);
430   }
431 };
432 }
433
434 //===----------------------------------------------------------------------===//
435 //  TargetLowering::DAGCombinerInfo implementation
436 //===----------------------------------------------------------------------===//
437
438 void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
439   ((DAGCombiner*)DC)->AddToWorklist(N);
440 }
441
442 void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
443   ((DAGCombiner*)DC)->removeFromWorklist(N);
444 }
445
446 SDValue TargetLowering::DAGCombinerInfo::
447 CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
448   return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
449 }
450
451 SDValue TargetLowering::DAGCombinerInfo::
452 CombineTo(SDNode *N, SDValue Res, bool AddTo) {
453   return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
454 }
455
456
457 SDValue TargetLowering::DAGCombinerInfo::
458 CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
459   return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
460 }
461
462 void TargetLowering::DAGCombinerInfo::
463 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
464   return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
465 }
466
467 //===----------------------------------------------------------------------===//
468 // Helper Functions
469 //===----------------------------------------------------------------------===//
470
471 void DAGCombiner::deleteAndRecombine(SDNode *N) {
472   removeFromWorklist(N);
473
474   // If the operands of this node are only used by the node, they will now be
475   // dead. Make sure to re-visit them and recursively delete dead nodes.
476   for (const SDValue &Op : N->ops())
477     // For an operand generating multiple values, one of the values may
478     // become dead allowing further simplification (e.g. split index
479     // arithmetic from an indexed load).
480     if (Op->hasOneUse() || Op->getNumValues() > 1)
481       AddToWorklist(Op.getNode());
482
483   DAG.DeleteNode(N);
484 }
485
486 /// Return 1 if we can compute the negated form of the specified expression for
487 /// the same cost as the expression itself, or 2 if we can compute the negated
488 /// form more cheaply than the expression itself.
489 static char isNegatibleForFree(SDValue Op, bool LegalOperations,
490                                const TargetLowering &TLI,
491                                const TargetOptions *Options,
492                                unsigned Depth = 0) {
493   // fneg is removable even if it has multiple uses.
494   if (Op.getOpcode() == ISD::FNEG) return 2;
495
496   // Don't allow anything with multiple uses.
497   if (!Op.hasOneUse()) return 0;
498
499   // Don't recurse exponentially.
500   if (Depth > 6) return 0;
501
502   switch (Op.getOpcode()) {
503   default: return false;
504   case ISD::ConstantFP:
505     // Don't invert constant FP values after legalize.  The negated constant
506     // isn't necessarily legal.
507     return LegalOperations ? 0 : 1;
508   case ISD::FADD:
509     // FIXME: determine better conditions for this xform.
510     if (!Options->UnsafeFPMath) return 0;
511
512     // After operation legalization, it might not be legal to create new FSUBs.
513     if (LegalOperations &&
514         !TLI.isOperationLegalOrCustom(ISD::FSUB,  Op.getValueType()))
515       return 0;
516
517     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
518     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
519                                     Options, Depth + 1))
520       return V;
521     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
522     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
523                               Depth + 1);
524   case ISD::FSUB:
525     // We can't turn -(A-B) into B-A when we honor signed zeros.
526     if (!Options->UnsafeFPMath) return 0;
527
528     // fold (fneg (fsub A, B)) -> (fsub B, A)
529     return 1;
530
531   case ISD::FMUL:
532   case ISD::FDIV:
533     if (Options->HonorSignDependentRoundingFPMath()) return 0;
534
535     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
536     if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
537                                     Options, Depth + 1))
538       return V;
539
540     return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
541                               Depth + 1);
542
543   case ISD::FP_EXTEND:
544   case ISD::FP_ROUND:
545   case ISD::FSIN:
546     return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
547                               Depth + 1);
548   }
549 }
550
551 /// If isNegatibleForFree returns true, return the newly negated expression.
552 static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
553                                     bool LegalOperations, unsigned Depth = 0) {
554   const TargetOptions &Options = DAG.getTarget().Options;
555   // fneg is removable even if it has multiple uses.
556   if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
557
558   // Don't allow anything with multiple uses.
559   assert(Op.hasOneUse() && "Unknown reuse!");
560
561   assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
562   switch (Op.getOpcode()) {
563   default: llvm_unreachable("Unknown code");
564   case ISD::ConstantFP: {
565     APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
566     V.changeSign();
567     return DAG.getConstantFP(V, Op.getValueType());
568   }
569   case ISD::FADD:
570     // FIXME: determine better conditions for this xform.
571     assert(Options.UnsafeFPMath);
572
573     // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
574     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
575                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
576       return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
577                          GetNegatedExpression(Op.getOperand(0), DAG,
578                                               LegalOperations, Depth+1),
579                          Op.getOperand(1));
580     // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
581     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
582                        GetNegatedExpression(Op.getOperand(1), DAG,
583                                             LegalOperations, Depth+1),
584                        Op.getOperand(0));
585   case ISD::FSUB:
586     // We can't turn -(A-B) into B-A when we honor signed zeros.
587     assert(Options.UnsafeFPMath);
588
589     // fold (fneg (fsub 0, B)) -> B
590     if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
591       if (N0CFP->getValueAPF().isZero())
592         return Op.getOperand(1);
593
594     // fold (fneg (fsub A, B)) -> (fsub B, A)
595     return DAG.getNode(ISD::FSUB, SDLoc(Op), Op.getValueType(),
596                        Op.getOperand(1), Op.getOperand(0));
597
598   case ISD::FMUL:
599   case ISD::FDIV:
600     assert(!Options.HonorSignDependentRoundingFPMath());
601
602     // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
603     if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
604                            DAG.getTargetLoweringInfo(), &Options, Depth+1))
605       return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
606                          GetNegatedExpression(Op.getOperand(0), DAG,
607                                               LegalOperations, Depth+1),
608                          Op.getOperand(1));
609
610     // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
611     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
612                        Op.getOperand(0),
613                        GetNegatedExpression(Op.getOperand(1), DAG,
614                                             LegalOperations, Depth+1));
615
616   case ISD::FP_EXTEND:
617   case ISD::FSIN:
618     return DAG.getNode(Op.getOpcode(), SDLoc(Op), Op.getValueType(),
619                        GetNegatedExpression(Op.getOperand(0), DAG,
620                                             LegalOperations, Depth+1));
621   case ISD::FP_ROUND:
622       return DAG.getNode(ISD::FP_ROUND, SDLoc(Op), Op.getValueType(),
623                          GetNegatedExpression(Op.getOperand(0), DAG,
624                                               LegalOperations, Depth+1),
625                          Op.getOperand(1));
626   }
627 }
628
629 // Return true if this node is a setcc, or is a select_cc
630 // that selects between the target values used for true and false, making it
631 // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
632 // the appropriate nodes based on the type of node we are checking. This
633 // simplifies life a bit for the callers.
634 bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
635                                     SDValue &CC) const {
636   if (N.getOpcode() == ISD::SETCC) {
637     LHS = N.getOperand(0);
638     RHS = N.getOperand(1);
639     CC  = N.getOperand(2);
640     return true;
641   }
642
643   if (N.getOpcode() != ISD::SELECT_CC ||
644       !TLI.isConstTrueVal(N.getOperand(2).getNode()) ||
645       !TLI.isConstFalseVal(N.getOperand(3).getNode()))
646     return false;
647
648   if (TLI.getBooleanContents(N.getValueType()) ==
649       TargetLowering::UndefinedBooleanContent)
650     return false;
651
652   LHS = N.getOperand(0);
653   RHS = N.getOperand(1);
654   CC  = N.getOperand(4);
655   return true;
656 }
657
658 /// Return true if this is a SetCC-equivalent operation with only one use.
659 /// If this is true, it allows the users to invert the operation for free when
660 /// it is profitable to do so.
661 bool DAGCombiner::isOneUseSetCC(SDValue N) const {
662   SDValue N0, N1, N2;
663   if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
664     return true;
665   return false;
666 }
667
668 /// Returns true if N is a BUILD_VECTOR node whose
669 /// elements are all the same constant or undefined.
670 static bool isConstantSplatVector(SDNode *N, APInt& SplatValue) {
671   BuildVectorSDNode *C = dyn_cast<BuildVectorSDNode>(N);
672   if (!C)
673     return false;
674
675   APInt SplatUndef;
676   unsigned SplatBitSize;
677   bool HasAnyUndefs;
678   EVT EltVT = N->getValueType(0).getVectorElementType();
679   return (C->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
680                              HasAnyUndefs) &&
681           EltVT.getSizeInBits() >= SplatBitSize);
682 }
683
684 // \brief Returns the SDNode if it is a constant BuildVector or constant.
685 static SDNode *isConstantBuildVectorOrConstantInt(SDValue N) {
686   if (isa<ConstantSDNode>(N))
687     return N.getNode();
688   BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N);
689   if (BV && BV->isConstant())
690     return BV;
691   return nullptr;
692 }
693
694 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
695 // int.
696 static ConstantSDNode *isConstOrConstSplat(SDValue N) {
697   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
698     return CN;
699
700   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
701     BitVector UndefElements;
702     ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
703
704     // BuildVectors can truncate their operands. Ignore that case here.
705     // FIXME: We blindly ignore splats which include undef which is overly
706     // pessimistic.
707     if (CN && UndefElements.none() &&
708         CN->getValueType(0) == N.getValueType().getScalarType())
709       return CN;
710   }
711
712   return nullptr;
713 }
714
715 // \brief Returns the SDNode if it is a constant splat BuildVector or constant
716 // float.
717 static ConstantFPSDNode *isConstOrConstSplatFP(SDValue N) {
718   if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
719     return CN;
720
721   if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
722     BitVector UndefElements;
723     ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
724
725     if (CN && UndefElements.none())
726       return CN;
727   }
728
729   return nullptr;
730 }
731
732 SDValue DAGCombiner::ReassociateOps(unsigned Opc, SDLoc DL,
733                                     SDValue N0, SDValue N1) {
734   EVT VT = N0.getValueType();
735   if (N0.getOpcode() == Opc) {
736     if (SDNode *L = isConstantBuildVectorOrConstantInt(N0.getOperand(1))) {
737       if (SDNode *R = isConstantBuildVectorOrConstantInt(N1)) {
738         // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
739         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, L, R);
740         if (!OpNode.getNode())
741           return SDValue();
742         return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
743       }
744       if (N0.hasOneUse()) {
745         // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one
746         // use
747         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N0.getOperand(0), N1);
748         if (!OpNode.getNode())
749           return SDValue();
750         AddToWorklist(OpNode.getNode());
751         return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
752       }
753     }
754   }
755
756   if (N1.getOpcode() == Opc) {
757     if (SDNode *R = isConstantBuildVectorOrConstantInt(N1.getOperand(1))) {
758       if (SDNode *L = isConstantBuildVectorOrConstantInt(N0)) {
759         // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
760         SDValue OpNode = DAG.FoldConstantArithmetic(Opc, VT, R, L);
761         if (!OpNode.getNode())
762           return SDValue();
763         return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
764       }
765       if (N1.hasOneUse()) {
766         // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one
767         // use
768         SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N1.getOperand(0), N0);
769         if (!OpNode.getNode())
770           return SDValue();
771         AddToWorklist(OpNode.getNode());
772         return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
773       }
774     }
775   }
776
777   return SDValue();
778 }
779
780 SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
781                                bool AddTo) {
782   assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
783   ++NodesCombined;
784   DEBUG(dbgs() << "\nReplacing.1 ";
785         N->dump(&DAG);
786         dbgs() << "\nWith: ";
787         To[0].getNode()->dump(&DAG);
788         dbgs() << " and " << NumTo-1 << " other values\n";
789         for (unsigned i = 0, e = NumTo; i != e; ++i)
790           assert((!To[i].getNode() ||
791                   N->getValueType(i) == To[i].getValueType()) &&
792                  "Cannot combine value to value of different type!"));
793   WorklistRemover DeadNodes(*this);
794   DAG.ReplaceAllUsesWith(N, To);
795   if (AddTo) {
796     // Push the new nodes and any users onto the worklist
797     for (unsigned i = 0, e = NumTo; i != e; ++i) {
798       if (To[i].getNode()) {
799         AddToWorklist(To[i].getNode());
800         AddUsersToWorklist(To[i].getNode());
801       }
802     }
803   }
804
805   // Finally, if the node is now dead, remove it from the graph.  The node
806   // may not be dead if the replacement process recursively simplified to
807   // something else needing this node.
808   if (N->use_empty())
809     deleteAndRecombine(N);
810   return SDValue(N, 0);
811 }
812
813 void DAGCombiner::
814 CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
815   // Replace all uses.  If any nodes become isomorphic to other nodes and
816   // are deleted, make sure to remove them from our worklist.
817   WorklistRemover DeadNodes(*this);
818   DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
819
820   // Push the new node and any (possibly new) users onto the worklist.
821   AddToWorklist(TLO.New.getNode());
822   AddUsersToWorklist(TLO.New.getNode());
823
824   // Finally, if the node is now dead, remove it from the graph.  The node
825   // may not be dead if the replacement process recursively simplified to
826   // something else needing this node.
827   if (TLO.Old.getNode()->use_empty())
828     deleteAndRecombine(TLO.Old.getNode());
829 }
830
831 /// Check the specified integer node value to see if it can be simplified or if
832 /// things it uses can be simplified by bit propagation. If so, return true.
833 bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
834   TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
835   APInt KnownZero, KnownOne;
836   if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
837     return false;
838
839   // Revisit the node.
840   AddToWorklist(Op.getNode());
841
842   // Replace the old value with the new one.
843   ++NodesCombined;
844   DEBUG(dbgs() << "\nReplacing.2 ";
845         TLO.Old.getNode()->dump(&DAG);
846         dbgs() << "\nWith: ";
847         TLO.New.getNode()->dump(&DAG);
848         dbgs() << '\n');
849
850   CommitTargetLoweringOpt(TLO);
851   return true;
852 }
853
854 void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
855   SDLoc dl(Load);
856   EVT VT = Load->getValueType(0);
857   SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
858
859   DEBUG(dbgs() << "\nReplacing.9 ";
860         Load->dump(&DAG);
861         dbgs() << "\nWith: ";
862         Trunc.getNode()->dump(&DAG);
863         dbgs() << '\n');
864   WorklistRemover DeadNodes(*this);
865   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
866   DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
867   deleteAndRecombine(Load);
868   AddToWorklist(Trunc.getNode());
869 }
870
871 SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
872   Replace = false;
873   SDLoc dl(Op);
874   if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
875     EVT MemVT = LD->getMemoryVT();
876     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
877       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
878                                                   : ISD::EXTLOAD)
879       : LD->getExtensionType();
880     Replace = true;
881     return DAG.getExtLoad(ExtType, dl, PVT,
882                           LD->getChain(), LD->getBasePtr(),
883                           MemVT, LD->getMemOperand());
884   }
885
886   unsigned Opc = Op.getOpcode();
887   switch (Opc) {
888   default: break;
889   case ISD::AssertSext:
890     return DAG.getNode(ISD::AssertSext, dl, PVT,
891                        SExtPromoteOperand(Op.getOperand(0), PVT),
892                        Op.getOperand(1));
893   case ISD::AssertZext:
894     return DAG.getNode(ISD::AssertZext, dl, PVT,
895                        ZExtPromoteOperand(Op.getOperand(0), PVT),
896                        Op.getOperand(1));
897   case ISD::Constant: {
898     unsigned ExtOpc =
899       Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
900     return DAG.getNode(ExtOpc, dl, PVT, Op);
901   }
902   }
903
904   if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
905     return SDValue();
906   return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
907 }
908
909 SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
910   if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
911     return SDValue();
912   EVT OldVT = Op.getValueType();
913   SDLoc dl(Op);
914   bool Replace = false;
915   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
916   if (!NewOp.getNode())
917     return SDValue();
918   AddToWorklist(NewOp.getNode());
919
920   if (Replace)
921     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
922   return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
923                      DAG.getValueType(OldVT));
924 }
925
926 SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
927   EVT OldVT = Op.getValueType();
928   SDLoc dl(Op);
929   bool Replace = false;
930   SDValue NewOp = PromoteOperand(Op, PVT, Replace);
931   if (!NewOp.getNode())
932     return SDValue();
933   AddToWorklist(NewOp.getNode());
934
935   if (Replace)
936     ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
937   return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
938 }
939
940 /// Promote the specified integer binary operation if the target indicates it is
941 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
942 /// i32 since i16 instructions are longer.
943 SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
944   if (!LegalOperations)
945     return SDValue();
946
947   EVT VT = Op.getValueType();
948   if (VT.isVector() || !VT.isInteger())
949     return SDValue();
950
951   // If operation type is 'undesirable', e.g. i16 on x86, consider
952   // promoting it.
953   unsigned Opc = Op.getOpcode();
954   if (TLI.isTypeDesirableForOp(Opc, VT))
955     return SDValue();
956
957   EVT PVT = VT;
958   // Consult target whether it is a good idea to promote this operation and
959   // what's the right type to promote it to.
960   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
961     assert(PVT != VT && "Don't know what type to promote to!");
962
963     bool Replace0 = false;
964     SDValue N0 = Op.getOperand(0);
965     SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
966     if (!NN0.getNode())
967       return SDValue();
968
969     bool Replace1 = false;
970     SDValue N1 = Op.getOperand(1);
971     SDValue NN1;
972     if (N0 == N1)
973       NN1 = NN0;
974     else {
975       NN1 = PromoteOperand(N1, PVT, Replace1);
976       if (!NN1.getNode())
977         return SDValue();
978     }
979
980     AddToWorklist(NN0.getNode());
981     if (NN1.getNode())
982       AddToWorklist(NN1.getNode());
983
984     if (Replace0)
985       ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
986     if (Replace1)
987       ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
988
989     DEBUG(dbgs() << "\nPromoting ";
990           Op.getNode()->dump(&DAG));
991     SDLoc dl(Op);
992     return DAG.getNode(ISD::TRUNCATE, dl, VT,
993                        DAG.getNode(Opc, dl, PVT, NN0, NN1));
994   }
995   return SDValue();
996 }
997
998 /// Promote the specified integer shift operation if the target indicates it is
999 /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
1000 /// i32 since i16 instructions are longer.
1001 SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
1002   if (!LegalOperations)
1003     return SDValue();
1004
1005   EVT VT = Op.getValueType();
1006   if (VT.isVector() || !VT.isInteger())
1007     return SDValue();
1008
1009   // If operation type is 'undesirable', e.g. i16 on x86, consider
1010   // promoting it.
1011   unsigned Opc = Op.getOpcode();
1012   if (TLI.isTypeDesirableForOp(Opc, VT))
1013     return SDValue();
1014
1015   EVT PVT = VT;
1016   // Consult target whether it is a good idea to promote this operation and
1017   // what's the right type to promote it to.
1018   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1019     assert(PVT != VT && "Don't know what type to promote to!");
1020
1021     bool Replace = false;
1022     SDValue N0 = Op.getOperand(0);
1023     if (Opc == ISD::SRA)
1024       N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
1025     else if (Opc == ISD::SRL)
1026       N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
1027     else
1028       N0 = PromoteOperand(N0, PVT, Replace);
1029     if (!N0.getNode())
1030       return SDValue();
1031
1032     AddToWorklist(N0.getNode());
1033     if (Replace)
1034       ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
1035
1036     DEBUG(dbgs() << "\nPromoting ";
1037           Op.getNode()->dump(&DAG));
1038     SDLoc dl(Op);
1039     return DAG.getNode(ISD::TRUNCATE, dl, VT,
1040                        DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
1041   }
1042   return SDValue();
1043 }
1044
1045 SDValue DAGCombiner::PromoteExtend(SDValue Op) {
1046   if (!LegalOperations)
1047     return SDValue();
1048
1049   EVT VT = Op.getValueType();
1050   if (VT.isVector() || !VT.isInteger())
1051     return SDValue();
1052
1053   // If operation type is 'undesirable', e.g. i16 on x86, consider
1054   // promoting it.
1055   unsigned Opc = Op.getOpcode();
1056   if (TLI.isTypeDesirableForOp(Opc, VT))
1057     return SDValue();
1058
1059   EVT PVT = VT;
1060   // Consult target whether it is a good idea to promote this operation and
1061   // what's the right type to promote it to.
1062   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1063     assert(PVT != VT && "Don't know what type to promote to!");
1064     // fold (aext (aext x)) -> (aext x)
1065     // fold (aext (zext x)) -> (zext x)
1066     // fold (aext (sext x)) -> (sext x)
1067     DEBUG(dbgs() << "\nPromoting ";
1068           Op.getNode()->dump(&DAG));
1069     return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
1070   }
1071   return SDValue();
1072 }
1073
1074 bool DAGCombiner::PromoteLoad(SDValue Op) {
1075   if (!LegalOperations)
1076     return false;
1077
1078   EVT VT = Op.getValueType();
1079   if (VT.isVector() || !VT.isInteger())
1080     return false;
1081
1082   // If operation type is 'undesirable', e.g. i16 on x86, consider
1083   // promoting it.
1084   unsigned Opc = Op.getOpcode();
1085   if (TLI.isTypeDesirableForOp(Opc, VT))
1086     return false;
1087
1088   EVT PVT = VT;
1089   // Consult target whether it is a good idea to promote this operation and
1090   // what's the right type to promote it to.
1091   if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
1092     assert(PVT != VT && "Don't know what type to promote to!");
1093
1094     SDLoc dl(Op);
1095     SDNode *N = Op.getNode();
1096     LoadSDNode *LD = cast<LoadSDNode>(N);
1097     EVT MemVT = LD->getMemoryVT();
1098     ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
1099       ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
1100                                                   : ISD::EXTLOAD)
1101       : LD->getExtensionType();
1102     SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
1103                                    LD->getChain(), LD->getBasePtr(),
1104                                    MemVT, LD->getMemOperand());
1105     SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
1106
1107     DEBUG(dbgs() << "\nPromoting ";
1108           N->dump(&DAG);
1109           dbgs() << "\nTo: ";
1110           Result.getNode()->dump(&DAG);
1111           dbgs() << '\n');
1112     WorklistRemover DeadNodes(*this);
1113     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
1114     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
1115     deleteAndRecombine(N);
1116     AddToWorklist(Result.getNode());
1117     return true;
1118   }
1119   return false;
1120 }
1121
1122 /// \brief Recursively delete a node which has no uses and any operands for
1123 /// which it is the only use.
1124 ///
1125 /// Note that this both deletes the nodes and removes them from the worklist.
1126 /// It also adds any nodes who have had a user deleted to the worklist as they
1127 /// may now have only one use and subject to other combines.
1128 bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
1129   if (!N->use_empty())
1130     return false;
1131
1132   SmallSetVector<SDNode *, 16> Nodes;
1133   Nodes.insert(N);
1134   do {
1135     N = Nodes.pop_back_val();
1136     if (!N)
1137       continue;
1138
1139     if (N->use_empty()) {
1140       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1141         Nodes.insert(N->getOperand(i).getNode());
1142
1143       removeFromWorklist(N);
1144       DAG.DeleteNode(N);
1145     } else {
1146       AddToWorklist(N);
1147     }
1148   } while (!Nodes.empty());
1149   return true;
1150 }
1151
1152 //===----------------------------------------------------------------------===//
1153 //  Main DAG Combiner implementation
1154 //===----------------------------------------------------------------------===//
1155
1156 void DAGCombiner::Run(CombineLevel AtLevel) {
1157   // set the instance variables, so that the various visit routines may use it.
1158   Level = AtLevel;
1159   LegalOperations = Level >= AfterLegalizeVectorOps;
1160   LegalTypes = Level >= AfterLegalizeTypes;
1161
1162   // Early exit if this basic block is in an optnone function.
1163   AttributeSet FnAttrs =
1164     DAG.getMachineFunction().getFunction()->getAttributes();
1165   if (FnAttrs.hasAttribute(AttributeSet::FunctionIndex,
1166                            Attribute::OptimizeNone))
1167     return;
1168
1169   // Add all the dag nodes to the worklist.
1170   for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
1171        E = DAG.allnodes_end(); I != E; ++I)
1172     AddToWorklist(I);
1173
1174   // Create a dummy node (which is not added to allnodes), that adds a reference
1175   // to the root node, preventing it from being deleted, and tracking any
1176   // changes of the root.
1177   HandleSDNode Dummy(DAG.getRoot());
1178
1179   // while the worklist isn't empty, find a node and
1180   // try and combine it.
1181   while (!WorklistMap.empty()) {
1182     SDNode *N;
1183     // The Worklist holds the SDNodes in order, but it may contain null entries.
1184     do {
1185       N = Worklist.pop_back_val();
1186     } while (!N);
1187
1188     bool GoodWorklistEntry = WorklistMap.erase(N);
1189     (void)GoodWorklistEntry;
1190     assert(GoodWorklistEntry &&
1191            "Found a worklist entry without a corresponding map entry!");
1192
1193     // If N has no uses, it is dead.  Make sure to revisit all N's operands once
1194     // N is deleted from the DAG, since they too may now be dead or may have a
1195     // reduced number of uses, allowing other xforms.
1196     if (recursivelyDeleteUnusedNodes(N))
1197       continue;
1198
1199     WorklistRemover DeadNodes(*this);
1200
1201     // If this combine is running after legalizing the DAG, re-legalize any
1202     // nodes pulled off the worklist.
1203     if (Level == AfterLegalizeDAG) {
1204       SmallSetVector<SDNode *, 16> UpdatedNodes;
1205       bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
1206
1207       for (SDNode *LN : UpdatedNodes) {
1208         AddToWorklist(LN);
1209         AddUsersToWorklist(LN);
1210       }
1211       if (!NIsValid)
1212         continue;
1213     }
1214
1215     DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
1216
1217     // Add any operands of the new node which have not yet been combined to the
1218     // worklist as well. Because the worklist uniques things already, this
1219     // won't repeatedly process the same operand.
1220     CombinedNodes.insert(N);
1221     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1222       if (!CombinedNodes.count(N->getOperand(i).getNode()))
1223         AddToWorklist(N->getOperand(i).getNode());
1224
1225     SDValue RV = combine(N);
1226
1227     if (!RV.getNode())
1228       continue;
1229
1230     ++NodesCombined;
1231
1232     // If we get back the same node we passed in, rather than a new node or
1233     // zero, we know that the node must have defined multiple values and
1234     // CombineTo was used.  Since CombineTo takes care of the worklist
1235     // mechanics for us, we have no work to do in this case.
1236     if (RV.getNode() == N)
1237       continue;
1238
1239     assert(N->getOpcode() != ISD::DELETED_NODE &&
1240            RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
1241            "Node was deleted but visit returned new node!");
1242
1243     DEBUG(dbgs() << " ... into: ";
1244           RV.getNode()->dump(&DAG));
1245
1246     // Transfer debug value.
1247     DAG.TransferDbgValues(SDValue(N, 0), RV);
1248     if (N->getNumValues() == RV.getNode()->getNumValues())
1249       DAG.ReplaceAllUsesWith(N, RV.getNode());
1250     else {
1251       assert(N->getValueType(0) == RV.getValueType() &&
1252              N->getNumValues() == 1 && "Type mismatch");
1253       SDValue OpV = RV;
1254       DAG.ReplaceAllUsesWith(N, &OpV);
1255     }
1256
1257     // Push the new node and any users onto the worklist
1258     AddToWorklist(RV.getNode());
1259     AddUsersToWorklist(RV.getNode());
1260
1261     // Finally, if the node is now dead, remove it from the graph.  The node
1262     // may not be dead if the replacement process recursively simplified to
1263     // something else needing this node. This will also take care of adding any
1264     // operands which have lost a user to the worklist.
1265     recursivelyDeleteUnusedNodes(N);
1266   }
1267
1268   // If the root changed (e.g. it was a dead load, update the root).
1269   DAG.setRoot(Dummy.getValue());
1270   DAG.RemoveDeadNodes();
1271 }
1272
1273 SDValue DAGCombiner::visit(SDNode *N) {
1274   switch (N->getOpcode()) {
1275   default: break;
1276   case ISD::TokenFactor:        return visitTokenFactor(N);
1277   case ISD::MERGE_VALUES:       return visitMERGE_VALUES(N);
1278   case ISD::ADD:                return visitADD(N);
1279   case ISD::SUB:                return visitSUB(N);
1280   case ISD::ADDC:               return visitADDC(N);
1281   case ISD::SUBC:               return visitSUBC(N);
1282   case ISD::ADDE:               return visitADDE(N);
1283   case ISD::SUBE:               return visitSUBE(N);
1284   case ISD::MUL:                return visitMUL(N);
1285   case ISD::SDIV:               return visitSDIV(N);
1286   case ISD::UDIV:               return visitUDIV(N);
1287   case ISD::SREM:               return visitSREM(N);
1288   case ISD::UREM:               return visitUREM(N);
1289   case ISD::MULHU:              return visitMULHU(N);
1290   case ISD::MULHS:              return visitMULHS(N);
1291   case ISD::SMUL_LOHI:          return visitSMUL_LOHI(N);
1292   case ISD::UMUL_LOHI:          return visitUMUL_LOHI(N);
1293   case ISD::SMULO:              return visitSMULO(N);
1294   case ISD::UMULO:              return visitUMULO(N);
1295   case ISD::SDIVREM:            return visitSDIVREM(N);
1296   case ISD::UDIVREM:            return visitUDIVREM(N);
1297   case ISD::AND:                return visitAND(N);
1298   case ISD::OR:                 return visitOR(N);
1299   case ISD::XOR:                return visitXOR(N);
1300   case ISD::SHL:                return visitSHL(N);
1301   case ISD::SRA:                return visitSRA(N);
1302   case ISD::SRL:                return visitSRL(N);
1303   case ISD::ROTR:
1304   case ISD::ROTL:               return visitRotate(N);
1305   case ISD::CTLZ:               return visitCTLZ(N);
1306   case ISD::CTLZ_ZERO_UNDEF:    return visitCTLZ_ZERO_UNDEF(N);
1307   case ISD::CTTZ:               return visitCTTZ(N);
1308   case ISD::CTTZ_ZERO_UNDEF:    return visitCTTZ_ZERO_UNDEF(N);
1309   case ISD::CTPOP:              return visitCTPOP(N);
1310   case ISD::SELECT:             return visitSELECT(N);
1311   case ISD::VSELECT:            return visitVSELECT(N);
1312   case ISD::SELECT_CC:          return visitSELECT_CC(N);
1313   case ISD::SETCC:              return visitSETCC(N);
1314   case ISD::SIGN_EXTEND:        return visitSIGN_EXTEND(N);
1315   case ISD::ZERO_EXTEND:        return visitZERO_EXTEND(N);
1316   case ISD::ANY_EXTEND:         return visitANY_EXTEND(N);
1317   case ISD::SIGN_EXTEND_INREG:  return visitSIGN_EXTEND_INREG(N);
1318   case ISD::TRUNCATE:           return visitTRUNCATE(N);
1319   case ISD::BITCAST:            return visitBITCAST(N);
1320   case ISD::BUILD_PAIR:         return visitBUILD_PAIR(N);
1321   case ISD::FADD:               return visitFADD(N);
1322   case ISD::FSUB:               return visitFSUB(N);
1323   case ISD::FMUL:               return visitFMUL(N);
1324   case ISD::FMA:                return visitFMA(N);
1325   case ISD::FDIV:               return visitFDIV(N);
1326   case ISD::FREM:               return visitFREM(N);
1327   case ISD::FSQRT:              return visitFSQRT(N);
1328   case ISD::FCOPYSIGN:          return visitFCOPYSIGN(N);
1329   case ISD::SINT_TO_FP:         return visitSINT_TO_FP(N);
1330   case ISD::UINT_TO_FP:         return visitUINT_TO_FP(N);
1331   case ISD::FP_TO_SINT:         return visitFP_TO_SINT(N);
1332   case ISD::FP_TO_UINT:         return visitFP_TO_UINT(N);
1333   case ISD::FP_ROUND:           return visitFP_ROUND(N);
1334   case ISD::FP_ROUND_INREG:     return visitFP_ROUND_INREG(N);
1335   case ISD::FP_EXTEND:          return visitFP_EXTEND(N);
1336   case ISD::FNEG:               return visitFNEG(N);
1337   case ISD::FABS:               return visitFABS(N);
1338   case ISD::FFLOOR:             return visitFFLOOR(N);
1339   case ISD::FMINNUM:            return visitFMINNUM(N);
1340   case ISD::FMAXNUM:            return visitFMAXNUM(N);
1341   case ISD::FCEIL:              return visitFCEIL(N);
1342   case ISD::FTRUNC:             return visitFTRUNC(N);
1343   case ISD::BRCOND:             return visitBRCOND(N);
1344   case ISD::BR_CC:              return visitBR_CC(N);
1345   case ISD::LOAD:               return visitLOAD(N);
1346   case ISD::STORE:              return visitSTORE(N);
1347   case ISD::INSERT_VECTOR_ELT:  return visitINSERT_VECTOR_ELT(N);
1348   case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
1349   case ISD::BUILD_VECTOR:       return visitBUILD_VECTOR(N);
1350   case ISD::CONCAT_VECTORS:     return visitCONCAT_VECTORS(N);
1351   case ISD::EXTRACT_SUBVECTOR:  return visitEXTRACT_SUBVECTOR(N);
1352   case ISD::VECTOR_SHUFFLE:     return visitVECTOR_SHUFFLE(N);
1353   case ISD::INSERT_SUBVECTOR:   return visitINSERT_SUBVECTOR(N);
1354   }
1355   return SDValue();
1356 }
1357
1358 SDValue DAGCombiner::combine(SDNode *N) {
1359   SDValue RV = visit(N);
1360
1361   // If nothing happened, try a target-specific DAG combine.
1362   if (!RV.getNode()) {
1363     assert(N->getOpcode() != ISD::DELETED_NODE &&
1364            "Node was deleted but visit returned NULL!");
1365
1366     if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
1367         TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
1368
1369       // Expose the DAG combiner to the target combiner impls.
1370       TargetLowering::DAGCombinerInfo
1371         DagCombineInfo(DAG, Level, false, this);
1372
1373       RV = TLI.PerformDAGCombine(N, DagCombineInfo);
1374     }
1375   }
1376
1377   // If nothing happened still, try promoting the operation.
1378   if (!RV.getNode()) {
1379     switch (N->getOpcode()) {
1380     default: break;
1381     case ISD::ADD:
1382     case ISD::SUB:
1383     case ISD::MUL:
1384     case ISD::AND:
1385     case ISD::OR:
1386     case ISD::XOR:
1387       RV = PromoteIntBinOp(SDValue(N, 0));
1388       break;
1389     case ISD::SHL:
1390     case ISD::SRA:
1391     case ISD::SRL:
1392       RV = PromoteIntShiftOp(SDValue(N, 0));
1393       break;
1394     case ISD::SIGN_EXTEND:
1395     case ISD::ZERO_EXTEND:
1396     case ISD::ANY_EXTEND:
1397       RV = PromoteExtend(SDValue(N, 0));
1398       break;
1399     case ISD::LOAD:
1400       if (PromoteLoad(SDValue(N, 0)))
1401         RV = SDValue(N, 0);
1402       break;
1403     }
1404   }
1405
1406   // If N is a commutative binary node, try commuting it to enable more
1407   // sdisel CSE.
1408   if (!RV.getNode() && SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
1409       N->getNumValues() == 1) {
1410     SDValue N0 = N->getOperand(0);
1411     SDValue N1 = N->getOperand(1);
1412
1413     // Constant operands are canonicalized to RHS.
1414     if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
1415       SDValue Ops[] = {N1, N0};
1416       SDNode *CSENode;
1417       if (const BinaryWithFlagsSDNode *BinNode =
1418               dyn_cast<BinaryWithFlagsSDNode>(N)) {
1419         CSENode = DAG.getNodeIfExists(
1420             N->getOpcode(), N->getVTList(), Ops, BinNode->hasNoUnsignedWrap(),
1421             BinNode->hasNoSignedWrap(), BinNode->isExact());
1422       } else {
1423         CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops);
1424       }
1425       if (CSENode)
1426         return SDValue(CSENode, 0);
1427     }
1428   }
1429
1430   return RV;
1431 }
1432
1433 /// Given a node, return its input chain if it has one, otherwise return a null
1434 /// sd operand.
1435 static SDValue getInputChainForNode(SDNode *N) {
1436   if (unsigned NumOps = N->getNumOperands()) {
1437     if (N->getOperand(0).getValueType() == MVT::Other)
1438       return N->getOperand(0);
1439     if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
1440       return N->getOperand(NumOps-1);
1441     for (unsigned i = 1; i < NumOps-1; ++i)
1442       if (N->getOperand(i).getValueType() == MVT::Other)
1443         return N->getOperand(i);
1444   }
1445   return SDValue();
1446 }
1447
1448 SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
1449   // If N has two operands, where one has an input chain equal to the other,
1450   // the 'other' chain is redundant.
1451   if (N->getNumOperands() == 2) {
1452     if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
1453       return N->getOperand(0);
1454     if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
1455       return N->getOperand(1);
1456   }
1457
1458   SmallVector<SDNode *, 8> TFs;     // List of token factors to visit.
1459   SmallVector<SDValue, 8> Ops;    // Ops for replacing token factor.
1460   SmallPtrSet<SDNode*, 16> SeenOps;
1461   bool Changed = false;             // If we should replace this token factor.
1462
1463   // Start out with this token factor.
1464   TFs.push_back(N);
1465
1466   // Iterate through token factors.  The TFs grows when new token factors are
1467   // encountered.
1468   for (unsigned i = 0; i < TFs.size(); ++i) {
1469     SDNode *TF = TFs[i];
1470
1471     // Check each of the operands.
1472     for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
1473       SDValue Op = TF->getOperand(i);
1474
1475       switch (Op.getOpcode()) {
1476       case ISD::EntryToken:
1477         // Entry tokens don't need to be added to the list. They are
1478         // rededundant.
1479         Changed = true;
1480         break;
1481
1482       case ISD::TokenFactor:
1483         if (Op.hasOneUse() &&
1484             std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
1485           // Queue up for processing.
1486           TFs.push_back(Op.getNode());
1487           // Clean up in case the token factor is removed.
1488           AddToWorklist(Op.getNode());
1489           Changed = true;
1490           break;
1491         }
1492         // Fall thru
1493
1494       default:
1495         // Only add if it isn't already in the list.
1496         if (SeenOps.insert(Op.getNode()).second)
1497           Ops.push_back(Op);
1498         else
1499           Changed = true;
1500         break;
1501       }
1502     }
1503   }
1504
1505   SDValue Result;
1506
1507   // If we've change things around then replace token factor.
1508   if (Changed) {
1509     if (Ops.empty()) {
1510       // The entry token is the only possible outcome.
1511       Result = DAG.getEntryNode();
1512     } else {
1513       // New and improved token factor.
1514       Result = DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Ops);
1515     }
1516
1517     // Don't add users to work list.
1518     return CombineTo(N, Result, false);
1519   }
1520
1521   return Result;
1522 }
1523
1524 /// MERGE_VALUES can always be eliminated.
1525 SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
1526   WorklistRemover DeadNodes(*this);
1527   // Replacing results may cause a different MERGE_VALUES to suddenly
1528   // be CSE'd with N, and carry its uses with it. Iterate until no
1529   // uses remain, to ensure that the node can be safely deleted.
1530   // First add the users of this node to the work list so that they
1531   // can be tried again once they have new operands.
1532   AddUsersToWorklist(N);
1533   do {
1534     for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
1535       DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
1536   } while (!N->use_empty());
1537   deleteAndRecombine(N);
1538   return SDValue(N, 0);   // Return N so it doesn't get rechecked!
1539 }
1540
1541 SDValue DAGCombiner::visitADD(SDNode *N) {
1542   SDValue N0 = N->getOperand(0);
1543   SDValue N1 = N->getOperand(1);
1544   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1545   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1546   EVT VT = N0.getValueType();
1547
1548   // fold vector ops
1549   if (VT.isVector()) {
1550     SDValue FoldedVOp = SimplifyVBinOp(N);
1551     if (FoldedVOp.getNode()) return FoldedVOp;
1552
1553     // fold (add x, 0) -> x, vector edition
1554     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1555       return N0;
1556     if (ISD::isBuildVectorAllZeros(N0.getNode()))
1557       return N1;
1558   }
1559
1560   // fold (add x, undef) -> undef
1561   if (N0.getOpcode() == ISD::UNDEF)
1562     return N0;
1563   if (N1.getOpcode() == ISD::UNDEF)
1564     return N1;
1565   // fold (add c1, c2) -> c1+c2
1566   if (N0C && N1C)
1567     return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
1568   // canonicalize constant to RHS
1569   if (N0C && !N1C)
1570     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N1, N0);
1571   // fold (add x, 0) -> x
1572   if (N1C && N1C->isNullValue())
1573     return N0;
1574   // fold (add Sym, c) -> Sym+c
1575   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1576     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
1577         GA->getOpcode() == ISD::GlobalAddress)
1578       return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1579                                   GA->getOffset() +
1580                                     (uint64_t)N1C->getSExtValue());
1581   // fold ((c1-A)+c2) -> (c1+c2)-A
1582   if (N1C && N0.getOpcode() == ISD::SUB)
1583     if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
1584       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1585                          DAG.getConstant(N1C->getAPIntValue()+
1586                                          N0C->getAPIntValue(), VT),
1587                          N0.getOperand(1));
1588   // reassociate add
1589   SDValue RADD = ReassociateOps(ISD::ADD, SDLoc(N), N0, N1);
1590   if (RADD.getNode())
1591     return RADD;
1592   // fold ((0-A) + B) -> B-A
1593   if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
1594       cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
1595     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1, N0.getOperand(1));
1596   // fold (A + (0-B)) -> A-B
1597   if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
1598       cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
1599     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1.getOperand(1));
1600   // fold (A+(B-A)) -> B
1601   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
1602     return N1.getOperand(0);
1603   // fold ((B-A)+A) -> B
1604   if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
1605     return N0.getOperand(0);
1606   // fold (A+(B-(A+C))) to (B-C)
1607   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1608       N0 == N1.getOperand(1).getOperand(0))
1609     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1610                        N1.getOperand(1).getOperand(1));
1611   // fold (A+(B-(C+A))) to (B-C)
1612   if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
1613       N0 == N1.getOperand(1).getOperand(1))
1614     return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1.getOperand(0),
1615                        N1.getOperand(1).getOperand(0));
1616   // fold (A+((B-A)+or-C)) to (B+or-C)
1617   if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
1618       N1.getOperand(0).getOpcode() == ISD::SUB &&
1619       N0 == N1.getOperand(0).getOperand(1))
1620     return DAG.getNode(N1.getOpcode(), SDLoc(N), VT,
1621                        N1.getOperand(0).getOperand(0), N1.getOperand(1));
1622
1623   // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
1624   if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
1625     SDValue N00 = N0.getOperand(0);
1626     SDValue N01 = N0.getOperand(1);
1627     SDValue N10 = N1.getOperand(0);
1628     SDValue N11 = N1.getOperand(1);
1629
1630     if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
1631       return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1632                          DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
1633                          DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
1634   }
1635
1636   if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
1637     return SDValue(N, 0);
1638
1639   // fold (a+b) -> (a|b) iff a and b share no bits.
1640   if (VT.isInteger() && !VT.isVector()) {
1641     APInt LHSZero, LHSOne;
1642     APInt RHSZero, RHSOne;
1643     DAG.computeKnownBits(N0, LHSZero, LHSOne);
1644
1645     if (LHSZero.getBoolValue()) {
1646       DAG.computeKnownBits(N1, RHSZero, RHSOne);
1647
1648       // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1649       // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1650       if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero){
1651         if (!LegalOperations || TLI.isOperationLegal(ISD::OR, VT))
1652           return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1);
1653       }
1654     }
1655   }
1656
1657   // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
1658   if (N1.getOpcode() == ISD::SHL &&
1659       N1.getOperand(0).getOpcode() == ISD::SUB)
1660     if (ConstantSDNode *C =
1661           dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
1662       if (C->getAPIntValue() == 0)
1663         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N0,
1664                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1665                                        N1.getOperand(0).getOperand(1),
1666                                        N1.getOperand(1)));
1667   if (N0.getOpcode() == ISD::SHL &&
1668       N0.getOperand(0).getOpcode() == ISD::SUB)
1669     if (ConstantSDNode *C =
1670           dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
1671       if (C->getAPIntValue() == 0)
1672         return DAG.getNode(ISD::SUB, SDLoc(N), VT, N1,
1673                            DAG.getNode(ISD::SHL, SDLoc(N), VT,
1674                                        N0.getOperand(0).getOperand(1),
1675                                        N0.getOperand(1)));
1676
1677   if (N1.getOpcode() == ISD::AND) {
1678     SDValue AndOp0 = N1.getOperand(0);
1679     ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
1680     unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
1681     unsigned DestBits = VT.getScalarType().getSizeInBits();
1682
1683     // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
1684     // and similar xforms where the inner op is either ~0 or 0.
1685     if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
1686       SDLoc DL(N);
1687       return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
1688     }
1689   }
1690
1691   // add (sext i1), X -> sub X, (zext i1)
1692   if (N0.getOpcode() == ISD::SIGN_EXTEND &&
1693       N0.getOperand(0).getValueType() == MVT::i1 &&
1694       !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
1695     SDLoc DL(N);
1696     SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
1697     return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
1698   }
1699
1700   // add X, (sextinreg Y i1) -> sub X, (and Y 1)
1701   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1702     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1703     if (TN->getVT() == MVT::i1) {
1704       SDLoc DL(N);
1705       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1706                                  DAG.getConstant(1, VT));
1707       return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
1708     }
1709   }
1710
1711   return SDValue();
1712 }
1713
1714 SDValue DAGCombiner::visitADDC(SDNode *N) {
1715   SDValue N0 = N->getOperand(0);
1716   SDValue N1 = N->getOperand(1);
1717   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1718   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1719   EVT VT = N0.getValueType();
1720
1721   // If the flag result is dead, turn this into an ADD.
1722   if (!N->hasAnyUseOfValue(1))
1723     return CombineTo(N, DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, N1),
1724                      DAG.getNode(ISD::CARRY_FALSE,
1725                                  SDLoc(N), MVT::Glue));
1726
1727   // canonicalize constant to RHS.
1728   if (N0C && !N1C)
1729     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N1, N0);
1730
1731   // fold (addc x, 0) -> x + no carry out
1732   if (N1C && N1C->isNullValue())
1733     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
1734                                         SDLoc(N), MVT::Glue));
1735
1736   // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
1737   APInt LHSZero, LHSOne;
1738   APInt RHSZero, RHSOne;
1739   DAG.computeKnownBits(N0, LHSZero, LHSOne);
1740
1741   if (LHSZero.getBoolValue()) {
1742     DAG.computeKnownBits(N1, RHSZero, RHSOne);
1743
1744     // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
1745     // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
1746     if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
1747       return CombineTo(N, DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N1),
1748                        DAG.getNode(ISD::CARRY_FALSE,
1749                                    SDLoc(N), MVT::Glue));
1750   }
1751
1752   return SDValue();
1753 }
1754
1755 SDValue DAGCombiner::visitADDE(SDNode *N) {
1756   SDValue N0 = N->getOperand(0);
1757   SDValue N1 = N->getOperand(1);
1758   SDValue CarryIn = N->getOperand(2);
1759   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1760   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1761
1762   // canonicalize constant to RHS
1763   if (N0C && !N1C)
1764     return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
1765                        N1, N0, CarryIn);
1766
1767   // fold (adde x, y, false) -> (addc x, y)
1768   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1769     return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
1770
1771   return SDValue();
1772 }
1773
1774 // Since it may not be valid to emit a fold to zero for vector initializers
1775 // check if we can before folding.
1776 static SDValue tryFoldToZero(SDLoc DL, const TargetLowering &TLI, EVT VT,
1777                              SelectionDAG &DAG,
1778                              bool LegalOperations, bool LegalTypes) {
1779   if (!VT.isVector())
1780     return DAG.getConstant(0, VT);
1781   if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
1782     return DAG.getConstant(0, VT);
1783   return SDValue();
1784 }
1785
1786 SDValue DAGCombiner::visitSUB(SDNode *N) {
1787   SDValue N0 = N->getOperand(0);
1788   SDValue N1 = N->getOperand(1);
1789   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
1790   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
1791   ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? nullptr :
1792     dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
1793   EVT VT = N0.getValueType();
1794
1795   // fold vector ops
1796   if (VT.isVector()) {
1797     SDValue FoldedVOp = SimplifyVBinOp(N);
1798     if (FoldedVOp.getNode()) return FoldedVOp;
1799
1800     // fold (sub x, 0) -> x, vector edition
1801     if (ISD::isBuildVectorAllZeros(N1.getNode()))
1802       return N0;
1803   }
1804
1805   // fold (sub x, x) -> 0
1806   // FIXME: Refactor this and xor and other similar operations together.
1807   if (N0 == N1)
1808     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
1809   // fold (sub c1, c2) -> c1-c2
1810   if (N0C && N1C)
1811     return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
1812   // fold (sub x, c) -> (add x, -c)
1813   if (N1C)
1814     return DAG.getNode(ISD::ADD, SDLoc(N), VT, N0,
1815                        DAG.getConstant(-N1C->getAPIntValue(), VT));
1816   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
1817   if (N0C && N0C->isAllOnesValue())
1818     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
1819   // fold A-(A-B) -> B
1820   if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
1821     return N1.getOperand(1);
1822   // fold (A+B)-A -> B
1823   if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
1824     return N0.getOperand(1);
1825   // fold (A+B)-B -> A
1826   if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
1827     return N0.getOperand(0);
1828   // fold C2-(A+C1) -> (C2-C1)-A
1829   if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
1830     SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
1831                                    VT);
1832     return DAG.getNode(ISD::SUB, SDLoc(N), VT, NewC,
1833                        N1.getOperand(0));
1834   }
1835   // fold ((A+(B+or-C))-B) -> A+or-C
1836   if (N0.getOpcode() == ISD::ADD &&
1837       (N0.getOperand(1).getOpcode() == ISD::SUB ||
1838        N0.getOperand(1).getOpcode() == ISD::ADD) &&
1839       N0.getOperand(1).getOperand(0) == N1)
1840     return DAG.getNode(N0.getOperand(1).getOpcode(), SDLoc(N), VT,
1841                        N0.getOperand(0), N0.getOperand(1).getOperand(1));
1842   // fold ((A+(C+B))-B) -> A+C
1843   if (N0.getOpcode() == ISD::ADD &&
1844       N0.getOperand(1).getOpcode() == ISD::ADD &&
1845       N0.getOperand(1).getOperand(1) == N1)
1846     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
1847                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1848   // fold ((A-(B-C))-C) -> A-B
1849   if (N0.getOpcode() == ISD::SUB &&
1850       N0.getOperand(1).getOpcode() == ISD::SUB &&
1851       N0.getOperand(1).getOperand(1) == N1)
1852     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1853                        N0.getOperand(0), N0.getOperand(1).getOperand(0));
1854
1855   // If either operand of a sub is undef, the result is undef
1856   if (N0.getOpcode() == ISD::UNDEF)
1857     return N0;
1858   if (N1.getOpcode() == ISD::UNDEF)
1859     return N1;
1860
1861   // If the relocation model supports it, consider symbol offsets.
1862   if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
1863     if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
1864       // fold (sub Sym, c) -> Sym-c
1865       if (N1C && GA->getOpcode() == ISD::GlobalAddress)
1866         return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
1867                                     GA->getOffset() -
1868                                       (uint64_t)N1C->getSExtValue());
1869       // fold (sub Sym+c1, Sym+c2) -> c1-c2
1870       if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
1871         if (GA->getGlobal() == GB->getGlobal())
1872           return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
1873                                  VT);
1874     }
1875
1876   // sub X, (sextinreg Y i1) -> add X, (and Y 1)
1877   if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
1878     VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
1879     if (TN->getVT() == MVT::i1) {
1880       SDLoc DL(N);
1881       SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
1882                                  DAG.getConstant(1, VT));
1883       return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
1884     }
1885   }
1886
1887   return SDValue();
1888 }
1889
1890 SDValue DAGCombiner::visitSUBC(SDNode *N) {
1891   SDValue N0 = N->getOperand(0);
1892   SDValue N1 = N->getOperand(1);
1893   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
1894   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
1895   EVT VT = N0.getValueType();
1896
1897   // If the flag result is dead, turn this into an SUB.
1898   if (!N->hasAnyUseOfValue(1))
1899     return CombineTo(N, DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, N1),
1900                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1901                                  MVT::Glue));
1902
1903   // fold (subc x, x) -> 0 + no borrow
1904   if (N0 == N1)
1905     return CombineTo(N, DAG.getConstant(0, VT),
1906                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1907                                  MVT::Glue));
1908
1909   // fold (subc x, 0) -> x + no borrow
1910   if (N1C && N1C->isNullValue())
1911     return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1912                                         MVT::Glue));
1913
1914   // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
1915   if (N0C && N0C->isAllOnesValue())
1916     return CombineTo(N, DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0),
1917                      DAG.getNode(ISD::CARRY_FALSE, SDLoc(N),
1918                                  MVT::Glue));
1919
1920   return SDValue();
1921 }
1922
1923 SDValue DAGCombiner::visitSUBE(SDNode *N) {
1924   SDValue N0 = N->getOperand(0);
1925   SDValue N1 = N->getOperand(1);
1926   SDValue CarryIn = N->getOperand(2);
1927
1928   // fold (sube x, y, false) -> (subc x, y)
1929   if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
1930     return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
1931
1932   return SDValue();
1933 }
1934
1935 SDValue DAGCombiner::visitMUL(SDNode *N) {
1936   SDValue N0 = N->getOperand(0);
1937   SDValue N1 = N->getOperand(1);
1938   EVT VT = N0.getValueType();
1939
1940   // fold (mul x, undef) -> 0
1941   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
1942     return DAG.getConstant(0, VT);
1943
1944   bool N0IsConst = false;
1945   bool N1IsConst = false;
1946   APInt ConstValue0, ConstValue1;
1947   // fold vector ops
1948   if (VT.isVector()) {
1949     SDValue FoldedVOp = SimplifyVBinOp(N);
1950     if (FoldedVOp.getNode()) return FoldedVOp;
1951
1952     N0IsConst = isConstantSplatVector(N0.getNode(), ConstValue0);
1953     N1IsConst = isConstantSplatVector(N1.getNode(), ConstValue1);
1954   } else {
1955     N0IsConst = dyn_cast<ConstantSDNode>(N0) != nullptr;
1956     ConstValue0 = N0IsConst ? (dyn_cast<ConstantSDNode>(N0))->getAPIntValue()
1957                             : APInt();
1958     N1IsConst = dyn_cast<ConstantSDNode>(N1) != nullptr;
1959     ConstValue1 = N1IsConst ? (dyn_cast<ConstantSDNode>(N1))->getAPIntValue()
1960                             : APInt();
1961   }
1962
1963   // fold (mul c1, c2) -> c1*c2
1964   if (N0IsConst && N1IsConst)
1965     return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0.getNode(), N1.getNode());
1966
1967   // canonicalize constant to RHS
1968   if (N0IsConst && !N1IsConst)
1969     return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
1970   // fold (mul x, 0) -> 0
1971   if (N1IsConst && ConstValue1 == 0)
1972     return N1;
1973   // We require a splat of the entire scalar bit width for non-contiguous
1974   // bit patterns.
1975   bool IsFullSplat =
1976     ConstValue1.getBitWidth() == VT.getScalarType().getSizeInBits();
1977   // fold (mul x, 1) -> x
1978   if (N1IsConst && ConstValue1 == 1 && IsFullSplat)
1979     return N0;
1980   // fold (mul x, -1) -> 0-x
1981   if (N1IsConst && ConstValue1.isAllOnesValue())
1982     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1983                        DAG.getConstant(0, VT), N0);
1984   // fold (mul x, (1 << c)) -> x << c
1985   if (N1IsConst && ConstValue1.isPowerOf2() && IsFullSplat)
1986     return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1987                        DAG.getConstant(ConstValue1.logBase2(),
1988                                        getShiftAmountTy(N0.getValueType())));
1989   // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
1990   if (N1IsConst && (-ConstValue1).isPowerOf2() && IsFullSplat) {
1991     unsigned Log2Val = (-ConstValue1).logBase2();
1992     // FIXME: If the input is something that is easily negated (e.g. a
1993     // single-use add), we should put the negate there.
1994     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
1995                        DAG.getConstant(0, VT),
1996                        DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
1997                             DAG.getConstant(Log2Val,
1998                                       getShiftAmountTy(N0.getValueType()))));
1999   }
2000
2001   APInt Val;
2002   // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
2003   if (N1IsConst && N0.getOpcode() == ISD::SHL &&
2004       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2005                      isa<ConstantSDNode>(N0.getOperand(1)))) {
2006     SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT,
2007                              N1, N0.getOperand(1));
2008     AddToWorklist(C3.getNode());
2009     return DAG.getNode(ISD::MUL, SDLoc(N), VT,
2010                        N0.getOperand(0), C3);
2011   }
2012
2013   // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
2014   // use.
2015   {
2016     SDValue Sh(nullptr,0), Y(nullptr,0);
2017     // Check for both (mul (shl X, C), Y)  and  (mul Y, (shl X, C)).
2018     if (N0.getOpcode() == ISD::SHL &&
2019         (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2020                        isa<ConstantSDNode>(N0.getOperand(1))) &&
2021         N0.getNode()->hasOneUse()) {
2022       Sh = N0; Y = N1;
2023     } else if (N1.getOpcode() == ISD::SHL &&
2024                isa<ConstantSDNode>(N1.getOperand(1)) &&
2025                N1.getNode()->hasOneUse()) {
2026       Sh = N1; Y = N0;
2027     }
2028
2029     if (Sh.getNode()) {
2030       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2031                                 Sh.getOperand(0), Y);
2032       return DAG.getNode(ISD::SHL, SDLoc(N), VT,
2033                          Mul, Sh.getOperand(1));
2034     }
2035   }
2036
2037   // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
2038   if (N1IsConst && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
2039       (isConstantSplatVector(N0.getOperand(1).getNode(), Val) ||
2040                      isa<ConstantSDNode>(N0.getOperand(1))))
2041     return DAG.getNode(ISD::ADD, SDLoc(N), VT,
2042                        DAG.getNode(ISD::MUL, SDLoc(N0), VT,
2043                                    N0.getOperand(0), N1),
2044                        DAG.getNode(ISD::MUL, SDLoc(N1), VT,
2045                                    N0.getOperand(1), N1));
2046
2047   // reassociate mul
2048   SDValue RMUL = ReassociateOps(ISD::MUL, SDLoc(N), N0, N1);
2049   if (RMUL.getNode())
2050     return RMUL;
2051
2052   return SDValue();
2053 }
2054
2055 SDValue DAGCombiner::visitSDIV(SDNode *N) {
2056   SDValue N0 = N->getOperand(0);
2057   SDValue N1 = N->getOperand(1);
2058   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2059   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2060   EVT VT = N->getValueType(0);
2061
2062   // fold vector ops
2063   if (VT.isVector()) {
2064     SDValue FoldedVOp = SimplifyVBinOp(N);
2065     if (FoldedVOp.getNode()) return FoldedVOp;
2066   }
2067
2068   // fold (sdiv c1, c2) -> c1/c2
2069   if (N0C && N1C && !N1C->isNullValue())
2070     return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
2071   // fold (sdiv X, 1) -> X
2072   if (N1C && N1C->getAPIntValue() == 1LL)
2073     return N0;
2074   // fold (sdiv X, -1) -> 0-X
2075   if (N1C && N1C->isAllOnesValue())
2076     return DAG.getNode(ISD::SUB, SDLoc(N), VT,
2077                        DAG.getConstant(0, VT), N0);
2078   // If we know the sign bits of both operands are zero, strength reduce to a
2079   // udiv instead.  Handles (X&15) /s 4 -> X&15 >> 2
2080   if (!VT.isVector()) {
2081     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2082       return DAG.getNode(ISD::UDIV, SDLoc(N), N1.getValueType(),
2083                          N0, N1);
2084   }
2085
2086   // fold (sdiv X, pow2) -> simple ops after legalize
2087   if (N1C && !N1C->isNullValue() && (N1C->getAPIntValue().isPowerOf2() ||
2088                                      (-N1C->getAPIntValue()).isPowerOf2())) {
2089     // If dividing by powers of two is cheap, then don't perform the following
2090     // fold.
2091     if (TLI.isPow2SDivCheap())
2092       return SDValue();
2093
2094     // Target-specific implementation of sdiv x, pow2.
2095     SDValue Res = BuildSDIVPow2(N);
2096     if (Res.getNode())
2097       return Res;
2098
2099     unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
2100
2101     // Splat the sign bit into the register
2102     SDValue SGN =
2103         DAG.getNode(ISD::SRA, SDLoc(N), VT, N0,
2104                     DAG.getConstant(VT.getScalarSizeInBits() - 1,
2105                                     getShiftAmountTy(N0.getValueType())));
2106     AddToWorklist(SGN.getNode());
2107
2108     // Add (N0 < 0) ? abs2 - 1 : 0;
2109     SDValue SRL =
2110         DAG.getNode(ISD::SRL, SDLoc(N), VT, SGN,
2111                     DAG.getConstant(VT.getScalarSizeInBits() - lg2,
2112                                     getShiftAmountTy(SGN.getValueType())));
2113     SDValue ADD = DAG.getNode(ISD::ADD, SDLoc(N), VT, N0, SRL);
2114     AddToWorklist(SRL.getNode());
2115     AddToWorklist(ADD.getNode());    // Divide by pow2
2116     SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), VT, ADD,
2117                   DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
2118
2119     // If we're dividing by a positive value, we're done.  Otherwise, we must
2120     // negate the result.
2121     if (N1C->getAPIntValue().isNonNegative())
2122       return SRA;
2123
2124     AddToWorklist(SRA.getNode());
2125     return DAG.getNode(ISD::SUB, SDLoc(N), VT, DAG.getConstant(0, VT), SRA);
2126   }
2127
2128   // if integer divide is expensive and we satisfy the requirements, emit an
2129   // alternate sequence.
2130   if (N1C && !TLI.isIntDivCheap()) {
2131     SDValue Op = BuildSDIV(N);
2132     if (Op.getNode()) return Op;
2133   }
2134
2135   // undef / X -> 0
2136   if (N0.getOpcode() == ISD::UNDEF)
2137     return DAG.getConstant(0, VT);
2138   // X / undef -> undef
2139   if (N1.getOpcode() == ISD::UNDEF)
2140     return N1;
2141
2142   return SDValue();
2143 }
2144
2145 SDValue DAGCombiner::visitUDIV(SDNode *N) {
2146   SDValue N0 = N->getOperand(0);
2147   SDValue N1 = N->getOperand(1);
2148   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2149   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2150   EVT VT = N->getValueType(0);
2151
2152   // fold vector ops
2153   if (VT.isVector()) {
2154     SDValue FoldedVOp = SimplifyVBinOp(N);
2155     if (FoldedVOp.getNode()) return FoldedVOp;
2156   }
2157
2158   // fold (udiv c1, c2) -> c1/c2
2159   if (N0C && N1C && !N1C->isNullValue())
2160     return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
2161   // fold (udiv x, (1 << c)) -> x >>u c
2162   if (N1C && N1C->getAPIntValue().isPowerOf2())
2163     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0,
2164                        DAG.getConstant(N1C->getAPIntValue().logBase2(),
2165                                        getShiftAmountTy(N0.getValueType())));
2166   // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
2167   if (N1.getOpcode() == ISD::SHL) {
2168     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2169       if (SHC->getAPIntValue().isPowerOf2()) {
2170         EVT ADDVT = N1.getOperand(1).getValueType();
2171         SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N), ADDVT,
2172                                   N1.getOperand(1),
2173                                   DAG.getConstant(SHC->getAPIntValue()
2174                                                                   .logBase2(),
2175                                                   ADDVT));
2176         AddToWorklist(Add.getNode());
2177         return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, Add);
2178       }
2179     }
2180   }
2181   // fold (udiv x, c) -> alternate
2182   if (N1C && !TLI.isIntDivCheap()) {
2183     SDValue Op = BuildUDIV(N);
2184     if (Op.getNode()) return Op;
2185   }
2186
2187   // undef / X -> 0
2188   if (N0.getOpcode() == ISD::UNDEF)
2189     return DAG.getConstant(0, VT);
2190   // X / undef -> undef
2191   if (N1.getOpcode() == ISD::UNDEF)
2192     return N1;
2193
2194   return SDValue();
2195 }
2196
2197 SDValue DAGCombiner::visitSREM(SDNode *N) {
2198   SDValue N0 = N->getOperand(0);
2199   SDValue N1 = N->getOperand(1);
2200   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2201   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2202   EVT VT = N->getValueType(0);
2203
2204   // fold (srem c1, c2) -> c1%c2
2205   if (N0C && N1C && !N1C->isNullValue())
2206     return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
2207   // If we know the sign bits of both operands are zero, strength reduce to a
2208   // urem instead.  Handles (X & 0x0FFFFFFF) %s 16 -> X&15
2209   if (!VT.isVector()) {
2210     if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
2211       return DAG.getNode(ISD::UREM, SDLoc(N), VT, N0, N1);
2212   }
2213
2214   // If X/C can be simplified by the division-by-constant logic, lower
2215   // X%C to the equivalent of X-X/C*C.
2216   if (N1C && !N1C->isNullValue()) {
2217     SDValue Div = DAG.getNode(ISD::SDIV, SDLoc(N), VT, N0, N1);
2218     AddToWorklist(Div.getNode());
2219     SDValue OptimizedDiv = combine(Div.getNode());
2220     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2221       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2222                                 OptimizedDiv, N1);
2223       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2224       AddToWorklist(Mul.getNode());
2225       return Sub;
2226     }
2227   }
2228
2229   // undef % X -> 0
2230   if (N0.getOpcode() == ISD::UNDEF)
2231     return DAG.getConstant(0, VT);
2232   // X % undef -> undef
2233   if (N1.getOpcode() == ISD::UNDEF)
2234     return N1;
2235
2236   return SDValue();
2237 }
2238
2239 SDValue DAGCombiner::visitUREM(SDNode *N) {
2240   SDValue N0 = N->getOperand(0);
2241   SDValue N1 = N->getOperand(1);
2242   ConstantSDNode *N0C = isConstOrConstSplat(N0);
2243   ConstantSDNode *N1C = isConstOrConstSplat(N1);
2244   EVT VT = N->getValueType(0);
2245
2246   // fold (urem c1, c2) -> c1%c2
2247   if (N0C && N1C && !N1C->isNullValue())
2248     return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
2249   // fold (urem x, pow2) -> (and x, pow2-1)
2250   if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
2251     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0,
2252                        DAG.getConstant(N1C->getAPIntValue()-1,VT));
2253   // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
2254   if (N1.getOpcode() == ISD::SHL) {
2255     if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
2256       if (SHC->getAPIntValue().isPowerOf2()) {
2257         SDValue Add =
2258           DAG.getNode(ISD::ADD, SDLoc(N), VT, N1,
2259                  DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
2260                                  VT));
2261         AddToWorklist(Add.getNode());
2262         return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, Add);
2263       }
2264     }
2265   }
2266
2267   // If X/C can be simplified by the division-by-constant logic, lower
2268   // X%C to the equivalent of X-X/C*C.
2269   if (N1C && !N1C->isNullValue()) {
2270     SDValue Div = DAG.getNode(ISD::UDIV, SDLoc(N), VT, N0, N1);
2271     AddToWorklist(Div.getNode());
2272     SDValue OptimizedDiv = combine(Div.getNode());
2273     if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
2274       SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT,
2275                                 OptimizedDiv, N1);
2276       SDValue Sub = DAG.getNode(ISD::SUB, SDLoc(N), VT, N0, Mul);
2277       AddToWorklist(Mul.getNode());
2278       return Sub;
2279     }
2280   }
2281
2282   // undef % X -> 0
2283   if (N0.getOpcode() == ISD::UNDEF)
2284     return DAG.getConstant(0, VT);
2285   // X % undef -> undef
2286   if (N1.getOpcode() == ISD::UNDEF)
2287     return N1;
2288
2289   return SDValue();
2290 }
2291
2292 SDValue DAGCombiner::visitMULHS(SDNode *N) {
2293   SDValue N0 = N->getOperand(0);
2294   SDValue N1 = N->getOperand(1);
2295   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2296   EVT VT = N->getValueType(0);
2297   SDLoc DL(N);
2298
2299   // fold (mulhs x, 0) -> 0
2300   if (N1C && N1C->isNullValue())
2301     return N1;
2302   // fold (mulhs x, 1) -> (sra x, size(x)-1)
2303   if (N1C && N1C->getAPIntValue() == 1)
2304     return DAG.getNode(ISD::SRA, SDLoc(N), N0.getValueType(), N0,
2305                        DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
2306                                        getShiftAmountTy(N0.getValueType())));
2307   // fold (mulhs x, undef) -> 0
2308   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2309     return DAG.getConstant(0, VT);
2310
2311   // If the type twice as wide is legal, transform the mulhs to a wider multiply
2312   // plus a shift.
2313   if (VT.isSimple() && !VT.isVector()) {
2314     MVT Simple = VT.getSimpleVT();
2315     unsigned SimpleSize = Simple.getSizeInBits();
2316     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2317     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2318       N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
2319       N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
2320       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2321       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2322             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2323       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2324     }
2325   }
2326
2327   return SDValue();
2328 }
2329
2330 SDValue DAGCombiner::visitMULHU(SDNode *N) {
2331   SDValue N0 = N->getOperand(0);
2332   SDValue N1 = N->getOperand(1);
2333   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2334   EVT VT = N->getValueType(0);
2335   SDLoc DL(N);
2336
2337   // fold (mulhu x, 0) -> 0
2338   if (N1C && N1C->isNullValue())
2339     return N1;
2340   // fold (mulhu x, 1) -> 0
2341   if (N1C && N1C->getAPIntValue() == 1)
2342     return DAG.getConstant(0, N0.getValueType());
2343   // fold (mulhu x, undef) -> 0
2344   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2345     return DAG.getConstant(0, VT);
2346
2347   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2348   // plus a shift.
2349   if (VT.isSimple() && !VT.isVector()) {
2350     MVT Simple = VT.getSimpleVT();
2351     unsigned SimpleSize = Simple.getSizeInBits();
2352     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2353     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2354       N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
2355       N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
2356       N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
2357       N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
2358             DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
2359       return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
2360     }
2361   }
2362
2363   return SDValue();
2364 }
2365
2366 /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
2367 /// give the opcodes for the two computations that are being performed. Return
2368 /// true if a simplification was made.
2369 SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
2370                                                 unsigned HiOp) {
2371   // If the high half is not needed, just compute the low half.
2372   bool HiExists = N->hasAnyUseOfValue(1);
2373   if (!HiExists &&
2374       (!LegalOperations ||
2375        TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
2376     SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2377     return CombineTo(N, Res, Res);
2378   }
2379
2380   // If the low half is not needed, just compute the high half.
2381   bool LoExists = N->hasAnyUseOfValue(0);
2382   if (!LoExists &&
2383       (!LegalOperations ||
2384        TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
2385     SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2386     return CombineTo(N, Res, Res);
2387   }
2388
2389   // If both halves are used, return as it is.
2390   if (LoExists && HiExists)
2391     return SDValue();
2392
2393   // If the two computed results can be simplified separately, separate them.
2394   if (LoExists) {
2395     SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
2396     AddToWorklist(Lo.getNode());
2397     SDValue LoOpt = combine(Lo.getNode());
2398     if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
2399         (!LegalOperations ||
2400          TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
2401       return CombineTo(N, LoOpt, LoOpt);
2402   }
2403
2404   if (HiExists) {
2405     SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
2406     AddToWorklist(Hi.getNode());
2407     SDValue HiOpt = combine(Hi.getNode());
2408     if (HiOpt.getNode() && HiOpt != Hi &&
2409         (!LegalOperations ||
2410          TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
2411       return CombineTo(N, HiOpt, HiOpt);
2412   }
2413
2414   return SDValue();
2415 }
2416
2417 SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
2418   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
2419   if (Res.getNode()) return Res;
2420
2421   EVT VT = N->getValueType(0);
2422   SDLoc DL(N);
2423
2424   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2425   // plus a shift.
2426   if (VT.isSimple() && !VT.isVector()) {
2427     MVT Simple = VT.getSimpleVT();
2428     unsigned SimpleSize = Simple.getSizeInBits();
2429     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2430     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2431       SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
2432       SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
2433       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2434       // Compute the high part as N1.
2435       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2436             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2437       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2438       // Compute the low part as N0.
2439       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2440       return CombineTo(N, Lo, Hi);
2441     }
2442   }
2443
2444   return SDValue();
2445 }
2446
2447 SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
2448   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
2449   if (Res.getNode()) return Res;
2450
2451   EVT VT = N->getValueType(0);
2452   SDLoc DL(N);
2453
2454   // If the type twice as wide is legal, transform the mulhu to a wider multiply
2455   // plus a shift.
2456   if (VT.isSimple() && !VT.isVector()) {
2457     MVT Simple = VT.getSimpleVT();
2458     unsigned SimpleSize = Simple.getSizeInBits();
2459     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
2460     if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
2461       SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
2462       SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
2463       Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
2464       // Compute the high part as N1.
2465       Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
2466             DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
2467       Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
2468       // Compute the low part as N0.
2469       Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
2470       return CombineTo(N, Lo, Hi);
2471     }
2472   }
2473
2474   return SDValue();
2475 }
2476
2477 SDValue DAGCombiner::visitSMULO(SDNode *N) {
2478   // (smulo x, 2) -> (saddo x, x)
2479   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2480     if (C2->getAPIntValue() == 2)
2481       return DAG.getNode(ISD::SADDO, SDLoc(N), N->getVTList(),
2482                          N->getOperand(0), N->getOperand(0));
2483
2484   return SDValue();
2485 }
2486
2487 SDValue DAGCombiner::visitUMULO(SDNode *N) {
2488   // (umulo x, 2) -> (uaddo x, x)
2489   if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2490     if (C2->getAPIntValue() == 2)
2491       return DAG.getNode(ISD::UADDO, SDLoc(N), N->getVTList(),
2492                          N->getOperand(0), N->getOperand(0));
2493
2494   return SDValue();
2495 }
2496
2497 SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
2498   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
2499   if (Res.getNode()) return Res;
2500
2501   return SDValue();
2502 }
2503
2504 SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
2505   SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
2506   if (Res.getNode()) return Res;
2507
2508   return SDValue();
2509 }
2510
2511 /// If this is a binary operator with two operands of the same opcode, try to
2512 /// simplify it.
2513 SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
2514   SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
2515   EVT VT = N0.getValueType();
2516   assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
2517
2518   // Bail early if none of these transforms apply.
2519   if (N0.getNode()->getNumOperands() == 0) return SDValue();
2520
2521   // For each of OP in AND/OR/XOR:
2522   // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
2523   // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
2524   // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
2525   // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
2526   //
2527   // do not sink logical op inside of a vector extend, since it may combine
2528   // into a vsetcc.
2529   EVT Op0VT = N0.getOperand(0).getValueType();
2530   if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
2531        N0.getOpcode() == ISD::SIGN_EXTEND ||
2532        // Avoid infinite looping with PromoteIntBinOp.
2533        (N0.getOpcode() == ISD::ANY_EXTEND &&
2534         (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
2535        (N0.getOpcode() == ISD::TRUNCATE &&
2536         (!TLI.isZExtFree(VT, Op0VT) ||
2537          !TLI.isTruncateFree(Op0VT, VT)) &&
2538         TLI.isTypeLegal(Op0VT))) &&
2539       !VT.isVector() &&
2540       Op0VT == N1.getOperand(0).getValueType() &&
2541       (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
2542     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2543                                  N0.getOperand(0).getValueType(),
2544                                  N0.getOperand(0), N1.getOperand(0));
2545     AddToWorklist(ORNode.getNode());
2546     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, ORNode);
2547   }
2548
2549   // For each of OP in SHL/SRL/SRA/AND...
2550   //   fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
2551   //   fold (or  (OP x, z), (OP y, z)) -> (OP (or  x, y), z)
2552   //   fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
2553   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
2554        N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
2555       N0.getOperand(1) == N1.getOperand(1)) {
2556     SDValue ORNode = DAG.getNode(N->getOpcode(), SDLoc(N0),
2557                                  N0.getOperand(0).getValueType(),
2558                                  N0.getOperand(0), N1.getOperand(0));
2559     AddToWorklist(ORNode.getNode());
2560     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
2561                        ORNode, N0.getOperand(1));
2562   }
2563
2564   // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
2565   // Only perform this optimization after type legalization and before
2566   // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
2567   // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
2568   // we don't want to undo this promotion.
2569   // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
2570   // on scalars.
2571   if ((N0.getOpcode() == ISD::BITCAST ||
2572        N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
2573       Level == AfterLegalizeTypes) {
2574     SDValue In0 = N0.getOperand(0);
2575     SDValue In1 = N1.getOperand(0);
2576     EVT In0Ty = In0.getValueType();
2577     EVT In1Ty = In1.getValueType();
2578     SDLoc DL(N);
2579     // If both incoming values are integers, and the original types are the
2580     // same.
2581     if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
2582       SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
2583       SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
2584       AddToWorklist(Op.getNode());
2585       return BC;
2586     }
2587   }
2588
2589   // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
2590   // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
2591   // If both shuffles use the same mask, and both shuffle within a single
2592   // vector, then it is worthwhile to move the swizzle after the operation.
2593   // The type-legalizer generates this pattern when loading illegal
2594   // vector types from memory. In many cases this allows additional shuffle
2595   // optimizations.
2596   // There are other cases where moving the shuffle after the xor/and/or
2597   // is profitable even if shuffles don't perform a swizzle.
2598   // If both shuffles use the same mask, and both shuffles have the same first
2599   // or second operand, then it might still be profitable to move the shuffle
2600   // after the xor/and/or operation.
2601   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
2602     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
2603     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
2604
2605     assert(N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType() &&
2606            "Inputs to shuffles are not the same type");
2607
2608     // Check that both shuffles use the same mask. The masks are known to be of
2609     // the same length because the result vector type is the same.
2610     // Check also that shuffles have only one use to avoid introducing extra
2611     // instructions.
2612     if (SVN0->hasOneUse() && SVN1->hasOneUse() &&
2613         SVN0->getMask().equals(SVN1->getMask())) {
2614       SDValue ShOp = N0->getOperand(1);
2615
2616       // Don't try to fold this node if it requires introducing a
2617       // build vector of all zeros that might be illegal at this stage.
2618       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2619         if (!LegalTypes)
2620           ShOp = DAG.getConstant(0, VT);
2621         else
2622           ShOp = SDValue();
2623       }
2624
2625       // (AND (shuf (A, C), shuf (B, C)) -> shuf (AND (A, B), C)
2626       // (OR  (shuf (A, C), shuf (B, C)) -> shuf (OR  (A, B), C)
2627       // (XOR (shuf (A, C), shuf (B, C)) -> shuf (XOR (A, B), V_0)
2628       if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
2629         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2630                                       N0->getOperand(0), N1->getOperand(0));
2631         AddToWorklist(NewNode.getNode());
2632         return DAG.getVectorShuffle(VT, SDLoc(N), NewNode, ShOp,
2633                                     &SVN0->getMask()[0]);
2634       }
2635
2636       // Don't try to fold this node if it requires introducing a
2637       // build vector of all zeros that might be illegal at this stage.
2638       ShOp = N0->getOperand(0);
2639       if (N->getOpcode() == ISD::XOR && ShOp.getOpcode() != ISD::UNDEF) {
2640         if (!LegalTypes)
2641           ShOp = DAG.getConstant(0, VT);
2642         else
2643           ShOp = SDValue();
2644       }
2645
2646       // (AND (shuf (C, A), shuf (C, B)) -> shuf (C, AND (A, B))
2647       // (OR  (shuf (C, A), shuf (C, B)) -> shuf (C, OR  (A, B))
2648       // (XOR (shuf (C, A), shuf (C, B)) -> shuf (V_0, XOR (A, B))
2649       if (N0->getOperand(0) == N1->getOperand(0) && ShOp.getNode()) {
2650         SDValue NewNode = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
2651                                       N0->getOperand(1), N1->getOperand(1));
2652         AddToWorklist(NewNode.getNode());
2653         return DAG.getVectorShuffle(VT, SDLoc(N), ShOp, NewNode,
2654                                     &SVN0->getMask()[0]);
2655       }
2656     }
2657   }
2658
2659   return SDValue();
2660 }
2661
2662 SDValue DAGCombiner::visitAND(SDNode *N) {
2663   SDValue N0 = N->getOperand(0);
2664   SDValue N1 = N->getOperand(1);
2665   SDValue LL, LR, RL, RR, CC0, CC1;
2666   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
2667   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
2668   EVT VT = N1.getValueType();
2669   unsigned BitWidth = VT.getScalarType().getSizeInBits();
2670
2671   // fold vector ops
2672   if (VT.isVector()) {
2673     SDValue FoldedVOp = SimplifyVBinOp(N);
2674     if (FoldedVOp.getNode()) return FoldedVOp;
2675
2676     // fold (and x, 0) -> 0, vector edition
2677     if (ISD::isBuildVectorAllZeros(N0.getNode()))
2678       // do not return N0, because undef node may exist in N0
2679       return DAG.getConstant(
2680           APInt::getNullValue(
2681               N0.getValueType().getScalarType().getSizeInBits()),
2682           N0.getValueType());
2683     if (ISD::isBuildVectorAllZeros(N1.getNode()))
2684       // do not return N1, because undef node may exist in N1
2685       return DAG.getConstant(
2686           APInt::getNullValue(
2687               N1.getValueType().getScalarType().getSizeInBits()),
2688           N1.getValueType());
2689
2690     // fold (and x, -1) -> x, vector edition
2691     if (ISD::isBuildVectorAllOnes(N0.getNode()))
2692       return N1;
2693     if (ISD::isBuildVectorAllOnes(N1.getNode()))
2694       return N0;
2695   }
2696
2697   // fold (and x, undef) -> 0
2698   if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
2699     return DAG.getConstant(0, VT);
2700   // fold (and c1, c2) -> c1&c2
2701   if (N0C && N1C)
2702     return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
2703   // canonicalize constant to RHS
2704   if (N0C && !N1C)
2705     return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
2706   // fold (and x, -1) -> x
2707   if (N1C && N1C->isAllOnesValue())
2708     return N0;
2709   // if (and x, c) is known to be zero, return 0
2710   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
2711                                    APInt::getAllOnesValue(BitWidth)))
2712     return DAG.getConstant(0, VT);
2713   // reassociate and
2714   SDValue RAND = ReassociateOps(ISD::AND, SDLoc(N), N0, N1);
2715   if (RAND.getNode())
2716     return RAND;
2717   // fold (and (or x, C), D) -> D if (C & D) == D
2718   if (N1C && N0.getOpcode() == ISD::OR)
2719     if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
2720       if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
2721         return N1;
2722   // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
2723   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
2724     SDValue N0Op0 = N0.getOperand(0);
2725     APInt Mask = ~N1C->getAPIntValue();
2726     Mask = Mask.trunc(N0Op0.getValueSizeInBits());
2727     if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
2728       SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
2729                                  N0.getValueType(), N0Op0);
2730
2731       // Replace uses of the AND with uses of the Zero extend node.
2732       CombineTo(N, Zext);
2733
2734       // We actually want to replace all uses of the any_extend with the
2735       // zero_extend, to avoid duplicating things.  This will later cause this
2736       // AND to be folded.
2737       CombineTo(N0.getNode(), Zext);
2738       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2739     }
2740   }
2741   // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
2742   // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
2743   // already be zero by virtue of the width of the base type of the load.
2744   //
2745   // the 'X' node here can either be nothing or an extract_vector_elt to catch
2746   // more cases.
2747   if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
2748        N0.getOperand(0).getOpcode() == ISD::LOAD) ||
2749       N0.getOpcode() == ISD::LOAD) {
2750     LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
2751                                          N0 : N0.getOperand(0) );
2752
2753     // Get the constant (if applicable) the zero'th operand is being ANDed with.
2754     // This can be a pure constant or a vector splat, in which case we treat the
2755     // vector as a scalar and use the splat value.
2756     APInt Constant = APInt::getNullValue(1);
2757     if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
2758       Constant = C->getAPIntValue();
2759     } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
2760       APInt SplatValue, SplatUndef;
2761       unsigned SplatBitSize;
2762       bool HasAnyUndefs;
2763       bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
2764                                              SplatBitSize, HasAnyUndefs);
2765       if (IsSplat) {
2766         // Undef bits can contribute to a possible optimisation if set, so
2767         // set them.
2768         SplatValue |= SplatUndef;
2769
2770         // The splat value may be something like "0x00FFFFFF", which means 0 for
2771         // the first vector value and FF for the rest, repeating. We need a mask
2772         // that will apply equally to all members of the vector, so AND all the
2773         // lanes of the constant together.
2774         EVT VT = Vector->getValueType(0);
2775         unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
2776
2777         // If the splat value has been compressed to a bitlength lower
2778         // than the size of the vector lane, we need to re-expand it to
2779         // the lane size.
2780         if (BitWidth > SplatBitSize)
2781           for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
2782                SplatBitSize < BitWidth;
2783                SplatBitSize = SplatBitSize * 2)
2784             SplatValue |= SplatValue.shl(SplatBitSize);
2785
2786         Constant = APInt::getAllOnesValue(BitWidth);
2787         for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
2788           Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
2789       }
2790     }
2791
2792     // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
2793     // actually legal and isn't going to get expanded, else this is a false
2794     // optimisation.
2795     bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
2796                                                     Load->getMemoryVT());
2797
2798     // Resize the constant to the same size as the original memory access before
2799     // extension. If it is still the AllOnesValue then this AND is completely
2800     // unneeded.
2801     Constant =
2802       Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
2803
2804     bool B;
2805     switch (Load->getExtensionType()) {
2806     default: B = false; break;
2807     case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
2808     case ISD::ZEXTLOAD:
2809     case ISD::NON_EXTLOAD: B = true; break;
2810     }
2811
2812     if (B && Constant.isAllOnesValue()) {
2813       // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
2814       // preserve semantics once we get rid of the AND.
2815       SDValue NewLoad(Load, 0);
2816       if (Load->getExtensionType() == ISD::EXTLOAD) {
2817         NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
2818                               Load->getValueType(0), SDLoc(Load),
2819                               Load->getChain(), Load->getBasePtr(),
2820                               Load->getOffset(), Load->getMemoryVT(),
2821                               Load->getMemOperand());
2822         // Replace uses of the EXTLOAD with the new ZEXTLOAD.
2823         if (Load->getNumValues() == 3) {
2824           // PRE/POST_INC loads have 3 values.
2825           SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
2826                            NewLoad.getValue(2) };
2827           CombineTo(Load, To, 3, true);
2828         } else {
2829           CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
2830         }
2831       }
2832
2833       // Fold the AND away, taking care not to fold to the old load node if we
2834       // replaced it.
2835       CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
2836
2837       return SDValue(N, 0); // Return N so it doesn't get rechecked!
2838     }
2839   }
2840   // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
2841   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
2842     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
2843     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
2844
2845     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
2846         LL.getValueType().isInteger()) {
2847       // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
2848       if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
2849         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2850                                      LR.getValueType(), LL, RL);
2851         AddToWorklist(ORNode.getNode());
2852         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2853       }
2854       // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
2855       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
2856         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(N0),
2857                                       LR.getValueType(), LL, RL);
2858         AddToWorklist(ANDNode.getNode());
2859         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
2860       }
2861       // fold (and (setgt X,  -1), (setgt Y,  -1)) -> (setgt (or X, Y), -1)
2862       if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
2863         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(N0),
2864                                      LR.getValueType(), LL, RL);
2865         AddToWorklist(ORNode.getNode());
2866         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
2867       }
2868     }
2869     // Simplify (and (setne X, 0), (setne X, -1)) -> (setuge (add X, 1), 2)
2870     if (LL == RL && isa<ConstantSDNode>(LR) && isa<ConstantSDNode>(RR) &&
2871         Op0 == Op1 && LL.getValueType().isInteger() &&
2872       Op0 == ISD::SETNE && ((cast<ConstantSDNode>(LR)->isNullValue() &&
2873                                  cast<ConstantSDNode>(RR)->isAllOnesValue()) ||
2874                                 (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
2875                                  cast<ConstantSDNode>(RR)->isNullValue()))) {
2876       SDValue ADDNode = DAG.getNode(ISD::ADD, SDLoc(N0), LL.getValueType(),
2877                                     LL, DAG.getConstant(1, LL.getValueType()));
2878       AddToWorklist(ADDNode.getNode());
2879       return DAG.getSetCC(SDLoc(N), VT, ADDNode,
2880                           DAG.getConstant(2, LL.getValueType()), ISD::SETUGE);
2881     }
2882     // canonicalize equivalent to ll == rl
2883     if (LL == RR && LR == RL) {
2884       Op1 = ISD::getSetCCSwappedOperands(Op1);
2885       std::swap(RL, RR);
2886     }
2887     if (LL == RL && LR == RR) {
2888       bool isInteger = LL.getValueType().isInteger();
2889       ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
2890       if (Result != ISD::SETCC_INVALID &&
2891           (!LegalOperations ||
2892            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
2893             TLI.isOperationLegal(ISD::SETCC,
2894                             getSetCCResultType(N0.getSimpleValueType())))))
2895         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
2896                             LL, LR, Result);
2897     }
2898   }
2899
2900   // Simplify: (and (op x...), (op y...))  -> (op (and x, y))
2901   if (N0.getOpcode() == N1.getOpcode()) {
2902     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
2903     if (Tmp.getNode()) return Tmp;
2904   }
2905
2906   // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
2907   // fold (and (sra)) -> (and (srl)) when possible.
2908   if (!VT.isVector() &&
2909       SimplifyDemandedBits(SDValue(N, 0)))
2910     return SDValue(N, 0);
2911
2912   // fold (zext_inreg (extload x)) -> (zextload x)
2913   if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
2914     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2915     EVT MemVT = LN0->getMemoryVT();
2916     // If we zero all the possible extended bits, then we can turn this into
2917     // a zextload if we are running before legalize or the operation is legal.
2918     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2919     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2920                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2921         ((!LegalOperations && !LN0->isVolatile()) ||
2922          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2923       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2924                                        LN0->getChain(), LN0->getBasePtr(),
2925                                        MemVT, LN0->getMemOperand());
2926       AddToWorklist(N);
2927       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2928       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2929     }
2930   }
2931   // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
2932   if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
2933       N0.hasOneUse()) {
2934     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
2935     EVT MemVT = LN0->getMemoryVT();
2936     // If we zero all the possible extended bits, then we can turn this into
2937     // a zextload if we are running before legalize or the operation is legal.
2938     unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
2939     if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
2940                            BitWidth - MemVT.getScalarType().getSizeInBits())) &&
2941         ((!LegalOperations && !LN0->isVolatile()) ||
2942          TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
2943       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT,
2944                                        LN0->getChain(), LN0->getBasePtr(),
2945                                        MemVT, LN0->getMemOperand());
2946       AddToWorklist(N);
2947       CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
2948       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2949     }
2950   }
2951
2952   // fold (and (load x), 255) -> (zextload x, i8)
2953   // fold (and (extload x, i16), 255) -> (zextload x, i8)
2954   // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
2955   if (N1C && (N0.getOpcode() == ISD::LOAD ||
2956               (N0.getOpcode() == ISD::ANY_EXTEND &&
2957                N0.getOperand(0).getOpcode() == ISD::LOAD))) {
2958     bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
2959     LoadSDNode *LN0 = HasAnyExt
2960       ? cast<LoadSDNode>(N0.getOperand(0))
2961       : cast<LoadSDNode>(N0);
2962     if (LN0->getExtensionType() != ISD::SEXTLOAD &&
2963         LN0->isUnindexed() && N0.hasOneUse() && SDValue(LN0, 0).hasOneUse()) {
2964       uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
2965       if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
2966         EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
2967         EVT LoadedVT = LN0->getMemoryVT();
2968
2969         if (ExtVT == LoadedVT &&
2970             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2971           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
2972
2973           SDValue NewLoad =
2974             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
2975                            LN0->getChain(), LN0->getBasePtr(), ExtVT,
2976                            LN0->getMemOperand());
2977           AddToWorklist(N);
2978           CombineTo(LN0, NewLoad, NewLoad.getValue(1));
2979           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
2980         }
2981
2982         // Do not change the width of a volatile load.
2983         // Do not generate loads of non-round integer types since these can
2984         // be expensive (and would be wrong if the type is not byte sized).
2985         if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
2986             (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
2987           EVT PtrType = LN0->getOperand(1).getValueType();
2988
2989           unsigned Alignment = LN0->getAlignment();
2990           SDValue NewPtr = LN0->getBasePtr();
2991
2992           // For big endian targets, we need to add an offset to the pointer
2993           // to load the correct bytes.  For little endian systems, we merely
2994           // need to read fewer bytes from the same pointer.
2995           if (TLI.isBigEndian()) {
2996             unsigned LVTStoreBytes = LoadedVT.getStoreSize();
2997             unsigned EVTStoreBytes = ExtVT.getStoreSize();
2998             unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
2999             NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0), PtrType,
3000                                  NewPtr, DAG.getConstant(PtrOff, PtrType));
3001             Alignment = MinAlign(Alignment, PtrOff);
3002           }
3003
3004           AddToWorklist(NewPtr.getNode());
3005
3006           EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
3007           SDValue Load =
3008             DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), LoadResultTy,
3009                            LN0->getChain(), NewPtr,
3010                            LN0->getPointerInfo(),
3011                            ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
3012                            LN0->isInvariant(), Alignment, LN0->getAAInfo());
3013           AddToWorklist(N);
3014           CombineTo(LN0, Load, Load.getValue(1));
3015           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
3016         }
3017       }
3018     }
3019   }
3020
3021   if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
3022       VT.getSizeInBits() <= 64) {
3023     if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
3024       APInt ADDC = ADDI->getAPIntValue();
3025       if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3026         // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
3027         // immediate for an add, but it is legal if its top c2 bits are set,
3028         // transform the ADD so the immediate doesn't need to be materialized
3029         // in a register.
3030         if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
3031           APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
3032                                              SRLI->getZExtValue());
3033           if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
3034             ADDC |= Mask;
3035             if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
3036               SDValue NewAdd =
3037                 DAG.getNode(ISD::ADD, SDLoc(N0), VT,
3038                             N0.getOperand(0), DAG.getConstant(ADDC, VT));
3039               CombineTo(N0.getNode(), NewAdd);
3040               return SDValue(N, 0); // Return N so it doesn't get rechecked!
3041             }
3042           }
3043         }
3044       }
3045     }
3046   }
3047
3048   // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
3049   if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
3050     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
3051                                        N0.getOperand(1), false);
3052     if (BSwap.getNode())
3053       return BSwap;
3054   }
3055
3056   return SDValue();
3057 }
3058
3059 /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
3060 SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
3061                                         bool DemandHighBits) {
3062   if (!LegalOperations)
3063     return SDValue();
3064
3065   EVT VT = N->getValueType(0);
3066   if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
3067     return SDValue();
3068   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3069     return SDValue();
3070
3071   // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
3072   bool LookPassAnd0 = false;
3073   bool LookPassAnd1 = false;
3074   if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
3075       std::swap(N0, N1);
3076   if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
3077       std::swap(N0, N1);
3078   if (N0.getOpcode() == ISD::AND) {
3079     if (!N0.getNode()->hasOneUse())
3080       return SDValue();
3081     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3082     if (!N01C || N01C->getZExtValue() != 0xFF00)
3083       return SDValue();
3084     N0 = N0.getOperand(0);
3085     LookPassAnd0 = true;
3086   }
3087
3088   if (N1.getOpcode() == ISD::AND) {
3089     if (!N1.getNode()->hasOneUse())
3090       return SDValue();
3091     ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3092     if (!N11C || N11C->getZExtValue() != 0xFF)
3093       return SDValue();
3094     N1 = N1.getOperand(0);
3095     LookPassAnd1 = true;
3096   }
3097
3098   if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
3099     std::swap(N0, N1);
3100   if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
3101     return SDValue();
3102   if (!N0.getNode()->hasOneUse() ||
3103       !N1.getNode()->hasOneUse())
3104     return SDValue();
3105
3106   ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3107   ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
3108   if (!N01C || !N11C)
3109     return SDValue();
3110   if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
3111     return SDValue();
3112
3113   // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
3114   SDValue N00 = N0->getOperand(0);
3115   if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
3116     if (!N00.getNode()->hasOneUse())
3117       return SDValue();
3118     ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
3119     if (!N001C || N001C->getZExtValue() != 0xFF)
3120       return SDValue();
3121     N00 = N00.getOperand(0);
3122     LookPassAnd0 = true;
3123   }
3124
3125   SDValue N10 = N1->getOperand(0);
3126   if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
3127     if (!N10.getNode()->hasOneUse())
3128       return SDValue();
3129     ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
3130     if (!N101C || N101C->getZExtValue() != 0xFF00)
3131       return SDValue();
3132     N10 = N10.getOperand(0);
3133     LookPassAnd1 = true;
3134   }
3135
3136   if (N00 != N10)
3137     return SDValue();
3138
3139   // Make sure everything beyond the low halfword gets set to zero since the SRL
3140   // 16 will clear the top bits.
3141   unsigned OpSizeInBits = VT.getSizeInBits();
3142   if (DemandHighBits && OpSizeInBits > 16) {
3143     // If the left-shift isn't masked out then the only way this is a bswap is
3144     // if all bits beyond the low 8 are 0. In that case the entire pattern
3145     // reduces to a left shift anyway: leave it for other parts of the combiner.
3146     if (!LookPassAnd0)
3147       return SDValue();
3148
3149     // However, if the right shift isn't masked out then it might be because
3150     // it's not needed. See if we can spot that too.
3151     if (!LookPassAnd1 &&
3152         !DAG.MaskedValueIsZero(
3153             N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
3154       return SDValue();
3155   }
3156
3157   SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
3158   if (OpSizeInBits > 16)
3159     Res = DAG.getNode(ISD::SRL, SDLoc(N), VT, Res,
3160                       DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
3161   return Res;
3162 }
3163
3164 /// Return true if the specified node is an element that makes up a 32-bit
3165 /// packed halfword byteswap.
3166 /// ((x & 0x000000ff) << 8) |
3167 /// ((x & 0x0000ff00) >> 8) |
3168 /// ((x & 0x00ff0000) << 8) |
3169 /// ((x & 0xff000000) >> 8)
3170 static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
3171   if (!N.getNode()->hasOneUse())
3172     return false;
3173
3174   unsigned Opc = N.getOpcode();
3175   if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
3176     return false;
3177
3178   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3179   if (!N1C)
3180     return false;
3181
3182   unsigned Num;
3183   switch (N1C->getZExtValue()) {
3184   default:
3185     return false;
3186   case 0xFF:       Num = 0; break;
3187   case 0xFF00:     Num = 1; break;
3188   case 0xFF0000:   Num = 2; break;
3189   case 0xFF000000: Num = 3; break;
3190   }
3191
3192   // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
3193   SDValue N0 = N.getOperand(0);
3194   if (Opc == ISD::AND) {
3195     if (Num == 0 || Num == 2) {
3196       // (x >> 8) & 0xff
3197       // (x >> 8) & 0xff0000
3198       if (N0.getOpcode() != ISD::SRL)
3199         return false;
3200       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3201       if (!C || C->getZExtValue() != 8)
3202         return false;
3203     } else {
3204       // (x << 8) & 0xff00
3205       // (x << 8) & 0xff000000
3206       if (N0.getOpcode() != ISD::SHL)
3207         return false;
3208       ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3209       if (!C || C->getZExtValue() != 8)
3210         return false;
3211     }
3212   } else if (Opc == ISD::SHL) {
3213     // (x & 0xff) << 8
3214     // (x & 0xff0000) << 8
3215     if (Num != 0 && Num != 2)
3216       return false;
3217     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3218     if (!C || C->getZExtValue() != 8)
3219       return false;
3220   } else { // Opc == ISD::SRL
3221     // (x & 0xff00) >> 8
3222     // (x & 0xff000000) >> 8
3223     if (Num != 1 && Num != 3)
3224       return false;
3225     ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
3226     if (!C || C->getZExtValue() != 8)
3227       return false;
3228   }
3229
3230   if (Parts[Num])
3231     return false;
3232
3233   Parts[Num] = N0.getOperand(0).getNode();
3234   return true;
3235 }
3236
3237 /// Match a 32-bit packed halfword bswap. That is
3238 /// ((x & 0x000000ff) << 8) |
3239 /// ((x & 0x0000ff00) >> 8) |
3240 /// ((x & 0x00ff0000) << 8) |
3241 /// ((x & 0xff000000) >> 8)
3242 /// => (rotl (bswap x), 16)
3243 SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
3244   if (!LegalOperations)
3245     return SDValue();
3246
3247   EVT VT = N->getValueType(0);
3248   if (VT != MVT::i32)
3249     return SDValue();
3250   if (!TLI.isOperationLegal(ISD::BSWAP, VT))
3251     return SDValue();
3252
3253   // Look for either
3254   // (or (or (and), (and)), (or (and), (and)))
3255   // (or (or (or (and), (and)), (and)), (and))
3256   if (N0.getOpcode() != ISD::OR)
3257     return SDValue();
3258   SDValue N00 = N0.getOperand(0);
3259   SDValue N01 = N0.getOperand(1);
3260   SDNode *Parts[4] = {};
3261
3262   if (N1.getOpcode() == ISD::OR &&
3263       N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
3264     // (or (or (and), (and)), (or (and), (and)))
3265     SDValue N000 = N00.getOperand(0);
3266     if (!isBSwapHWordElement(N000, Parts))
3267       return SDValue();
3268
3269     SDValue N001 = N00.getOperand(1);
3270     if (!isBSwapHWordElement(N001, Parts))
3271       return SDValue();
3272     SDValue N010 = N01.getOperand(0);
3273     if (!isBSwapHWordElement(N010, Parts))
3274       return SDValue();
3275     SDValue N011 = N01.getOperand(1);
3276     if (!isBSwapHWordElement(N011, Parts))
3277       return SDValue();
3278   } else {
3279     // (or (or (or (and), (and)), (and)), (and))
3280     if (!isBSwapHWordElement(N1, Parts))
3281       return SDValue();
3282     if (!isBSwapHWordElement(N01, Parts))
3283       return SDValue();
3284     if (N00.getOpcode() != ISD::OR)
3285       return SDValue();
3286     SDValue N000 = N00.getOperand(0);
3287     if (!isBSwapHWordElement(N000, Parts))
3288       return SDValue();
3289     SDValue N001 = N00.getOperand(1);
3290     if (!isBSwapHWordElement(N001, Parts))
3291       return SDValue();
3292   }
3293
3294   // Make sure the parts are all coming from the same node.
3295   if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
3296     return SDValue();
3297
3298   SDValue BSwap = DAG.getNode(ISD::BSWAP, SDLoc(N), VT,
3299                               SDValue(Parts[0],0));
3300
3301   // Result of the bswap should be rotated by 16. If it's not legal, then
3302   // do  (x << 16) | (x >> 16).
3303   SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
3304   if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
3305     return DAG.getNode(ISD::ROTL, SDLoc(N), VT, BSwap, ShAmt);
3306   if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
3307     return DAG.getNode(ISD::ROTR, SDLoc(N), VT, BSwap, ShAmt);
3308   return DAG.getNode(ISD::OR, SDLoc(N), VT,
3309                      DAG.getNode(ISD::SHL, SDLoc(N), VT, BSwap, ShAmt),
3310                      DAG.getNode(ISD::SRL, SDLoc(N), VT, BSwap, ShAmt));
3311 }
3312
3313 SDValue DAGCombiner::visitOR(SDNode *N) {
3314   SDValue N0 = N->getOperand(0);
3315   SDValue N1 = N->getOperand(1);
3316   SDValue LL, LR, RL, RR, CC0, CC1;
3317   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3318   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3319   EVT VT = N1.getValueType();
3320
3321   // fold vector ops
3322   if (VT.isVector()) {
3323     SDValue FoldedVOp = SimplifyVBinOp(N);
3324     if (FoldedVOp.getNode()) return FoldedVOp;
3325
3326     // fold (or x, 0) -> x, vector edition
3327     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3328       return N1;
3329     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3330       return N0;
3331
3332     // fold (or x, -1) -> -1, vector edition
3333     if (ISD::isBuildVectorAllOnes(N0.getNode()))
3334       // do not return N0, because undef node may exist in N0
3335       return DAG.getConstant(
3336           APInt::getAllOnesValue(
3337               N0.getValueType().getScalarType().getSizeInBits()),
3338           N0.getValueType());
3339     if (ISD::isBuildVectorAllOnes(N1.getNode()))
3340       // do not return N1, because undef node may exist in N1
3341       return DAG.getConstant(
3342           APInt::getAllOnesValue(
3343               N1.getValueType().getScalarType().getSizeInBits()),
3344           N1.getValueType());
3345
3346     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask1)
3347     // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf B, A, Mask2)
3348     // Do this only if the resulting shuffle is legal.
3349     if (isa<ShuffleVectorSDNode>(N0) &&
3350         isa<ShuffleVectorSDNode>(N1) &&
3351         // Avoid folding a node with illegal type.
3352         TLI.isTypeLegal(VT) &&
3353         N0->getOperand(1) == N1->getOperand(1) &&
3354         ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode())) {
3355       bool CanFold = true;
3356       unsigned NumElts = VT.getVectorNumElements();
3357       const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
3358       const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
3359       // We construct two shuffle masks:
3360       // - Mask1 is a shuffle mask for a shuffle with N0 as the first operand
3361       // and N1 as the second operand.
3362       // - Mask2 is a shuffle mask for a shuffle with N1 as the first operand
3363       // and N0 as the second operand.
3364       // We do this because OR is commutable and therefore there might be
3365       // two ways to fold this node into a shuffle.
3366       SmallVector<int,4> Mask1;
3367       SmallVector<int,4> Mask2;
3368
3369       for (unsigned i = 0; i != NumElts && CanFold; ++i) {
3370         int M0 = SV0->getMaskElt(i);
3371         int M1 = SV1->getMaskElt(i);
3372
3373         // Both shuffle indexes are undef. Propagate Undef.
3374         if (M0 < 0 && M1 < 0) {
3375           Mask1.push_back(M0);
3376           Mask2.push_back(M0);
3377           continue;
3378         }
3379
3380         if (M0 < 0 || M1 < 0 ||
3381             (M0 < (int)NumElts && M1 < (int)NumElts) ||
3382             (M0 >= (int)NumElts && M1 >= (int)NumElts)) {
3383           CanFold = false;
3384           break;
3385         }
3386
3387         Mask1.push_back(M0 < (int)NumElts ? M0 : M1 + NumElts);
3388         Mask2.push_back(M1 < (int)NumElts ? M1 : M0 + NumElts);
3389       }
3390
3391       if (CanFold) {
3392         // Fold this sequence only if the resulting shuffle is 'legal'.
3393         if (TLI.isShuffleMaskLegal(Mask1, VT))
3394           return DAG.getVectorShuffle(VT, SDLoc(N), N0->getOperand(0),
3395                                       N1->getOperand(0), &Mask1[0]);
3396         if (TLI.isShuffleMaskLegal(Mask2, VT))
3397           return DAG.getVectorShuffle(VT, SDLoc(N), N1->getOperand(0),
3398                                       N0->getOperand(0), &Mask2[0]);
3399       }
3400     }
3401   }
3402
3403   // fold (or x, undef) -> -1
3404   if (!LegalOperations &&
3405       (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
3406     EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
3407     return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
3408   }
3409   // fold (or c1, c2) -> c1|c2
3410   if (N0C && N1C)
3411     return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
3412   // canonicalize constant to RHS
3413   if (N0C && !N1C)
3414     return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
3415   // fold (or x, 0) -> x
3416   if (N1C && N1C->isNullValue())
3417     return N0;
3418   // fold (or x, -1) -> -1
3419   if (N1C && N1C->isAllOnesValue())
3420     return N1;
3421   // fold (or x, c) -> c iff (x & ~c) == 0
3422   if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
3423     return N1;
3424
3425   // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
3426   SDValue BSwap = MatchBSwapHWord(N, N0, N1);
3427   if (BSwap.getNode())
3428     return BSwap;
3429   BSwap = MatchBSwapHWordLow(N, N0, N1);
3430   if (BSwap.getNode())
3431     return BSwap;
3432
3433   // reassociate or
3434   SDValue ROR = ReassociateOps(ISD::OR, SDLoc(N), N0, N1);
3435   if (ROR.getNode())
3436     return ROR;
3437   // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
3438   // iff (c1 & c2) == 0.
3439   if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3440              isa<ConstantSDNode>(N0.getOperand(1))) {
3441     ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
3442     if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0) {
3443       SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1);
3444       if (!COR.getNode())
3445         return SDValue();
3446       return DAG.getNode(ISD::AND, SDLoc(N), VT,
3447                          DAG.getNode(ISD::OR, SDLoc(N0), VT,
3448                                      N0.getOperand(0), N1), COR);
3449     }
3450   }
3451   // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
3452   if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
3453     ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
3454     ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
3455
3456     if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
3457         LL.getValueType().isInteger()) {
3458       // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
3459       // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
3460       if (cast<ConstantSDNode>(LR)->isNullValue() &&
3461           (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
3462         SDValue ORNode = DAG.getNode(ISD::OR, SDLoc(LR),
3463                                      LR.getValueType(), LL, RL);
3464         AddToWorklist(ORNode.getNode());
3465         return DAG.getSetCC(SDLoc(N), VT, ORNode, LR, Op1);
3466       }
3467       // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
3468       // fold (or (setgt X, -1), (setgt Y  -1)) -> (setgt (and X, Y), -1)
3469       if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
3470           (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
3471         SDValue ANDNode = DAG.getNode(ISD::AND, SDLoc(LR),
3472                                       LR.getValueType(), LL, RL);
3473         AddToWorklist(ANDNode.getNode());
3474         return DAG.getSetCC(SDLoc(N), VT, ANDNode, LR, Op1);
3475       }
3476     }
3477     // canonicalize equivalent to ll == rl
3478     if (LL == RR && LR == RL) {
3479       Op1 = ISD::getSetCCSwappedOperands(Op1);
3480       std::swap(RL, RR);
3481     }
3482     if (LL == RL && LR == RR) {
3483       bool isInteger = LL.getValueType().isInteger();
3484       ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
3485       if (Result != ISD::SETCC_INVALID &&
3486           (!LegalOperations ||
3487            (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
3488             TLI.isOperationLegal(ISD::SETCC,
3489               getSetCCResultType(N0.getValueType())))))
3490         return DAG.getSetCC(SDLoc(N), N0.getValueType(),
3491                             LL, LR, Result);
3492     }
3493   }
3494
3495   // Simplify: (or (op x...), (op y...))  -> (op (or x, y))
3496   if (N0.getOpcode() == N1.getOpcode()) {
3497     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3498     if (Tmp.getNode()) return Tmp;
3499   }
3500
3501   // (or (and X, C1), (and Y, C2))  -> (and (or X, Y), C3) if possible.
3502   if (N0.getOpcode() == ISD::AND &&
3503       N1.getOpcode() == ISD::AND &&
3504       N0.getOperand(1).getOpcode() == ISD::Constant &&
3505       N1.getOperand(1).getOpcode() == ISD::Constant &&
3506       // Don't increase # computations.
3507       (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
3508     // We can only do this xform if we know that bits from X that are set in C2
3509     // but not in C1 are already zero.  Likewise for Y.
3510     const APInt &LHSMask =
3511       cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
3512     const APInt &RHSMask =
3513       cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
3514
3515     if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
3516         DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
3517       SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
3518                               N0.getOperand(0), N1.getOperand(0));
3519       return DAG.getNode(ISD::AND, SDLoc(N), VT, X,
3520                          DAG.getConstant(LHSMask | RHSMask, VT));
3521     }
3522   }
3523
3524   // See if this is some rotate idiom.
3525   if (SDNode *Rot = MatchRotate(N0, N1, SDLoc(N)))
3526     return SDValue(Rot, 0);
3527
3528   // Simplify the operands using demanded-bits information.
3529   if (!VT.isVector() &&
3530       SimplifyDemandedBits(SDValue(N, 0)))
3531     return SDValue(N, 0);
3532
3533   return SDValue();
3534 }
3535
3536 /// Match "(X shl/srl V1) & V2" where V2 may not be present.
3537 static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
3538   if (Op.getOpcode() == ISD::AND) {
3539     if (isa<ConstantSDNode>(Op.getOperand(1))) {
3540       Mask = Op.getOperand(1);
3541       Op = Op.getOperand(0);
3542     } else {
3543       return false;
3544     }
3545   }
3546
3547   if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
3548     Shift = Op;
3549     return true;
3550   }
3551
3552   return false;
3553 }
3554
3555 // Return true if we can prove that, whenever Neg and Pos are both in the
3556 // range [0, OpSize), Neg == (Pos == 0 ? 0 : OpSize - Pos).  This means that
3557 // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
3558 //
3559 //     (or (shift1 X, Neg), (shift2 X, Pos))
3560 //
3561 // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
3562 // in direction shift1 by Neg.  The range [0, OpSize) means that we only need
3563 // to consider shift amounts with defined behavior.
3564 static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned OpSize) {
3565   // If OpSize is a power of 2 then:
3566   //
3567   //  (a) (Pos == 0 ? 0 : OpSize - Pos) == (OpSize - Pos) & (OpSize - 1)
3568   //  (b) Neg == Neg & (OpSize - 1) whenever Neg is in [0, OpSize).
3569   //
3570   // So if OpSize is a power of 2 and Neg is (and Neg', OpSize-1), we check
3571   // for the stronger condition:
3572   //
3573   //     Neg & (OpSize - 1) == (OpSize - Pos) & (OpSize - 1)    [A]
3574   //
3575   // for all Neg and Pos.  Since Neg & (OpSize - 1) == Neg' & (OpSize - 1)
3576   // we can just replace Neg with Neg' for the rest of the function.
3577   //
3578   // In other cases we check for the even stronger condition:
3579   //
3580   //     Neg == OpSize - Pos                                    [B]
3581   //
3582   // for all Neg and Pos.  Note that the (or ...) then invokes undefined
3583   // behavior if Pos == 0 (and consequently Neg == OpSize).
3584   //
3585   // We could actually use [A] whenever OpSize is a power of 2, but the
3586   // only extra cases that it would match are those uninteresting ones
3587   // where Neg and Pos are never in range at the same time.  E.g. for
3588   // OpSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
3589   // as well as (sub 32, Pos), but:
3590   //
3591   //     (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
3592   //
3593   // always invokes undefined behavior for 32-bit X.
3594   //
3595   // Below, Mask == OpSize - 1 when using [A] and is all-ones otherwise.
3596   unsigned MaskLoBits = 0;
3597   if (Neg.getOpcode() == ISD::AND &&
3598       isPowerOf2_64(OpSize) &&
3599       Neg.getOperand(1).getOpcode() == ISD::Constant &&
3600       cast<ConstantSDNode>(Neg.getOperand(1))->getAPIntValue() == OpSize - 1) {
3601     Neg = Neg.getOperand(0);
3602     MaskLoBits = Log2_64(OpSize);
3603   }
3604
3605   // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
3606   if (Neg.getOpcode() != ISD::SUB)
3607     return 0;
3608   ConstantSDNode *NegC = dyn_cast<ConstantSDNode>(Neg.getOperand(0));
3609   if (!NegC)
3610     return 0;
3611   SDValue NegOp1 = Neg.getOperand(1);
3612
3613   // On the RHS of [A], if Pos is Pos' & (OpSize - 1), just replace Pos with
3614   // Pos'.  The truncation is redundant for the purpose of the equality.
3615   if (MaskLoBits &&
3616       Pos.getOpcode() == ISD::AND &&
3617       Pos.getOperand(1).getOpcode() == ISD::Constant &&
3618       cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() == OpSize - 1)
3619     Pos = Pos.getOperand(0);
3620
3621   // The condition we need is now:
3622   //
3623   //     (NegC - NegOp1) & Mask == (OpSize - Pos) & Mask
3624   //
3625   // If NegOp1 == Pos then we need:
3626   //
3627   //              OpSize & Mask == NegC & Mask
3628   //
3629   // (because "x & Mask" is a truncation and distributes through subtraction).
3630   APInt Width;
3631   if (Pos == NegOp1)
3632     Width = NegC->getAPIntValue();
3633   // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
3634   // Then the condition we want to prove becomes:
3635   //
3636   //     (NegC - NegOp1) & Mask == (OpSize - (NegOp1 + PosC)) & Mask
3637   //
3638   // which, again because "x & Mask" is a truncation, becomes:
3639   //
3640   //                NegC & Mask == (OpSize - PosC) & Mask
3641   //              OpSize & Mask == (NegC + PosC) & Mask
3642   else if (Pos.getOpcode() == ISD::ADD &&
3643            Pos.getOperand(0) == NegOp1 &&
3644            Pos.getOperand(1).getOpcode() == ISD::Constant)
3645     Width = (cast<ConstantSDNode>(Pos.getOperand(1))->getAPIntValue() +
3646              NegC->getAPIntValue());
3647   else
3648     return false;
3649
3650   // Now we just need to check that OpSize & Mask == Width & Mask.
3651   if (MaskLoBits)
3652     // Opsize & Mask is 0 since Mask is Opsize - 1.
3653     return Width.getLoBits(MaskLoBits) == 0;
3654   return Width == OpSize;
3655 }
3656
3657 // A subroutine of MatchRotate used once we have found an OR of two opposite
3658 // shifts of Shifted.  If Neg == <operand size> - Pos then the OR reduces
3659 // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
3660 // former being preferred if supported.  InnerPos and InnerNeg are Pos and
3661 // Neg with outer conversions stripped away.
3662 SDNode *DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
3663                                        SDValue Neg, SDValue InnerPos,
3664                                        SDValue InnerNeg, unsigned PosOpcode,
3665                                        unsigned NegOpcode, SDLoc DL) {
3666   // fold (or (shl x, (*ext y)),
3667   //          (srl x, (*ext (sub 32, y)))) ->
3668   //   (rotl x, y) or (rotr x, (sub 32, y))
3669   //
3670   // fold (or (shl x, (*ext (sub 32, y))),
3671   //          (srl x, (*ext y))) ->
3672   //   (rotr x, y) or (rotl x, (sub 32, y))
3673   EVT VT = Shifted.getValueType();
3674   if (matchRotateSub(InnerPos, InnerNeg, VT.getSizeInBits())) {
3675     bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
3676     return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
3677                        HasPos ? Pos : Neg).getNode();
3678   }
3679
3680   return nullptr;
3681 }
3682
3683 // MatchRotate - Handle an 'or' of two operands.  If this is one of the many
3684 // idioms for rotate, and if the target supports rotation instructions, generate
3685 // a rot[lr].
3686 SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, SDLoc DL) {
3687   // Must be a legal type.  Expanded 'n promoted things won't work with rotates.
3688   EVT VT = LHS.getValueType();
3689   if (!TLI.isTypeLegal(VT)) return nullptr;
3690
3691   // The target must have at least one rotate flavor.
3692   bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
3693   bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
3694   if (!HasROTL && !HasROTR) return nullptr;
3695
3696   // Match "(X shl/srl V1) & V2" where V2 may not be present.
3697   SDValue LHSShift;   // The shift.
3698   SDValue LHSMask;    // AND value if any.
3699   if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
3700     return nullptr; // Not part of a rotate.
3701
3702   SDValue RHSShift;   // The shift.
3703   SDValue RHSMask;    // AND value if any.
3704   if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
3705     return nullptr; // Not part of a rotate.
3706
3707   if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
3708     return nullptr;   // Not shifting the same value.
3709
3710   if (LHSShift.getOpcode() == RHSShift.getOpcode())
3711     return nullptr;   // Shifts must disagree.
3712
3713   // Canonicalize shl to left side in a shl/srl pair.
3714   if (RHSShift.getOpcode() == ISD::SHL) {
3715     std::swap(LHS, RHS);
3716     std::swap(LHSShift, RHSShift);
3717     std::swap(LHSMask , RHSMask );
3718   }
3719
3720   unsigned OpSizeInBits = VT.getSizeInBits();
3721   SDValue LHSShiftArg = LHSShift.getOperand(0);
3722   SDValue LHSShiftAmt = LHSShift.getOperand(1);
3723   SDValue RHSShiftArg = RHSShift.getOperand(0);
3724   SDValue RHSShiftAmt = RHSShift.getOperand(1);
3725
3726   // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
3727   // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
3728   if (LHSShiftAmt.getOpcode() == ISD::Constant &&
3729       RHSShiftAmt.getOpcode() == ISD::Constant) {
3730     uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
3731     uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
3732     if ((LShVal + RShVal) != OpSizeInBits)
3733       return nullptr;
3734
3735     SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
3736                               LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
3737
3738     // If there is an AND of either shifted operand, apply it to the result.
3739     if (LHSMask.getNode() || RHSMask.getNode()) {
3740       APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
3741
3742       if (LHSMask.getNode()) {
3743         APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
3744         Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
3745       }
3746       if (RHSMask.getNode()) {
3747         APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
3748         Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
3749       }
3750
3751       Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
3752     }
3753
3754     return Rot.getNode();
3755   }
3756
3757   // If there is a mask here, and we have a variable shift, we can't be sure
3758   // that we're masking out the right stuff.
3759   if (LHSMask.getNode() || RHSMask.getNode())
3760     return nullptr;
3761
3762   // If the shift amount is sign/zext/any-extended just peel it off.
3763   SDValue LExtOp0 = LHSShiftAmt;
3764   SDValue RExtOp0 = RHSShiftAmt;
3765   if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3766        LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3767        LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3768        LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
3769       (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
3770        RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
3771        RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
3772        RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
3773     LExtOp0 = LHSShiftAmt.getOperand(0);
3774     RExtOp0 = RHSShiftAmt.getOperand(0);
3775   }
3776
3777   SDNode *TryL = MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt,
3778                                    LExtOp0, RExtOp0, ISD::ROTL, ISD::ROTR, DL);
3779   if (TryL)
3780     return TryL;
3781
3782   SDNode *TryR = MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
3783                                    RExtOp0, LExtOp0, ISD::ROTR, ISD::ROTL, DL);
3784   if (TryR)
3785     return TryR;
3786
3787   return nullptr;
3788 }
3789
3790 SDValue DAGCombiner::visitXOR(SDNode *N) {
3791   SDValue N0 = N->getOperand(0);
3792   SDValue N1 = N->getOperand(1);
3793   SDValue LHS, RHS, CC;
3794   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
3795   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
3796   EVT VT = N0.getValueType();
3797
3798   // fold vector ops
3799   if (VT.isVector()) {
3800     SDValue FoldedVOp = SimplifyVBinOp(N);
3801     if (FoldedVOp.getNode()) return FoldedVOp;
3802
3803     // fold (xor x, 0) -> x, vector edition
3804     if (ISD::isBuildVectorAllZeros(N0.getNode()))
3805       return N1;
3806     if (ISD::isBuildVectorAllZeros(N1.getNode()))
3807       return N0;
3808   }
3809
3810   // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
3811   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
3812     return DAG.getConstant(0, VT);
3813   // fold (xor x, undef) -> undef
3814   if (N0.getOpcode() == ISD::UNDEF)
3815     return N0;
3816   if (N1.getOpcode() == ISD::UNDEF)
3817     return N1;
3818   // fold (xor c1, c2) -> c1^c2
3819   if (N0C && N1C)
3820     return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
3821   // canonicalize constant to RHS
3822   if (N0C && !N1C)
3823     return DAG.getNode(ISD::XOR, SDLoc(N), VT, N1, N0);
3824   // fold (xor x, 0) -> x
3825   if (N1C && N1C->isNullValue())
3826     return N0;
3827   // reassociate xor
3828   SDValue RXOR = ReassociateOps(ISD::XOR, SDLoc(N), N0, N1);
3829   if (RXOR.getNode())
3830     return RXOR;
3831
3832   // fold !(x cc y) -> (x !cc y)
3833   if (TLI.isConstTrueVal(N1.getNode()) && isSetCCEquivalent(N0, LHS, RHS, CC)) {
3834     bool isInt = LHS.getValueType().isInteger();
3835     ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
3836                                                isInt);
3837
3838     if (!LegalOperations ||
3839         TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
3840       switch (N0.getOpcode()) {
3841       default:
3842         llvm_unreachable("Unhandled SetCC Equivalent!");
3843       case ISD::SETCC:
3844         return DAG.getSetCC(SDLoc(N), VT, LHS, RHS, NotCC);
3845       case ISD::SELECT_CC:
3846         return DAG.getSelectCC(SDLoc(N), LHS, RHS, N0.getOperand(2),
3847                                N0.getOperand(3), NotCC);
3848       }
3849     }
3850   }
3851
3852   // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
3853   if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
3854       N0.getNode()->hasOneUse() &&
3855       isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
3856     SDValue V = N0.getOperand(0);
3857     V = DAG.getNode(ISD::XOR, SDLoc(N0), V.getValueType(), V,
3858                     DAG.getConstant(1, V.getValueType()));
3859     AddToWorklist(V.getNode());
3860     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, V);
3861   }
3862
3863   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
3864   if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
3865       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3866     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3867     if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
3868       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3869       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3870       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3871       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3872       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3873     }
3874   }
3875   // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
3876   if (N1C && N1C->isAllOnesValue() &&
3877       (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
3878     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
3879     if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
3880       unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
3881       LHS = DAG.getNode(ISD::XOR, SDLoc(LHS), VT, LHS, N1); // LHS = ~LHS
3882       RHS = DAG.getNode(ISD::XOR, SDLoc(RHS), VT, RHS, N1); // RHS = ~RHS
3883       AddToWorklist(LHS.getNode()); AddToWorklist(RHS.getNode());
3884       return DAG.getNode(NewOpcode, SDLoc(N), VT, LHS, RHS);
3885     }
3886   }
3887   // fold (xor (and x, y), y) -> (and (not x), y)
3888   if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
3889       N0->getOperand(1) == N1) {
3890     SDValue X = N0->getOperand(0);
3891     SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
3892     AddToWorklist(NotX.getNode());
3893     return DAG.getNode(ISD::AND, SDLoc(N), VT, NotX, N1);
3894   }
3895   // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
3896   if (N1C && N0.getOpcode() == ISD::XOR) {
3897     ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
3898     ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
3899     if (N00C)
3900       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(1),
3901                          DAG.getConstant(N1C->getAPIntValue() ^
3902                                          N00C->getAPIntValue(), VT));
3903     if (N01C)
3904       return DAG.getNode(ISD::XOR, SDLoc(N), VT, N0.getOperand(0),
3905                          DAG.getConstant(N1C->getAPIntValue() ^
3906                                          N01C->getAPIntValue(), VT));
3907   }
3908   // fold (xor x, x) -> 0
3909   if (N0 == N1)
3910     return tryFoldToZero(SDLoc(N), TLI, VT, DAG, LegalOperations, LegalTypes);
3911
3912   // Simplify: xor (op x...), (op y...)  -> (op (xor x, y))
3913   if (N0.getOpcode() == N1.getOpcode()) {
3914     SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
3915     if (Tmp.getNode()) return Tmp;
3916   }
3917
3918   // Simplify the expression using non-local knowledge.
3919   if (!VT.isVector() &&
3920       SimplifyDemandedBits(SDValue(N, 0)))
3921     return SDValue(N, 0);
3922
3923   return SDValue();
3924 }
3925
3926 /// Handle transforms common to the three shifts, when the shift amount is a
3927 /// constant.
3928 SDValue DAGCombiner::visitShiftByConstant(SDNode *N, ConstantSDNode *Amt) {
3929   // We can't and shouldn't fold opaque constants.
3930   if (Amt->isOpaque())
3931     return SDValue();
3932
3933   SDNode *LHS = N->getOperand(0).getNode();
3934   if (!LHS->hasOneUse()) return SDValue();
3935
3936   // We want to pull some binops through shifts, so that we have (and (shift))
3937   // instead of (shift (and)), likewise for add, or, xor, etc.  This sort of
3938   // thing happens with address calculations, so it's important to canonicalize
3939   // it.
3940   bool HighBitSet = false;  // Can we transform this if the high bit is set?
3941
3942   switch (LHS->getOpcode()) {
3943   default: return SDValue();
3944   case ISD::OR:
3945   case ISD::XOR:
3946     HighBitSet = false; // We can only transform sra if the high bit is clear.
3947     break;
3948   case ISD::AND:
3949     HighBitSet = true;  // We can only transform sra if the high bit is set.
3950     break;
3951   case ISD::ADD:
3952     if (N->getOpcode() != ISD::SHL)
3953       return SDValue(); // only shl(add) not sr[al](add).
3954     HighBitSet = false; // We can only transform sra if the high bit is clear.
3955     break;
3956   }
3957
3958   // We require the RHS of the binop to be a constant and not opaque as well.
3959   ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
3960   if (!BinOpCst || BinOpCst->isOpaque()) return SDValue();
3961
3962   // FIXME: disable this unless the input to the binop is a shift by a constant.
3963   // If it is not a shift, it pessimizes some common cases like:
3964   //
3965   //    void foo(int *X, int i) { X[i & 1235] = 1; }
3966   //    int bar(int *X, int i) { return X[i & 255]; }
3967   SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
3968   if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
3969        BinOpLHSVal->getOpcode() != ISD::SRA &&
3970        BinOpLHSVal->getOpcode() != ISD::SRL) ||
3971       !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
3972     return SDValue();
3973
3974   EVT VT = N->getValueType(0);
3975
3976   // If this is a signed shift right, and the high bit is modified by the
3977   // logical operation, do not perform the transformation. The highBitSet
3978   // boolean indicates the value of the high bit of the constant which would
3979   // cause it to be modified for this operation.
3980   if (N->getOpcode() == ISD::SRA) {
3981     bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
3982     if (BinOpRHSSignSet != HighBitSet)
3983       return SDValue();
3984   }
3985
3986   if (!TLI.isDesirableToCommuteWithShift(LHS))
3987     return SDValue();
3988
3989   // Fold the constants, shifting the binop RHS by the shift amount.
3990   SDValue NewRHS = DAG.getNode(N->getOpcode(), SDLoc(LHS->getOperand(1)),
3991                                N->getValueType(0),
3992                                LHS->getOperand(1), N->getOperand(1));
3993   assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
3994
3995   // Create the new shift.
3996   SDValue NewShift = DAG.getNode(N->getOpcode(),
3997                                  SDLoc(LHS->getOperand(0)),
3998                                  VT, LHS->getOperand(0), N->getOperand(1));
3999
4000   // Create the new binop.
4001   return DAG.getNode(LHS->getOpcode(), SDLoc(N), VT, NewShift, NewRHS);
4002 }
4003
4004 SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
4005   assert(N->getOpcode() == ISD::TRUNCATE);
4006   assert(N->getOperand(0).getOpcode() == ISD::AND);
4007
4008   // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
4009   if (N->hasOneUse() && N->getOperand(0).hasOneUse()) {
4010     SDValue N01 = N->getOperand(0).getOperand(1);
4011
4012     if (ConstantSDNode *N01C = isConstOrConstSplat(N01)) {
4013       EVT TruncVT = N->getValueType(0);
4014       SDValue N00 = N->getOperand(0).getOperand(0);
4015       APInt TruncC = N01C->getAPIntValue();
4016       TruncC = TruncC.trunc(TruncVT.getScalarSizeInBits());
4017
4018       return DAG.getNode(ISD::AND, SDLoc(N), TruncVT,
4019                          DAG.getNode(ISD::TRUNCATE, SDLoc(N), TruncVT, N00),
4020                          DAG.getConstant(TruncC, TruncVT));
4021     }
4022   }
4023
4024   return SDValue();
4025 }
4026
4027 SDValue DAGCombiner::visitRotate(SDNode *N) {
4028   // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
4029   if (N->getOperand(1).getOpcode() == ISD::TRUNCATE &&
4030       N->getOperand(1).getOperand(0).getOpcode() == ISD::AND) {
4031     SDValue NewOp1 = distributeTruncateThroughAnd(N->getOperand(1).getNode());
4032     if (NewOp1.getNode())
4033       return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0),
4034                          N->getOperand(0), NewOp1);
4035   }
4036   return SDValue();
4037 }
4038
4039 SDValue DAGCombiner::visitSHL(SDNode *N) {
4040   SDValue N0 = N->getOperand(0);
4041   SDValue N1 = N->getOperand(1);
4042   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4043   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4044   EVT VT = N0.getValueType();
4045   unsigned OpSizeInBits = VT.getScalarSizeInBits();
4046
4047   // fold vector ops
4048   if (VT.isVector()) {
4049     SDValue FoldedVOp = SimplifyVBinOp(N);
4050     if (FoldedVOp.getNode()) return FoldedVOp;
4051
4052     BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
4053     // If setcc produces all-one true value then:
4054     // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
4055     if (N1CV && N1CV->isConstant()) {
4056       if (N0.getOpcode() == ISD::AND) {
4057         SDValue N00 = N0->getOperand(0);
4058         SDValue N01 = N0->getOperand(1);
4059         BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
4060
4061         if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
4062             TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
4063                 TargetLowering::ZeroOrNegativeOneBooleanContent) {
4064           SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, VT, N01CV, N1CV);
4065           if (C.getNode())
4066             return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
4067         }
4068       } else {
4069         N1C = isConstOrConstSplat(N1);
4070       }
4071     }
4072   }
4073
4074   // fold (shl c1, c2) -> c1<<c2
4075   if (N0C && N1C)
4076     return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
4077   // fold (shl 0, x) -> 0
4078   if (N0C && N0C->isNullValue())
4079     return N0;
4080   // fold (shl x, c >= size(x)) -> undef
4081   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4082     return DAG.getUNDEF(VT);
4083   // fold (shl x, 0) -> x
4084   if (N1C && N1C->isNullValue())
4085     return N0;
4086   // fold (shl undef, x) -> 0
4087   if (N0.getOpcode() == ISD::UNDEF)
4088     return DAG.getConstant(0, VT);
4089   // if (shl x, c) is known to be zero, return 0
4090   if (DAG.MaskedValueIsZero(SDValue(N, 0),
4091                             APInt::getAllOnesValue(OpSizeInBits)))
4092     return DAG.getConstant(0, VT);
4093   // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
4094   if (N1.getOpcode() == ISD::TRUNCATE &&
4095       N1.getOperand(0).getOpcode() == ISD::AND) {
4096     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4097     if (NewOp1.getNode())
4098       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
4099   }
4100
4101   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4102     return SDValue(N, 0);
4103
4104   // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
4105   if (N1C && N0.getOpcode() == ISD::SHL) {
4106     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4107       uint64_t c1 = N0C1->getZExtValue();
4108       uint64_t c2 = N1C->getZExtValue();
4109       if (c1 + c2 >= OpSizeInBits)
4110         return DAG.getConstant(0, VT);
4111       return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4112                          DAG.getConstant(c1 + c2, N1.getValueType()));
4113     }
4114   }
4115
4116   // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
4117   // For this to be valid, the second form must not preserve any of the bits
4118   // that are shifted out by the inner shift in the first form.  This means
4119   // the outer shift size must be >= the number of bits added by the ext.
4120   // As a corollary, we don't care what kind of ext it is.
4121   if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
4122               N0.getOpcode() == ISD::ANY_EXTEND ||
4123               N0.getOpcode() == ISD::SIGN_EXTEND) &&
4124       N0.getOperand(0).getOpcode() == ISD::SHL) {
4125     SDValue N0Op0 = N0.getOperand(0);
4126     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4127       uint64_t c1 = N0Op0C1->getZExtValue();
4128       uint64_t c2 = N1C->getZExtValue();
4129       EVT InnerShiftVT = N0Op0.getValueType();
4130       uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
4131       if (c2 >= OpSizeInBits - InnerShiftSize) {
4132         if (c1 + c2 >= OpSizeInBits)
4133           return DAG.getConstant(0, VT);
4134         return DAG.getNode(ISD::SHL, SDLoc(N0), VT,
4135                            DAG.getNode(N0.getOpcode(), SDLoc(N0), VT,
4136                                        N0Op0->getOperand(0)),
4137                            DAG.getConstant(c1 + c2, N1.getValueType()));
4138       }
4139     }
4140   }
4141
4142   // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
4143   // Only fold this if the inner zext has no other uses to avoid increasing
4144   // the total number of instructions.
4145   if (N1C && N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
4146       N0.getOperand(0).getOpcode() == ISD::SRL) {
4147     SDValue N0Op0 = N0.getOperand(0);
4148     if (ConstantSDNode *N0Op0C1 = isConstOrConstSplat(N0Op0.getOperand(1))) {
4149       uint64_t c1 = N0Op0C1->getZExtValue();
4150       if (c1 < VT.getScalarSizeInBits()) {
4151         uint64_t c2 = N1C->getZExtValue();
4152         if (c1 == c2) {
4153           SDValue NewOp0 = N0.getOperand(0);
4154           EVT CountVT = NewOp0.getOperand(1).getValueType();
4155           SDValue NewSHL = DAG.getNode(ISD::SHL, SDLoc(N), NewOp0.getValueType(),
4156                                        NewOp0, DAG.getConstant(c2, CountVT));
4157           AddToWorklist(NewSHL.getNode());
4158           return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
4159         }
4160       }
4161     }
4162   }
4163
4164   // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
4165   //                               (and (srl x, (sub c1, c2), MASK)
4166   // Only fold this if the inner shift has no other uses -- if it does, folding
4167   // this will increase the total number of instructions.
4168   if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
4169     if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
4170       uint64_t c1 = N0C1->getZExtValue();
4171       if (c1 < OpSizeInBits) {
4172         uint64_t c2 = N1C->getZExtValue();
4173         APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
4174         SDValue Shift;
4175         if (c2 > c1) {
4176           Mask = Mask.shl(c2 - c1);
4177           Shift = DAG.getNode(ISD::SHL, SDLoc(N), VT, N0.getOperand(0),
4178                               DAG.getConstant(c2 - c1, N1.getValueType()));
4179         } else {
4180           Mask = Mask.lshr(c1 - c2);
4181           Shift = DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4182                               DAG.getConstant(c1 - c2, N1.getValueType()));
4183         }
4184         return DAG.getNode(ISD::AND, SDLoc(N0), VT, Shift,
4185                            DAG.getConstant(Mask, VT));
4186       }
4187     }
4188   }
4189   // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
4190   if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
4191     unsigned BitSize = VT.getScalarSizeInBits();
4192     SDValue HiBitsMask =
4193       DAG.getConstant(APInt::getHighBitsSet(BitSize,
4194                                             BitSize - N1C->getZExtValue()), VT);
4195     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4196                        HiBitsMask);
4197   }
4198
4199   // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
4200   // Variant of version done on multiply, except mul by a power of 2 is turned
4201   // into a shift.
4202   APInt Val;
4203   if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
4204       (isa<ConstantSDNode>(N0.getOperand(1)) ||
4205        isConstantSplatVector(N0.getOperand(1).getNode(), Val))) {
4206     SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
4207     SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
4208     return DAG.getNode(ISD::ADD, SDLoc(N), VT, Shl0, Shl1);
4209   }
4210
4211   if (N1C) {
4212     SDValue NewSHL = visitShiftByConstant(N, N1C);
4213     if (NewSHL.getNode())
4214       return NewSHL;
4215   }
4216
4217   return SDValue();
4218 }
4219
4220 SDValue DAGCombiner::visitSRA(SDNode *N) {
4221   SDValue N0 = N->getOperand(0);
4222   SDValue N1 = N->getOperand(1);
4223   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4224   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4225   EVT VT = N0.getValueType();
4226   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4227
4228   // fold vector ops
4229   if (VT.isVector()) {
4230     SDValue FoldedVOp = SimplifyVBinOp(N);
4231     if (FoldedVOp.getNode()) return FoldedVOp;
4232
4233     N1C = isConstOrConstSplat(N1);
4234   }
4235
4236   // fold (sra c1, c2) -> (sra c1, c2)
4237   if (N0C && N1C)
4238     return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
4239   // fold (sra 0, x) -> 0
4240   if (N0C && N0C->isNullValue())
4241     return N0;
4242   // fold (sra -1, x) -> -1
4243   if (N0C && N0C->isAllOnesValue())
4244     return N0;
4245   // fold (sra x, (setge c, size(x))) -> undef
4246   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4247     return DAG.getUNDEF(VT);
4248   // fold (sra x, 0) -> x
4249   if (N1C && N1C->isNullValue())
4250     return N0;
4251   // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
4252   // sext_inreg.
4253   if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
4254     unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
4255     EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
4256     if (VT.isVector())
4257       ExtVT = EVT::getVectorVT(*DAG.getContext(),
4258                                ExtVT, VT.getVectorNumElements());
4259     if ((!LegalOperations ||
4260          TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
4261       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
4262                          N0.getOperand(0), DAG.getValueType(ExtVT));
4263   }
4264
4265   // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
4266   if (N1C && N0.getOpcode() == ISD::SRA) {
4267     if (ConstantSDNode *C1 = isConstOrConstSplat(N0.getOperand(1))) {
4268       unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
4269       if (Sum >= OpSizeInBits)
4270         Sum = OpSizeInBits - 1;
4271       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
4272                          DAG.getConstant(Sum, N1.getValueType()));
4273     }
4274   }
4275
4276   // fold (sra (shl X, m), (sub result_size, n))
4277   // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
4278   // result_size - n != m.
4279   // If truncate is free for the target sext(shl) is likely to result in better
4280   // code.
4281   if (N0.getOpcode() == ISD::SHL && N1C) {
4282     // Get the two constanst of the shifts, CN0 = m, CN = n.
4283     const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
4284     if (N01C) {
4285       LLVMContext &Ctx = *DAG.getContext();
4286       // Determine what the truncate's result bitsize and type would be.
4287       EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
4288
4289       if (VT.isVector())
4290         TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorNumElements());
4291
4292       // Determine the residual right-shift amount.
4293       signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
4294
4295       // If the shift is not a no-op (in which case this should be just a sign
4296       // extend already), the truncated to type is legal, sign_extend is legal
4297       // on that type, and the truncate to that type is both legal and free,
4298       // perform the transform.
4299       if ((ShiftAmt > 0) &&
4300           TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
4301           TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
4302           TLI.isTruncateFree(VT, TruncVT)) {
4303
4304           SDValue Amt = DAG.getConstant(ShiftAmt,
4305               getShiftAmountTy(N0.getOperand(0).getValueType()));
4306           SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0), VT,
4307                                       N0.getOperand(0), Amt);
4308           SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), TruncVT,
4309                                       Shift);
4310           return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N),
4311                              N->getValueType(0), Trunc);
4312       }
4313     }
4314   }
4315
4316   // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
4317   if (N1.getOpcode() == ISD::TRUNCATE &&
4318       N1.getOperand(0).getOpcode() == ISD::AND) {
4319     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4320     if (NewOp1.getNode())
4321       return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
4322   }
4323
4324   // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
4325   //      if c1 is equal to the number of bits the trunc removes
4326   if (N0.getOpcode() == ISD::TRUNCATE &&
4327       (N0.getOperand(0).getOpcode() == ISD::SRL ||
4328        N0.getOperand(0).getOpcode() == ISD::SRA) &&
4329       N0.getOperand(0).hasOneUse() &&
4330       N0.getOperand(0).getOperand(1).hasOneUse() &&
4331       N1C) {
4332     SDValue N0Op0 = N0.getOperand(0);
4333     if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
4334       unsigned LargeShiftVal = LargeShift->getZExtValue();
4335       EVT LargeVT = N0Op0.getValueType();
4336
4337       if (LargeVT.getScalarSizeInBits() - OpSizeInBits == LargeShiftVal) {
4338         SDValue Amt =
4339           DAG.getConstant(LargeShiftVal + N1C->getZExtValue(),
4340                           getShiftAmountTy(N0Op0.getOperand(0).getValueType()));
4341         SDValue SRA = DAG.getNode(ISD::SRA, SDLoc(N), LargeVT,
4342                                   N0Op0.getOperand(0), Amt);
4343         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, SRA);
4344       }
4345     }
4346   }
4347
4348   // Simplify, based on bits shifted out of the LHS.
4349   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4350     return SDValue(N, 0);
4351
4352
4353   // If the sign bit is known to be zero, switch this to a SRL.
4354   if (DAG.SignBitIsZero(N0))
4355     return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
4356
4357   if (N1C) {
4358     SDValue NewSRA = visitShiftByConstant(N, N1C);
4359     if (NewSRA.getNode())
4360       return NewSRA;
4361   }
4362
4363   return SDValue();
4364 }
4365
4366 SDValue DAGCombiner::visitSRL(SDNode *N) {
4367   SDValue N0 = N->getOperand(0);
4368   SDValue N1 = N->getOperand(1);
4369   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4370   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4371   EVT VT = N0.getValueType();
4372   unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
4373
4374   // fold vector ops
4375   if (VT.isVector()) {
4376     SDValue FoldedVOp = SimplifyVBinOp(N);
4377     if (FoldedVOp.getNode()) return FoldedVOp;
4378
4379     N1C = isConstOrConstSplat(N1);
4380   }
4381
4382   // fold (srl c1, c2) -> c1 >>u c2
4383   if (N0C && N1C)
4384     return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
4385   // fold (srl 0, x) -> 0
4386   if (N0C && N0C->isNullValue())
4387     return N0;
4388   // fold (srl x, c >= size(x)) -> undef
4389   if (N1C && N1C->getZExtValue() >= OpSizeInBits)
4390     return DAG.getUNDEF(VT);
4391   // fold (srl x, 0) -> x
4392   if (N1C && N1C->isNullValue())
4393     return N0;
4394   // if (srl x, c) is known to be zero, return 0
4395   if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
4396                                    APInt::getAllOnesValue(OpSizeInBits)))
4397     return DAG.getConstant(0, VT);
4398
4399   // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
4400   if (N1C && N0.getOpcode() == ISD::SRL) {
4401     if (ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1))) {
4402       uint64_t c1 = N01C->getZExtValue();
4403       uint64_t c2 = N1C->getZExtValue();
4404       if (c1 + c2 >= OpSizeInBits)
4405         return DAG.getConstant(0, VT);
4406       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0),
4407                          DAG.getConstant(c1 + c2, N1.getValueType()));
4408     }
4409   }
4410
4411   // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
4412   if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
4413       N0.getOperand(0).getOpcode() == ISD::SRL &&
4414       isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
4415     uint64_t c1 =
4416       cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
4417     uint64_t c2 = N1C->getZExtValue();
4418     EVT InnerShiftVT = N0.getOperand(0).getValueType();
4419     EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
4420     uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
4421     // This is only valid if the OpSizeInBits + c1 = size of inner shift.
4422     if (c1 + OpSizeInBits == InnerShiftSize) {
4423       if (c1 + c2 >= InnerShiftSize)
4424         return DAG.getConstant(0, VT);
4425       return DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT,
4426                          DAG.getNode(ISD::SRL, SDLoc(N0), InnerShiftVT,
4427                                      N0.getOperand(0)->getOperand(0),
4428                                      DAG.getConstant(c1 + c2, ShiftCountVT)));
4429     }
4430   }
4431
4432   // fold (srl (shl x, c), c) -> (and x, cst2)
4433   if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1) {
4434     unsigned BitSize = N0.getScalarValueSizeInBits();
4435     if (BitSize <= 64) {
4436       uint64_t ShAmt = N1C->getZExtValue() + 64 - BitSize;
4437       return DAG.getNode(ISD::AND, SDLoc(N), VT, N0.getOperand(0),
4438                          DAG.getConstant(~0ULL >> ShAmt, VT));
4439     }
4440   }
4441
4442   // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
4443   if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
4444     // Shifting in all undef bits?
4445     EVT SmallVT = N0.getOperand(0).getValueType();
4446     unsigned BitSize = SmallVT.getScalarSizeInBits();
4447     if (N1C->getZExtValue() >= BitSize)
4448       return DAG.getUNDEF(VT);
4449
4450     if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
4451       uint64_t ShiftAmt = N1C->getZExtValue();
4452       SDValue SmallShift = DAG.getNode(ISD::SRL, SDLoc(N0), SmallVT,
4453                                        N0.getOperand(0),
4454                           DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
4455       AddToWorklist(SmallShift.getNode());
4456       APInt Mask = APInt::getAllOnesValue(OpSizeInBits).lshr(ShiftAmt);
4457       return DAG.getNode(ISD::AND, SDLoc(N), VT,
4458                          DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, SmallShift),
4459                          DAG.getConstant(Mask, VT));
4460     }
4461   }
4462
4463   // fold (srl (sra X, Y), 31) -> (srl X, 31).  This srl only looks at the sign
4464   // bit, which is unmodified by sra.
4465   if (N1C && N1C->getZExtValue() + 1 == OpSizeInBits) {
4466     if (N0.getOpcode() == ISD::SRA)
4467       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
4468   }
4469
4470   // fold (srl (ctlz x), "5") -> x  iff x has one bit set (the low bit).
4471   if (N1C && N0.getOpcode() == ISD::CTLZ &&
4472       N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
4473     APInt KnownZero, KnownOne;
4474     DAG.computeKnownBits(N0.getOperand(0), KnownZero, KnownOne);
4475
4476     // If any of the input bits are KnownOne, then the input couldn't be all
4477     // zeros, thus the result of the srl will always be zero.
4478     if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
4479
4480     // If all of the bits input the to ctlz node are known to be zero, then
4481     // the result of the ctlz is "32" and the result of the shift is one.
4482     APInt UnknownBits = ~KnownZero;
4483     if (UnknownBits == 0) return DAG.getConstant(1, VT);
4484
4485     // Otherwise, check to see if there is exactly one bit input to the ctlz.
4486     if ((UnknownBits & (UnknownBits - 1)) == 0) {
4487       // Okay, we know that only that the single bit specified by UnknownBits
4488       // could be set on input to the CTLZ node. If this bit is set, the SRL
4489       // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
4490       // to an SRL/XOR pair, which is likely to simplify more.
4491       unsigned ShAmt = UnknownBits.countTrailingZeros();
4492       SDValue Op = N0.getOperand(0);
4493
4494       if (ShAmt) {
4495         Op = DAG.getNode(ISD::SRL, SDLoc(N0), VT, Op,
4496                   DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
4497         AddToWorklist(Op.getNode());
4498       }
4499
4500       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
4501                          Op, DAG.getConstant(1, VT));
4502     }
4503   }
4504
4505   // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
4506   if (N1.getOpcode() == ISD::TRUNCATE &&
4507       N1.getOperand(0).getOpcode() == ISD::AND) {
4508     SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode());
4509     if (NewOp1.getNode())
4510       return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
4511   }
4512
4513   // fold operands of srl based on knowledge that the low bits are not
4514   // demanded.
4515   if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
4516     return SDValue(N, 0);
4517
4518   if (N1C) {
4519     SDValue NewSRL = visitShiftByConstant(N, N1C);
4520     if (NewSRL.getNode())
4521       return NewSRL;
4522   }
4523
4524   // Attempt to convert a srl of a load into a narrower zero-extending load.
4525   SDValue NarrowLoad = ReduceLoadWidth(N);
4526   if (NarrowLoad.getNode())
4527     return NarrowLoad;
4528
4529   // Here is a common situation. We want to optimize:
4530   //
4531   //   %a = ...
4532   //   %b = and i32 %a, 2
4533   //   %c = srl i32 %b, 1
4534   //   brcond i32 %c ...
4535   //
4536   // into
4537   //
4538   //   %a = ...
4539   //   %b = and %a, 2
4540   //   %c = setcc eq %b, 0
4541   //   brcond %c ...
4542   //
4543   // However when after the source operand of SRL is optimized into AND, the SRL
4544   // itself may not be optimized further. Look for it and add the BRCOND into
4545   // the worklist.
4546   if (N->hasOneUse()) {
4547     SDNode *Use = *N->use_begin();
4548     if (Use->getOpcode() == ISD::BRCOND)
4549       AddToWorklist(Use);
4550     else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
4551       // Also look pass the truncate.
4552       Use = *Use->use_begin();
4553       if (Use->getOpcode() == ISD::BRCOND)
4554         AddToWorklist(Use);
4555     }
4556   }
4557
4558   return SDValue();
4559 }
4560
4561 SDValue DAGCombiner::visitCTLZ(SDNode *N) {
4562   SDValue N0 = N->getOperand(0);
4563   EVT VT = N->getValueType(0);
4564
4565   // fold (ctlz c1) -> c2
4566   if (isa<ConstantSDNode>(N0))
4567     return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
4568   return SDValue();
4569 }
4570
4571 SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
4572   SDValue N0 = N->getOperand(0);
4573   EVT VT = N->getValueType(0);
4574
4575   // fold (ctlz_zero_undef c1) -> c2
4576   if (isa<ConstantSDNode>(N0))
4577     return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4578   return SDValue();
4579 }
4580
4581 SDValue DAGCombiner::visitCTTZ(SDNode *N) {
4582   SDValue N0 = N->getOperand(0);
4583   EVT VT = N->getValueType(0);
4584
4585   // fold (cttz c1) -> c2
4586   if (isa<ConstantSDNode>(N0))
4587     return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
4588   return SDValue();
4589 }
4590
4591 SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
4592   SDValue N0 = N->getOperand(0);
4593   EVT VT = N->getValueType(0);
4594
4595   // fold (cttz_zero_undef c1) -> c2
4596   if (isa<ConstantSDNode>(N0))
4597     return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
4598   return SDValue();
4599 }
4600
4601 SDValue DAGCombiner::visitCTPOP(SDNode *N) {
4602   SDValue N0 = N->getOperand(0);
4603   EVT VT = N->getValueType(0);
4604
4605   // fold (ctpop c1) -> c2
4606   if (isa<ConstantSDNode>(N0))
4607     return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
4608   return SDValue();
4609 }
4610
4611 SDValue DAGCombiner::visitSELECT(SDNode *N) {
4612   SDValue N0 = N->getOperand(0);
4613   SDValue N1 = N->getOperand(1);
4614   SDValue N2 = N->getOperand(2);
4615   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
4616   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
4617   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
4618   EVT VT = N->getValueType(0);
4619   EVT VT0 = N0.getValueType();
4620
4621   // fold (select C, X, X) -> X
4622   if (N1 == N2)
4623     return N1;
4624   // fold (select true, X, Y) -> X
4625   if (N0C && !N0C->isNullValue())
4626     return N1;
4627   // fold (select false, X, Y) -> Y
4628   if (N0C && N0C->isNullValue())
4629     return N2;
4630   // fold (select C, 1, X) -> (or C, X)
4631   if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
4632     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4633   // fold (select C, 0, 1) -> (xor C, 1)
4634   // We can't do this reliably if integer based booleans have different contents
4635   // to floating point based booleans. This is because we can't tell whether we
4636   // have an integer-based boolean or a floating-point-based boolean unless we
4637   // can find the SETCC that produced it and inspect its operands. This is
4638   // fairly easy if C is the SETCC node, but it can potentially be
4639   // undiscoverable (or not reasonably discoverable). For example, it could be
4640   // in another basic block or it could require searching a complicated
4641   // expression.
4642   if (VT.isInteger() &&
4643       (VT0 == MVT::i1 || (VT0.isInteger() &&
4644                           TLI.getBooleanContents(false, false) ==
4645                               TLI.getBooleanContents(false, true) &&
4646                           TLI.getBooleanContents(false, false) ==
4647                               TargetLowering::ZeroOrOneBooleanContent)) &&
4648       N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
4649     SDValue XORNode;
4650     if (VT == VT0)
4651       return DAG.getNode(ISD::XOR, SDLoc(N), VT0,
4652                          N0, DAG.getConstant(1, VT0));
4653     XORNode = DAG.getNode(ISD::XOR, SDLoc(N0), VT0,
4654                           N0, DAG.getConstant(1, VT0));
4655     AddToWorklist(XORNode.getNode());
4656     if (VT.bitsGT(VT0))
4657       return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, XORNode);
4658     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, XORNode);
4659   }
4660   // fold (select C, 0, X) -> (and (not C), X)
4661   if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
4662     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4663     AddToWorklist(NOTNode.getNode());
4664     return DAG.getNode(ISD::AND, SDLoc(N), VT, NOTNode, N2);
4665   }
4666   // fold (select C, X, 1) -> (or (not C), X)
4667   if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
4668     SDValue NOTNode = DAG.getNOT(SDLoc(N0), N0, VT);
4669     AddToWorklist(NOTNode.getNode());
4670     return DAG.getNode(ISD::OR, SDLoc(N), VT, NOTNode, N1);
4671   }
4672   // fold (select C, X, 0) -> (and C, X)
4673   if (VT == MVT::i1 && N2C && N2C->isNullValue())
4674     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4675   // fold (select X, X, Y) -> (or X, Y)
4676   // fold (select X, 1, Y) -> (or X, Y)
4677   if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
4678     return DAG.getNode(ISD::OR, SDLoc(N), VT, N0, N2);
4679   // fold (select X, Y, X) -> (and X, Y)
4680   // fold (select X, Y, 0) -> (and X, Y)
4681   if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
4682     return DAG.getNode(ISD::AND, SDLoc(N), VT, N0, N1);
4683
4684   // If we can fold this based on the true/false value, do so.
4685   if (SimplifySelectOps(N, N1, N2))
4686     return SDValue(N, 0);  // Don't revisit N.
4687
4688   // fold selects based on a setcc into other things, such as min/max/abs
4689   if (N0.getOpcode() == ISD::SETCC) {
4690     if ((!LegalOperations &&
4691          TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT)) ||
4692         TLI.isOperationLegal(ISD::SELECT_CC, VT))
4693       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT,
4694                          N0.getOperand(0), N0.getOperand(1),
4695                          N1, N2, N0.getOperand(2));
4696     return SimplifySelect(SDLoc(N), N0, N1, N2);
4697   }
4698
4699   return SDValue();
4700 }
4701
4702 static
4703 std::pair<SDValue, SDValue> SplitVSETCC(const SDNode *N, SelectionDAG &DAG) {
4704   SDLoc DL(N);
4705   EVT LoVT, HiVT;
4706   std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
4707
4708   // Split the inputs.
4709   SDValue Lo, Hi, LL, LH, RL, RH;
4710   std::tie(LL, LH) = DAG.SplitVectorOperand(N, 0);
4711   std::tie(RL, RH) = DAG.SplitVectorOperand(N, 1);
4712
4713   Lo = DAG.getNode(N->getOpcode(), DL, LoVT, LL, RL, N->getOperand(2));
4714   Hi = DAG.getNode(N->getOpcode(), DL, HiVT, LH, RH, N->getOperand(2));
4715
4716   return std::make_pair(Lo, Hi);
4717 }
4718
4719 // This function assumes all the vselect's arguments are CONCAT_VECTOR
4720 // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
4721 static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
4722   SDLoc dl(N);
4723   SDValue Cond = N->getOperand(0);
4724   SDValue LHS = N->getOperand(1);
4725   SDValue RHS = N->getOperand(2);
4726   EVT VT = N->getValueType(0);
4727   int NumElems = VT.getVectorNumElements();
4728   assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
4729          RHS.getOpcode() == ISD::CONCAT_VECTORS &&
4730          Cond.getOpcode() == ISD::BUILD_VECTOR);
4731
4732   // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
4733   // binary ones here.
4734   if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
4735     return SDValue();
4736
4737   // We're sure we have an even number of elements due to the
4738   // concat_vectors we have as arguments to vselect.
4739   // Skip BV elements until we find one that's not an UNDEF
4740   // After we find an UNDEF element, keep looping until we get to half the
4741   // length of the BV and see if all the non-undef nodes are the same.
4742   ConstantSDNode *BottomHalf = nullptr;
4743   for (int i = 0; i < NumElems / 2; ++i) {
4744     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4745       continue;
4746
4747     if (BottomHalf == nullptr)
4748       BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4749     else if (Cond->getOperand(i).getNode() != BottomHalf)
4750       return SDValue();
4751   }
4752
4753   // Do the same for the second half of the BuildVector
4754   ConstantSDNode *TopHalf = nullptr;
4755   for (int i = NumElems / 2; i < NumElems; ++i) {
4756     if (Cond->getOperand(i)->getOpcode() == ISD::UNDEF)
4757       continue;
4758
4759     if (TopHalf == nullptr)
4760       TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
4761     else if (Cond->getOperand(i).getNode() != TopHalf)
4762       return SDValue();
4763   }
4764
4765   assert(TopHalf && BottomHalf &&
4766          "One half of the selector was all UNDEFs and the other was all the "
4767          "same value. This should have been addressed before this function.");
4768   return DAG.getNode(
4769       ISD::CONCAT_VECTORS, dl, VT,
4770       BottomHalf->isNullValue() ? RHS->getOperand(0) : LHS->getOperand(0),
4771       TopHalf->isNullValue() ? RHS->getOperand(1) : LHS->getOperand(1));
4772 }
4773
4774 SDValue DAGCombiner::visitVSELECT(SDNode *N) {
4775   SDValue N0 = N->getOperand(0);
4776   SDValue N1 = N->getOperand(1);
4777   SDValue N2 = N->getOperand(2);
4778   SDLoc DL(N);
4779
4780   // Canonicalize integer abs.
4781   // vselect (setg[te] X,  0),  X, -X ->
4782   // vselect (setgt    X, -1),  X, -X ->
4783   // vselect (setl[te] X,  0), -X,  X ->
4784   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
4785   if (N0.getOpcode() == ISD::SETCC) {
4786     SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
4787     ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
4788     bool isAbs = false;
4789     bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
4790
4791     if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
4792          (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
4793         N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
4794       isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
4795     else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
4796              N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
4797       isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
4798
4799     if (isAbs) {
4800       EVT VT = LHS.getValueType();
4801       SDValue Shift = DAG.getNode(
4802           ISD::SRA, DL, VT, LHS,
4803           DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
4804       SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
4805       AddToWorklist(Shift.getNode());
4806       AddToWorklist(Add.getNode());
4807       return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
4808     }
4809   }
4810
4811   // If the VSELECT result requires splitting and the mask is provided by a
4812   // SETCC, then split both nodes and its operands before legalization. This
4813   // prevents the type legalizer from unrolling SETCC into scalar comparisons
4814   // and enables future optimizations (e.g. min/max pattern matching on X86).
4815   if (N0.getOpcode() == ISD::SETCC) {
4816     EVT VT = N->getValueType(0);
4817
4818     // Check if any splitting is required.
4819     if (TLI.getTypeAction(*DAG.getContext(), VT) !=
4820         TargetLowering::TypeSplitVector)
4821       return SDValue();
4822
4823     SDValue Lo, Hi, CCLo, CCHi, LL, LH, RL, RH;
4824     std::tie(CCLo, CCHi) = SplitVSETCC(N0.getNode(), DAG);
4825     std::tie(LL, LH) = DAG.SplitVectorOperand(N, 1);
4826     std::tie(RL, RH) = DAG.SplitVectorOperand(N, 2);
4827
4828     Lo = DAG.getNode(N->getOpcode(), DL, LL.getValueType(), CCLo, LL, RL);
4829     Hi = DAG.getNode(N->getOpcode(), DL, LH.getValueType(), CCHi, LH, RH);
4830
4831     // Add the new VSELECT nodes to the work list in case they need to be split
4832     // again.
4833     AddToWorklist(Lo.getNode());
4834     AddToWorklist(Hi.getNode());
4835
4836     return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Lo, Hi);
4837   }
4838
4839   // Fold (vselect (build_vector all_ones), N1, N2) -> N1
4840   if (ISD::isBuildVectorAllOnes(N0.getNode()))
4841     return N1;
4842   // Fold (vselect (build_vector all_zeros), N1, N2) -> N2
4843   if (ISD::isBuildVectorAllZeros(N0.getNode()))
4844     return N2;
4845
4846   // The ConvertSelectToConcatVector function is assuming both the above
4847   // checks for (vselect (build_vector all{ones,zeros) ...) have been made
4848   // and addressed.
4849   if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
4850       N2.getOpcode() == ISD::CONCAT_VECTORS &&
4851       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
4852     SDValue CV = ConvertSelectToConcatVector(N, DAG);
4853     if (CV.getNode())
4854       return CV;
4855   }
4856
4857   return SDValue();
4858 }
4859
4860 SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
4861   SDValue N0 = N->getOperand(0);
4862   SDValue N1 = N->getOperand(1);
4863   SDValue N2 = N->getOperand(2);
4864   SDValue N3 = N->getOperand(3);
4865   SDValue N4 = N->getOperand(4);
4866   ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
4867
4868   // fold select_cc lhs, rhs, x, x, cc -> x
4869   if (N2 == N3)
4870     return N2;
4871
4872   // Determine if the condition we're dealing with is constant
4873   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
4874                               N0, N1, CC, SDLoc(N), false);
4875   if (SCC.getNode()) {
4876     AddToWorklist(SCC.getNode());
4877
4878     if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
4879       if (!SCCC->isNullValue())
4880         return N2;    // cond always true -> true val
4881       else
4882         return N3;    // cond always false -> false val
4883     }
4884
4885     // Fold to a simpler select_cc
4886     if (SCC.getOpcode() == ISD::SETCC)
4887       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), N2.getValueType(),
4888                          SCC.getOperand(0), SCC.getOperand(1), N2, N3,
4889                          SCC.getOperand(2));
4890   }
4891
4892   // If we can fold this based on the true/false value, do so.
4893   if (SimplifySelectOps(N, N2, N3))
4894     return SDValue(N, 0);  // Don't revisit N.
4895
4896   // fold select_cc into other things, such as min/max/abs
4897   return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
4898 }
4899
4900 SDValue DAGCombiner::visitSETCC(SDNode *N) {
4901   return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
4902                        cast<CondCodeSDNode>(N->getOperand(2))->get(),
4903                        SDLoc(N));
4904 }
4905
4906 // tryToFoldExtendOfConstant - Try to fold a sext/zext/aext
4907 // dag node into a ConstantSDNode or a build_vector of constants.
4908 // This function is called by the DAGCombiner when visiting sext/zext/aext
4909 // dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
4910 // Vector extends are not folded if operations are legal; this is to
4911 // avoid introducing illegal build_vector dag nodes.
4912 static SDNode *tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
4913                                          SelectionDAG &DAG, bool LegalTypes,
4914                                          bool LegalOperations) {
4915   unsigned Opcode = N->getOpcode();
4916   SDValue N0 = N->getOperand(0);
4917   EVT VT = N->getValueType(0);
4918
4919   assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
4920          Opcode == ISD::ANY_EXTEND) && "Expected EXTEND dag node in input!");
4921
4922   // fold (sext c1) -> c1
4923   // fold (zext c1) -> c1
4924   // fold (aext c1) -> c1
4925   if (isa<ConstantSDNode>(N0))
4926     return DAG.getNode(Opcode, SDLoc(N), VT, N0).getNode();
4927
4928   // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
4929   // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
4930   // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
4931   EVT SVT = VT.getScalarType();
4932   if (!(VT.isVector() &&
4933       (!LegalTypes || (!LegalOperations && TLI.isTypeLegal(SVT))) &&
4934       ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
4935     return nullptr;
4936
4937   // We can fold this node into a build_vector.
4938   unsigned VTBits = SVT.getSizeInBits();
4939   unsigned EVTBits = N0->getValueType(0).getScalarType().getSizeInBits();
4940   unsigned ShAmt = VTBits - EVTBits;
4941   SmallVector<SDValue, 8> Elts;
4942   unsigned NumElts = N0->getNumOperands();
4943   SDLoc DL(N);
4944
4945   for (unsigned i=0; i != NumElts; ++i) {
4946     SDValue Op = N0->getOperand(i);
4947     if (Op->getOpcode() == ISD::UNDEF) {
4948       Elts.push_back(DAG.getUNDEF(SVT));
4949       continue;
4950     }
4951
4952     ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
4953     const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
4954     if (Opcode == ISD::SIGN_EXTEND)
4955       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
4956                                      SVT));
4957     else
4958       Elts.push_back(DAG.getConstant(C.shl(ShAmt).lshr(ShAmt).getZExtValue(),
4959                                      SVT));
4960   }
4961
4962   return DAG.getNode(ISD::BUILD_VECTOR, DL, VT, Elts).getNode();
4963 }
4964
4965 // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
4966 // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
4967 // transformation. Returns true if extension are possible and the above
4968 // mentioned transformation is profitable.
4969 static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
4970                                     unsigned ExtOpc,
4971                                     SmallVectorImpl<SDNode *> &ExtendNodes,
4972                                     const TargetLowering &TLI) {
4973   bool HasCopyToRegUses = false;
4974   bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
4975   for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
4976                             UE = N0.getNode()->use_end();
4977        UI != UE; ++UI) {
4978     SDNode *User = *UI;
4979     if (User == N)
4980       continue;
4981     if (UI.getUse().getResNo() != N0.getResNo())
4982       continue;
4983     // FIXME: Only extend SETCC N, N and SETCC N, c for now.
4984     if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
4985       ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
4986       if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
4987         // Sign bits will be lost after a zext.
4988         return false;
4989       bool Add = false;
4990       for (unsigned i = 0; i != 2; ++i) {
4991         SDValue UseOp = User->getOperand(i);
4992         if (UseOp == N0)
4993           continue;
4994         if (!isa<ConstantSDNode>(UseOp))
4995           return false;
4996         Add = true;
4997       }
4998       if (Add)
4999         ExtendNodes.push_back(User);
5000       continue;
5001     }
5002     // If truncates aren't free and there are users we can't
5003     // extend, it isn't worthwhile.
5004     if (!isTruncFree)
5005       return false;
5006     // Remember if this value is live-out.
5007     if (User->getOpcode() == ISD::CopyToReg)
5008       HasCopyToRegUses = true;
5009   }
5010
5011   if (HasCopyToRegUses) {
5012     bool BothLiveOut = false;
5013     for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5014          UI != UE; ++UI) {
5015       SDUse &Use = UI.getUse();
5016       if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
5017         BothLiveOut = true;
5018         break;
5019       }
5020     }
5021     if (BothLiveOut)
5022       // Both unextended and extended values are live out. There had better be
5023       // a good reason for the transformation.
5024       return ExtendNodes.size();
5025   }
5026   return true;
5027 }
5028
5029 void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
5030                                   SDValue Trunc, SDValue ExtLoad, SDLoc DL,
5031                                   ISD::NodeType ExtType) {
5032   // Extend SetCC uses if necessary.
5033   for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
5034     SDNode *SetCC = SetCCs[i];
5035     SmallVector<SDValue, 4> Ops;
5036
5037     for (unsigned j = 0; j != 2; ++j) {
5038       SDValue SOp = SetCC->getOperand(j);
5039       if (SOp == Trunc)
5040         Ops.push_back(ExtLoad);
5041       else
5042         Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
5043     }
5044
5045     Ops.push_back(SetCC->getOperand(2));
5046     CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
5047   }
5048 }
5049
5050 SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
5051   SDValue N0 = N->getOperand(0);
5052   EVT VT = N->getValueType(0);
5053
5054   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5055                                               LegalOperations))
5056     return SDValue(Res, 0);
5057
5058   // fold (sext (sext x)) -> (sext x)
5059   // fold (sext (aext x)) -> (sext x)
5060   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5061     return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT,
5062                        N0.getOperand(0));
5063
5064   if (N0.getOpcode() == ISD::TRUNCATE) {
5065     // fold (sext (truncate (load x))) -> (sext (smaller load x))
5066     // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
5067     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5068     if (NarrowLoad.getNode()) {
5069       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5070       if (NarrowLoad.getNode() != N0.getNode()) {
5071         CombineTo(N0.getNode(), NarrowLoad);
5072         // CombineTo deleted the truncate, if needed, but not what's under it.
5073         AddToWorklist(oye);
5074       }
5075       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5076     }
5077
5078     // See if the value being truncated is already sign extended.  If so, just
5079     // eliminate the trunc/sext pair.
5080     SDValue Op = N0.getOperand(0);
5081     unsigned OpBits   = Op.getValueType().getScalarType().getSizeInBits();
5082     unsigned MidBits  = N0.getValueType().getScalarType().getSizeInBits();
5083     unsigned DestBits = VT.getScalarType().getSizeInBits();
5084     unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
5085
5086     if (OpBits == DestBits) {
5087       // Op is i32, Mid is i8, and Dest is i32.  If Op has more than 24 sign
5088       // bits, it is already ready.
5089       if (NumSignBits > DestBits-MidBits)
5090         return Op;
5091     } else if (OpBits < DestBits) {
5092       // Op is i32, Mid is i8, and Dest is i64.  If Op has more than 24 sign
5093       // bits, just sext from i32.
5094       if (NumSignBits > OpBits-MidBits)
5095         return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, Op);
5096     } else {
5097       // Op is i64, Mid is i8, and Dest is i32.  If Op has more than 56 sign
5098       // bits, just truncate to i32.
5099       if (NumSignBits > OpBits-MidBits)
5100         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5101     }
5102
5103     // fold (sext (truncate x)) -> (sextinreg x).
5104     if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
5105                                                  N0.getValueType())) {
5106       if (OpBits < DestBits)
5107         Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
5108       else if (OpBits > DestBits)
5109         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
5110       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, Op,
5111                          DAG.getValueType(N0.getValueType()));
5112     }
5113   }
5114
5115   // fold (sext (load x)) -> (sext (truncate (sextload x)))
5116   // None of the supported targets knows how to perform load and sign extend
5117   // on vectors in one instruction.  We only perform this transformation on
5118   // scalars.
5119   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5120       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5121       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5122        TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
5123     bool DoXform = true;
5124     SmallVector<SDNode*, 4> SetCCs;
5125     if (!N0.hasOneUse())
5126       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
5127     if (DoXform) {
5128       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5129       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5130                                        LN0->getChain(),
5131                                        LN0->getBasePtr(), N0.getValueType(),
5132                                        LN0->getMemOperand());
5133       CombineTo(N, ExtLoad);
5134       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5135                                   N0.getValueType(), ExtLoad);
5136       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5137       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5138                       ISD::SIGN_EXTEND);
5139       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5140     }
5141   }
5142
5143   // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
5144   // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
5145   if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5146       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5147     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5148     EVT MemVT = LN0->getMemoryVT();
5149     if ((!LegalOperations && !LN0->isVolatile()) ||
5150         TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
5151       SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
5152                                        LN0->getChain(),
5153                                        LN0->getBasePtr(), MemVT,
5154                                        LN0->getMemOperand());
5155       CombineTo(N, ExtLoad);
5156       CombineTo(N0.getNode(),
5157                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5158                             N0.getValueType(), ExtLoad),
5159                 ExtLoad.getValue(1));
5160       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5161     }
5162   }
5163
5164   // fold (sext (and/or/xor (load x), cst)) ->
5165   //      (and/or/xor (sextload x), (sext cst))
5166   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5167        N0.getOpcode() == ISD::XOR) &&
5168       isa<LoadSDNode>(N0.getOperand(0)) &&
5169       N0.getOperand(1).getOpcode() == ISD::Constant &&
5170       TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
5171       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5172     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5173     if (LN0->getExtensionType() != ISD::ZEXTLOAD && LN0->isUnindexed()) {
5174       bool DoXform = true;
5175       SmallVector<SDNode*, 4> SetCCs;
5176       if (!N0.hasOneUse())
5177         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
5178                                           SetCCs, TLI);
5179       if (DoXform) {
5180         SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN0), VT,
5181                                          LN0->getChain(), LN0->getBasePtr(),
5182                                          LN0->getMemoryVT(),
5183                                          LN0->getMemOperand());
5184         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5185         Mask = Mask.sext(VT.getSizeInBits());
5186         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5187                                   ExtLoad, DAG.getConstant(Mask, VT));
5188         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5189                                     SDLoc(N0.getOperand(0)),
5190                                     N0.getOperand(0).getValueType(), ExtLoad);
5191         CombineTo(N, And);
5192         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5193         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5194                         ISD::SIGN_EXTEND);
5195         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5196       }
5197     }
5198   }
5199
5200   if (N0.getOpcode() == ISD::SETCC) {
5201     EVT N0VT = N0.getOperand(0).getValueType();
5202     // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
5203     // Only do this before legalize for now.
5204     if (VT.isVector() && !LegalOperations &&
5205         TLI.getBooleanContents(N0VT) ==
5206             TargetLowering::ZeroOrNegativeOneBooleanContent) {
5207       // On some architectures (such as SSE/NEON/etc) the SETCC result type is
5208       // of the same size as the compared operands. Only optimize sext(setcc())
5209       // if this is the case.
5210       EVT SVT = getSetCCResultType(N0VT);
5211
5212       // We know that the # elements of the results is the same as the
5213       // # elements of the compare (and the # elements of the compare result
5214       // for that matter).  Check to see that they are the same size.  If so,
5215       // we know that the element size of the sext'd result matches the
5216       // element size of the compare operands.
5217       if (VT.getSizeInBits() == SVT.getSizeInBits())
5218         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5219                              N0.getOperand(1),
5220                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5221
5222       // If the desired elements are smaller or larger than the source
5223       // elements we can use a matching integer vector type and then
5224       // truncate/sign extend
5225       EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5226       if (SVT == MatchingVectorType) {
5227         SDValue VsetCC = DAG.getSetCC(SDLoc(N), MatchingVectorType,
5228                                N0.getOperand(0), N0.getOperand(1),
5229                                cast<CondCodeSDNode>(N0.getOperand(2))->get());
5230         return DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT);
5231       }
5232     }
5233
5234     // sext(setcc x, y, cc) -> (select (setcc x, y, cc), -1, 0)
5235     unsigned ElementWidth = VT.getScalarType().getSizeInBits();
5236     SDValue NegOne =
5237       DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
5238     SDValue SCC =
5239       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5240                        NegOne, DAG.getConstant(0, VT),
5241                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5242     if (SCC.getNode()) return SCC;
5243
5244     if (!VT.isVector()) {
5245       EVT SetCCVT = getSetCCResultType(N0.getOperand(0).getValueType());
5246       if (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, SetCCVT)) {
5247         SDLoc DL(N);
5248         ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
5249         SDValue SetCC = DAG.getSetCC(DL, SetCCVT,
5250                                      N0.getOperand(0), N0.getOperand(1), CC);
5251         return DAG.getSelect(DL, VT, SetCC,
5252                              NegOne, DAG.getConstant(0, VT));
5253       }
5254     }
5255   }
5256
5257   // fold (sext x) -> (zext x) if the sign bit is known zero.
5258   if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
5259       DAG.SignBitIsZero(N0))
5260     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0);
5261
5262   return SDValue();
5263 }
5264
5265 // isTruncateOf - If N is a truncate of some other value, return true, record
5266 // the value being truncated in Op and which of Op's bits are zero in KnownZero.
5267 // This function computes KnownZero to avoid a duplicated call to
5268 // computeKnownBits in the caller.
5269 static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
5270                          APInt &KnownZero) {
5271   APInt KnownOne;
5272   if (N->getOpcode() == ISD::TRUNCATE) {
5273     Op = N->getOperand(0);
5274     DAG.computeKnownBits(Op, KnownZero, KnownOne);
5275     return true;
5276   }
5277
5278   if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
5279       cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
5280     return false;
5281
5282   SDValue Op0 = N->getOperand(0);
5283   SDValue Op1 = N->getOperand(1);
5284   assert(Op0.getValueType() == Op1.getValueType());
5285
5286   ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
5287   ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
5288   if (COp0 && COp0->isNullValue())
5289     Op = Op1;
5290   else if (COp1 && COp1->isNullValue())
5291     Op = Op0;
5292   else
5293     return false;
5294
5295   DAG.computeKnownBits(Op, KnownZero, KnownOne);
5296
5297   if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
5298     return false;
5299
5300   return true;
5301 }
5302
5303 SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
5304   SDValue N0 = N->getOperand(0);
5305   EVT VT = N->getValueType(0);
5306
5307   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5308                                               LegalOperations))
5309     return SDValue(Res, 0);
5310
5311   // fold (zext (zext x)) -> (zext x)
5312   // fold (zext (aext x)) -> (zext x)
5313   if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
5314     return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
5315                        N0.getOperand(0));
5316
5317   // fold (zext (truncate x)) -> (zext x) or
5318   //      (zext (truncate x)) -> (truncate x)
5319   // This is valid when the truncated bits of x are already zero.
5320   // FIXME: We should extend this to work for vectors too.
5321   SDValue Op;
5322   APInt KnownZero;
5323   if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
5324     APInt TruncatedBits =
5325       (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
5326       APInt(Op.getValueSizeInBits(), 0) :
5327       APInt::getBitsSet(Op.getValueSizeInBits(),
5328                         N0.getValueSizeInBits(),
5329                         std::min(Op.getValueSizeInBits(),
5330                                  VT.getSizeInBits()));
5331     if (TruncatedBits == (KnownZero & TruncatedBits)) {
5332       if (VT.bitsGT(Op.getValueType()))
5333         return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, Op);
5334       if (VT.bitsLT(Op.getValueType()))
5335         return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5336
5337       return Op;
5338     }
5339   }
5340
5341   // fold (zext (truncate (load x))) -> (zext (smaller load x))
5342   // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
5343   if (N0.getOpcode() == ISD::TRUNCATE) {
5344     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5345     if (NarrowLoad.getNode()) {
5346       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5347       if (NarrowLoad.getNode() != N0.getNode()) {
5348         CombineTo(N0.getNode(), NarrowLoad);
5349         // CombineTo deleted the truncate, if needed, but not what's under it.
5350         AddToWorklist(oye);
5351       }
5352       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5353     }
5354   }
5355
5356   // fold (zext (truncate x)) -> (and x, mask)
5357   if (N0.getOpcode() == ISD::TRUNCATE &&
5358       (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
5359
5360     // fold (zext (truncate (load x))) -> (zext (smaller load x))
5361     // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
5362     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5363     if (NarrowLoad.getNode()) {
5364       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5365       if (NarrowLoad.getNode() != N0.getNode()) {
5366         CombineTo(N0.getNode(), NarrowLoad);
5367         // CombineTo deleted the truncate, if needed, but not what's under it.
5368         AddToWorklist(oye);
5369       }
5370       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5371     }
5372
5373     SDValue Op = N0.getOperand(0);
5374     if (Op.getValueType().bitsLT(VT)) {
5375       Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, Op);
5376       AddToWorklist(Op.getNode());
5377     } else if (Op.getValueType().bitsGT(VT)) {
5378       Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Op);
5379       AddToWorklist(Op.getNode());
5380     }
5381     return DAG.getZeroExtendInReg(Op, SDLoc(N),
5382                                   N0.getValueType().getScalarType());
5383   }
5384
5385   // Fold (zext (and (trunc x), cst)) -> (and x, cst),
5386   // if either of the casts is not free.
5387   if (N0.getOpcode() == ISD::AND &&
5388       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5389       N0.getOperand(1).getOpcode() == ISD::Constant &&
5390       (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5391                            N0.getValueType()) ||
5392        !TLI.isZExtFree(N0.getValueType(), VT))) {
5393     SDValue X = N0.getOperand(0).getOperand(0);
5394     if (X.getValueType().bitsLT(VT)) {
5395       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(X), VT, X);
5396     } else if (X.getValueType().bitsGT(VT)) {
5397       X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
5398     }
5399     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5400     Mask = Mask.zext(VT.getSizeInBits());
5401     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5402                        X, DAG.getConstant(Mask, VT));
5403   }
5404
5405   // fold (zext (load x)) -> (zext (truncate (zextload x)))
5406   // None of the supported targets knows how to perform load and vector_zext
5407   // on vectors in one instruction.  We only perform this transformation on
5408   // scalars.
5409   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5410       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5411       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
5412        TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
5413     bool DoXform = true;
5414     SmallVector<SDNode*, 4> SetCCs;
5415     if (!N0.hasOneUse())
5416       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
5417     if (DoXform) {
5418       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5419       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5420                                        LN0->getChain(),
5421                                        LN0->getBasePtr(), N0.getValueType(),
5422                                        LN0->getMemOperand());
5423       CombineTo(N, ExtLoad);
5424       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5425                                   N0.getValueType(), ExtLoad);
5426       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5427
5428       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5429                       ISD::ZERO_EXTEND);
5430       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5431     }
5432   }
5433
5434   // fold (zext (and/or/xor (load x), cst)) ->
5435   //      (and/or/xor (zextload x), (zext cst))
5436   if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
5437        N0.getOpcode() == ISD::XOR) &&
5438       isa<LoadSDNode>(N0.getOperand(0)) &&
5439       N0.getOperand(1).getOpcode() == ISD::Constant &&
5440       TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
5441       (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
5442     LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
5443     if (LN0->getExtensionType() != ISD::SEXTLOAD && LN0->isUnindexed()) {
5444       bool DoXform = true;
5445       SmallVector<SDNode*, 4> SetCCs;
5446       if (!N0.hasOneUse())
5447         DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
5448                                           SetCCs, TLI);
5449       if (DoXform) {
5450         SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN0), VT,
5451                                          LN0->getChain(), LN0->getBasePtr(),
5452                                          LN0->getMemoryVT(),
5453                                          LN0->getMemOperand());
5454         APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5455         Mask = Mask.zext(VT.getSizeInBits());
5456         SDValue And = DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
5457                                   ExtLoad, DAG.getConstant(Mask, VT));
5458         SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
5459                                     SDLoc(N0.getOperand(0)),
5460                                     N0.getOperand(0).getValueType(), ExtLoad);
5461         CombineTo(N, And);
5462         CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
5463         ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5464                         ISD::ZERO_EXTEND);
5465         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5466       }
5467     }
5468   }
5469
5470   // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
5471   // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
5472   if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
5473       ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
5474     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5475     EVT MemVT = LN0->getMemoryVT();
5476     if ((!LegalOperations && !LN0->isVolatile()) ||
5477         TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
5478       SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N), VT,
5479                                        LN0->getChain(),
5480                                        LN0->getBasePtr(), MemVT,
5481                                        LN0->getMemOperand());
5482       CombineTo(N, ExtLoad);
5483       CombineTo(N0.getNode(),
5484                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(),
5485                             ExtLoad),
5486                 ExtLoad.getValue(1));
5487       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5488     }
5489   }
5490
5491   if (N0.getOpcode() == ISD::SETCC) {
5492     if (!LegalOperations && VT.isVector() &&
5493         N0.getValueType().getVectorElementType() == MVT::i1) {
5494       EVT N0VT = N0.getOperand(0).getValueType();
5495       if (getSetCCResultType(N0VT) == N0.getValueType())
5496         return SDValue();
5497
5498       // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
5499       // Only do this before legalize for now.
5500       EVT EltVT = VT.getVectorElementType();
5501       SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
5502                                     DAG.getConstant(1, EltVT));
5503       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5504         // We know that the # elements of the results is the same as the
5505         // # elements of the compare (and the # elements of the compare result
5506         // for that matter).  Check to see that they are the same size.  If so,
5507         // we know that the element size of the sext'd result matches the
5508         // element size of the compare operands.
5509         return DAG.getNode(ISD::AND, SDLoc(N), VT,
5510                            DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5511                                          N0.getOperand(1),
5512                                  cast<CondCodeSDNode>(N0.getOperand(2))->get()),
5513                            DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT,
5514                                        OneOps));
5515
5516       // If the desired elements are smaller or larger than the source
5517       // elements we can use a matching integer vector type and then
5518       // truncate/sign extend
5519       EVT MatchingElementType =
5520         EVT::getIntegerVT(*DAG.getContext(),
5521                           N0VT.getScalarType().getSizeInBits());
5522       EVT MatchingVectorType =
5523         EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
5524                          N0VT.getVectorNumElements());
5525       SDValue VsetCC =
5526         DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5527                       N0.getOperand(1),
5528                       cast<CondCodeSDNode>(N0.getOperand(2))->get());
5529       return DAG.getNode(ISD::AND, SDLoc(N), VT,
5530                          DAG.getSExtOrTrunc(VsetCC, SDLoc(N), VT),
5531                          DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, OneOps));
5532     }
5533
5534     // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5535     SDValue SCC =
5536       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5537                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5538                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5539     if (SCC.getNode()) return SCC;
5540   }
5541
5542   // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
5543   if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
5544       isa<ConstantSDNode>(N0.getOperand(1)) &&
5545       N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
5546       N0.hasOneUse()) {
5547     SDValue ShAmt = N0.getOperand(1);
5548     unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
5549     if (N0.getOpcode() == ISD::SHL) {
5550       SDValue InnerZExt = N0.getOperand(0);
5551       // If the original shl may be shifting out bits, do not perform this
5552       // transformation.
5553       unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
5554         InnerZExt.getOperand(0).getValueType().getSizeInBits();
5555       if (ShAmtVal > KnownZeroBits)
5556         return SDValue();
5557     }
5558
5559     SDLoc DL(N);
5560
5561     // Ensure that the shift amount is wide enough for the shifted value.
5562     if (VT.getSizeInBits() >= 256)
5563       ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
5564
5565     return DAG.getNode(N0.getOpcode(), DL, VT,
5566                        DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
5567                        ShAmt);
5568   }
5569
5570   return SDValue();
5571 }
5572
5573 SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
5574   SDValue N0 = N->getOperand(0);
5575   EVT VT = N->getValueType(0);
5576
5577   if (SDNode *Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes,
5578                                               LegalOperations))
5579     return SDValue(Res, 0);
5580
5581   // fold (aext (aext x)) -> (aext x)
5582   // fold (aext (zext x)) -> (zext x)
5583   // fold (aext (sext x)) -> (sext x)
5584   if (N0.getOpcode() == ISD::ANY_EXTEND  ||
5585       N0.getOpcode() == ISD::ZERO_EXTEND ||
5586       N0.getOpcode() == ISD::SIGN_EXTEND)
5587     return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
5588
5589   // fold (aext (truncate (load x))) -> (aext (smaller load x))
5590   // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
5591   if (N0.getOpcode() == ISD::TRUNCATE) {
5592     SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
5593     if (NarrowLoad.getNode()) {
5594       SDNode* oye = N0.getNode()->getOperand(0).getNode();
5595       if (NarrowLoad.getNode() != N0.getNode()) {
5596         CombineTo(N0.getNode(), NarrowLoad);
5597         // CombineTo deleted the truncate, if needed, but not what's under it.
5598         AddToWorklist(oye);
5599       }
5600       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5601     }
5602   }
5603
5604   // fold (aext (truncate x))
5605   if (N0.getOpcode() == ISD::TRUNCATE) {
5606     SDValue TruncOp = N0.getOperand(0);
5607     if (TruncOp.getValueType() == VT)
5608       return TruncOp; // x iff x size == zext size.
5609     if (TruncOp.getValueType().bitsGT(VT))
5610       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, TruncOp);
5611     return DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, TruncOp);
5612   }
5613
5614   // Fold (aext (and (trunc x), cst)) -> (and x, cst)
5615   // if the trunc is not free.
5616   if (N0.getOpcode() == ISD::AND &&
5617       N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
5618       N0.getOperand(1).getOpcode() == ISD::Constant &&
5619       !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
5620                           N0.getValueType())) {
5621     SDValue X = N0.getOperand(0).getOperand(0);
5622     if (X.getValueType().bitsLT(VT)) {
5623       X = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N), VT, X);
5624     } else if (X.getValueType().bitsGT(VT)) {
5625       X = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, X);
5626     }
5627     APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
5628     Mask = Mask.zext(VT.getSizeInBits());
5629     return DAG.getNode(ISD::AND, SDLoc(N), VT,
5630                        X, DAG.getConstant(Mask, VT));
5631   }
5632
5633   // fold (aext (load x)) -> (aext (truncate (extload x)))
5634   // None of the supported targets knows how to perform load and any_ext
5635   // on vectors in one instruction.  We only perform this transformation on
5636   // scalars.
5637   if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
5638       ISD::isUNINDEXEDLoad(N0.getNode()) &&
5639       TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
5640     bool DoXform = true;
5641     SmallVector<SDNode*, 4> SetCCs;
5642     if (!N0.hasOneUse())
5643       DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
5644     if (DoXform) {
5645       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5646       SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
5647                                        LN0->getChain(),
5648                                        LN0->getBasePtr(), N0.getValueType(),
5649                                        LN0->getMemOperand());
5650       CombineTo(N, ExtLoad);
5651       SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5652                                   N0.getValueType(), ExtLoad);
5653       CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
5654       ExtendSetCCUses(SetCCs, Trunc, ExtLoad, SDLoc(N),
5655                       ISD::ANY_EXTEND);
5656       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5657     }
5658   }
5659
5660   // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
5661   // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
5662   // fold (aext ( extload x)) -> (aext (truncate (extload  x)))
5663   if (N0.getOpcode() == ISD::LOAD &&
5664       !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
5665       N0.hasOneUse()) {
5666     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5667     ISD::LoadExtType ExtType = LN0->getExtensionType();
5668     EVT MemVT = LN0->getMemoryVT();
5669     if (!LegalOperations || TLI.isLoadExtLegal(ExtType, MemVT)) {
5670       SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
5671                                        VT, LN0->getChain(), LN0->getBasePtr(),
5672                                        MemVT, LN0->getMemOperand());
5673       CombineTo(N, ExtLoad);
5674       CombineTo(N0.getNode(),
5675                 DAG.getNode(ISD::TRUNCATE, SDLoc(N0),
5676                             N0.getValueType(), ExtLoad),
5677                 ExtLoad.getValue(1));
5678       return SDValue(N, 0);   // Return N so it doesn't get rechecked!
5679     }
5680   }
5681
5682   if (N0.getOpcode() == ISD::SETCC) {
5683     // For vectors:
5684     // aext(setcc) -> vsetcc
5685     // aext(setcc) -> truncate(vsetcc)
5686     // aext(setcc) -> aext(vsetcc)
5687     // Only do this before legalize for now.
5688     if (VT.isVector() && !LegalOperations) {
5689       EVT N0VT = N0.getOperand(0).getValueType();
5690         // We know that the # elements of the results is the same as the
5691         // # elements of the compare (and the # elements of the compare result
5692         // for that matter).  Check to see that they are the same size.  If so,
5693         // we know that the element size of the sext'd result matches the
5694         // element size of the compare operands.
5695       if (VT.getSizeInBits() == N0VT.getSizeInBits())
5696         return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
5697                              N0.getOperand(1),
5698                              cast<CondCodeSDNode>(N0.getOperand(2))->get());
5699       // If the desired elements are smaller or larger than the source
5700       // elements we can use a matching integer vector type and then
5701       // truncate/any extend
5702       else {
5703         EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
5704         SDValue VsetCC =
5705           DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
5706                         N0.getOperand(1),
5707                         cast<CondCodeSDNode>(N0.getOperand(2))->get());
5708         return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
5709       }
5710     }
5711
5712     // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
5713     SDValue SCC =
5714       SimplifySelectCC(SDLoc(N), N0.getOperand(0), N0.getOperand(1),
5715                        DAG.getConstant(1, VT), DAG.getConstant(0, VT),
5716                        cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
5717     if (SCC.getNode())
5718       return SCC;
5719   }
5720
5721   return SDValue();
5722 }
5723
5724 /// See if the specified operand can be simplified with the knowledge that only
5725 /// the bits specified by Mask are used.  If so, return the simpler operand,
5726 /// otherwise return a null SDValue.
5727 SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
5728   switch (V.getOpcode()) {
5729   default: break;
5730   case ISD::Constant: {
5731     const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
5732     assert(CV && "Const value should be ConstSDNode.");
5733     const APInt &CVal = CV->getAPIntValue();
5734     APInt NewVal = CVal & Mask;
5735     if (NewVal != CVal)
5736       return DAG.getConstant(NewVal, V.getValueType());
5737     break;
5738   }
5739   case ISD::OR:
5740   case ISD::XOR:
5741     // If the LHS or RHS don't contribute bits to the or, drop them.
5742     if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
5743       return V.getOperand(1);
5744     if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
5745       return V.getOperand(0);
5746     break;
5747   case ISD::SRL:
5748     // Only look at single-use SRLs.
5749     if (!V.getNode()->hasOneUse())
5750       break;
5751     if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
5752       // See if we can recursively simplify the LHS.
5753       unsigned Amt = RHSC->getZExtValue();
5754
5755       // Watch out for shift count overflow though.
5756       if (Amt >= Mask.getBitWidth()) break;
5757       APInt NewMask = Mask << Amt;
5758       SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
5759       if (SimplifyLHS.getNode())
5760         return DAG.getNode(ISD::SRL, SDLoc(V), V.getValueType(),
5761                            SimplifyLHS, V.getOperand(1));
5762     }
5763   }
5764   return SDValue();
5765 }
5766
5767 /// If the result of a wider load is shifted to right of N  bits and then
5768 /// truncated to a narrower type and where N is a multiple of number of bits of
5769 /// the narrower type, transform it to a narrower load from address + N / num of
5770 /// bits of new type. If the result is to be extended, also fold the extension
5771 /// to form a extending load.
5772 SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
5773   unsigned Opc = N->getOpcode();
5774
5775   ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
5776   SDValue N0 = N->getOperand(0);
5777   EVT VT = N->getValueType(0);
5778   EVT ExtVT = VT;
5779
5780   // This transformation isn't valid for vector loads.
5781   if (VT.isVector())
5782     return SDValue();
5783
5784   // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
5785   // extended to VT.
5786   if (Opc == ISD::SIGN_EXTEND_INREG) {
5787     ExtType = ISD::SEXTLOAD;
5788     ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
5789   } else if (Opc == ISD::SRL) {
5790     // Another special-case: SRL is basically zero-extending a narrower value.
5791     ExtType = ISD::ZEXTLOAD;
5792     N0 = SDValue(N, 0);
5793     ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
5794     if (!N01) return SDValue();
5795     ExtVT = EVT::getIntegerVT(*DAG.getContext(),
5796                               VT.getSizeInBits() - N01->getZExtValue());
5797   }
5798   if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
5799     return SDValue();
5800
5801   unsigned EVTBits = ExtVT.getSizeInBits();
5802
5803   // Do not generate loads of non-round integer types since these can
5804   // be expensive (and would be wrong if the type is not byte sized).
5805   if (!ExtVT.isRound())
5806     return SDValue();
5807
5808   unsigned ShAmt = 0;
5809   if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
5810     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5811       ShAmt = N01->getZExtValue();
5812       // Is the shift amount a multiple of size of VT?
5813       if ((ShAmt & (EVTBits-1)) == 0) {
5814         N0 = N0.getOperand(0);
5815         // Is the load width a multiple of size of VT?
5816         if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
5817           return SDValue();
5818       }
5819
5820       // At this point, we must have a load or else we can't do the transform.
5821       if (!isa<LoadSDNode>(N0)) return SDValue();
5822
5823       // Because a SRL must be assumed to *need* to zero-extend the high bits
5824       // (as opposed to anyext the high bits), we can't combine the zextload
5825       // lowering of SRL and an sextload.
5826       if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
5827         return SDValue();
5828
5829       // If the shift amount is larger than the input type then we're not
5830       // accessing any of the loaded bytes.  If the load was a zextload/extload
5831       // then the result of the shift+trunc is zero/undef (handled elsewhere).
5832       if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
5833         return SDValue();
5834     }
5835   }
5836
5837   // If the load is shifted left (and the result isn't shifted back right),
5838   // we can fold the truncate through the shift.
5839   unsigned ShLeftAmt = 0;
5840   if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
5841       ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
5842     if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
5843       ShLeftAmt = N01->getZExtValue();
5844       N0 = N0.getOperand(0);
5845     }
5846   }
5847
5848   // If we haven't found a load, we can't narrow it.  Don't transform one with
5849   // multiple uses, this would require adding a new load.
5850   if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
5851     return SDValue();
5852
5853   // Don't change the width of a volatile load.
5854   LoadSDNode *LN0 = cast<LoadSDNode>(N0);
5855   if (LN0->isVolatile())
5856     return SDValue();
5857
5858   // Verify that we are actually reducing a load width here.
5859   if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
5860     return SDValue();
5861
5862   // For the transform to be legal, the load must produce only two values
5863   // (the value loaded and the chain).  Don't transform a pre-increment
5864   // load, for example, which produces an extra value.  Otherwise the
5865   // transformation is not equivalent, and the downstream logic to replace
5866   // uses gets things wrong.
5867   if (LN0->getNumValues() > 2)
5868     return SDValue();
5869
5870   // If the load that we're shrinking is an extload and we're not just
5871   // discarding the extension we can't simply shrink the load. Bail.
5872   // TODO: It would be possible to merge the extensions in some cases.
5873   if (LN0->getExtensionType() != ISD::NON_EXTLOAD &&
5874       LN0->getMemoryVT().getSizeInBits() < ExtVT.getSizeInBits() + ShAmt)
5875     return SDValue();
5876
5877   EVT PtrType = N0.getOperand(1).getValueType();
5878
5879   if (PtrType == MVT::Untyped || PtrType.isExtended())
5880     // It's not possible to generate a constant of extended or untyped type.
5881     return SDValue();
5882
5883   // For big endian targets, we need to adjust the offset to the pointer to
5884   // load the correct bytes.
5885   if (TLI.isBigEndian()) {
5886     unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
5887     unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
5888     ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
5889   }
5890
5891   uint64_t PtrOff = ShAmt / 8;
5892   unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
5893   SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LN0),
5894                                PtrType, LN0->getBasePtr(),
5895                                DAG.getConstant(PtrOff, PtrType));
5896   AddToWorklist(NewPtr.getNode());
5897
5898   SDValue Load;
5899   if (ExtType == ISD::NON_EXTLOAD)
5900     Load =  DAG.getLoad(VT, SDLoc(N0), LN0->getChain(), NewPtr,
5901                         LN0->getPointerInfo().getWithOffset(PtrOff),
5902                         LN0->isVolatile(), LN0->isNonTemporal(),
5903                         LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5904   else
5905     Load = DAG.getExtLoad(ExtType, SDLoc(N0), VT, LN0->getChain(),NewPtr,
5906                           LN0->getPointerInfo().getWithOffset(PtrOff),
5907                           ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
5908                           LN0->isInvariant(), NewAlign, LN0->getAAInfo());
5909
5910   // Replace the old load's chain with the new load's chain.
5911   WorklistRemover DeadNodes(*this);
5912   DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
5913
5914   // Shift the result left, if we've swallowed a left shift.
5915   SDValue Result = Load;
5916   if (ShLeftAmt != 0) {
5917     EVT ShImmTy = getShiftAmountTy(Result.getValueType());
5918     if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
5919       ShImmTy = VT;
5920     // If the shift amount is as large as the result size (but, presumably,
5921     // no larger than the source) then the useful bits of the result are
5922     // zero; we can't simply return the shortened shift, because the result
5923     // of that operation is undefined.
5924     if (ShLeftAmt >= VT.getSizeInBits())
5925       Result = DAG.getConstant(0, VT);
5926     else
5927       Result = DAG.getNode(ISD::SHL, SDLoc(N0), VT,
5928                           Result, DAG.getConstant(ShLeftAmt, ShImmTy));
5929   }
5930
5931   // Return the new loaded value.
5932   return Result;
5933 }
5934
5935 SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
5936   SDValue N0 = N->getOperand(0);
5937   SDValue N1 = N->getOperand(1);
5938   EVT VT = N->getValueType(0);
5939   EVT EVT = cast<VTSDNode>(N1)->getVT();
5940   unsigned VTBits = VT.getScalarType().getSizeInBits();
5941   unsigned EVTBits = EVT.getScalarType().getSizeInBits();
5942
5943   // fold (sext_in_reg c1) -> c1
5944   if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
5945     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
5946
5947   // If the input is already sign extended, just drop the extension.
5948   if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
5949     return N0;
5950
5951   // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
5952   if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
5953       EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
5954     return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
5955                        N0.getOperand(0), N1);
5956
5957   // fold (sext_in_reg (sext x)) -> (sext x)
5958   // fold (sext_in_reg (aext x)) -> (sext x)
5959   // if x is small enough.
5960   if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
5961     SDValue N00 = N0.getOperand(0);
5962     if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
5963         (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
5964       return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
5965   }
5966
5967   // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
5968   if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
5969     return DAG.getZeroExtendInReg(N0, SDLoc(N), EVT);
5970
5971   // fold operands of sext_in_reg based on knowledge that the top bits are not
5972   // demanded.
5973   if (SimplifyDemandedBits(SDValue(N, 0)))
5974     return SDValue(N, 0);
5975
5976   // fold (sext_in_reg (load x)) -> (smaller sextload x)
5977   // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
5978   SDValue NarrowLoad = ReduceLoadWidth(N);
5979   if (NarrowLoad.getNode())
5980     return NarrowLoad;
5981
5982   // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
5983   // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
5984   // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
5985   if (N0.getOpcode() == ISD::SRL) {
5986     if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
5987       if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
5988         // We can turn this into an SRA iff the input to the SRL is already sign
5989         // extended enough.
5990         unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
5991         if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
5992           return DAG.getNode(ISD::SRA, SDLoc(N), VT,
5993                              N0.getOperand(0), N0.getOperand(1));
5994       }
5995   }
5996
5997   // fold (sext_inreg (extload x)) -> (sextload x)
5998   if (ISD::isEXTLoad(N0.getNode()) &&
5999       ISD::isUNINDEXEDLoad(N0.getNode()) &&
6000       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6001       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6002        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6003     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6004     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6005                                      LN0->getChain(),
6006                                      LN0->getBasePtr(), EVT,
6007                                      LN0->getMemOperand());
6008     CombineTo(N, ExtLoad);
6009     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6010     AddToWorklist(ExtLoad.getNode());
6011     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6012   }
6013   // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
6014   if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
6015       N0.hasOneUse() &&
6016       EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
6017       ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
6018        TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
6019     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6020     SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
6021                                      LN0->getChain(),
6022                                      LN0->getBasePtr(), EVT,
6023                                      LN0->getMemOperand());
6024     CombineTo(N, ExtLoad);
6025     CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
6026     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
6027   }
6028
6029   // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
6030   if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
6031     SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
6032                                        N0.getOperand(1), false);
6033     if (BSwap.getNode())
6034       return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
6035                          BSwap, N1);
6036   }
6037
6038   // Fold a sext_inreg of a build_vector of ConstantSDNodes or undefs
6039   // into a build_vector.
6040   if (ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
6041     SmallVector<SDValue, 8> Elts;
6042     unsigned NumElts = N0->getNumOperands();
6043     unsigned ShAmt = VTBits - EVTBits;
6044
6045     for (unsigned i = 0; i != NumElts; ++i) {
6046       SDValue Op = N0->getOperand(i);
6047       if (Op->getOpcode() == ISD::UNDEF) {
6048         Elts.push_back(Op);
6049         continue;
6050       }
6051
6052       ConstantSDNode *CurrentND = cast<ConstantSDNode>(Op);
6053       const APInt &C = APInt(VTBits, CurrentND->getAPIntValue().getZExtValue());
6054       Elts.push_back(DAG.getConstant(C.shl(ShAmt).ashr(ShAmt).getZExtValue(),
6055                                      Op.getValueType()));
6056     }
6057
6058     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Elts);
6059   }
6060
6061   return SDValue();
6062 }
6063
6064 SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
6065   SDValue N0 = N->getOperand(0);
6066   EVT VT = N->getValueType(0);
6067   bool isLE = TLI.isLittleEndian();
6068
6069   // noop truncate
6070   if (N0.getValueType() == N->getValueType(0))
6071     return N0;
6072   // fold (truncate c1) -> c1
6073   if (isa<ConstantSDNode>(N0))
6074     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
6075   // fold (truncate (truncate x)) -> (truncate x)
6076   if (N0.getOpcode() == ISD::TRUNCATE)
6077     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6078   // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
6079   if (N0.getOpcode() == ISD::ZERO_EXTEND ||
6080       N0.getOpcode() == ISD::SIGN_EXTEND ||
6081       N0.getOpcode() == ISD::ANY_EXTEND) {
6082     if (N0.getOperand(0).getValueType().bitsLT(VT))
6083       // if the source is smaller than the dest, we still need an extend
6084       return DAG.getNode(N0.getOpcode(), SDLoc(N), VT,
6085                          N0.getOperand(0));
6086     if (N0.getOperand(0).getValueType().bitsGT(VT))
6087       // if the source is larger than the dest, than we just need the truncate
6088       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
6089     // if the source and dest are the same type, we can drop both the extend
6090     // and the truncate.
6091     return N0.getOperand(0);
6092   }
6093
6094   // Fold extract-and-trunc into a narrow extract. For example:
6095   //   i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
6096   //   i32 y = TRUNCATE(i64 x)
6097   //        -- becomes --
6098   //   v16i8 b = BITCAST (v2i64 val)
6099   //   i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
6100   //
6101   // Note: We only run this optimization after type legalization (which often
6102   // creates this pattern) and before operation legalization after which
6103   // we need to be more careful about the vector instructions that we generate.
6104   if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
6105       LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
6106
6107     EVT VecTy = N0.getOperand(0).getValueType();
6108     EVT ExTy = N0.getValueType();
6109     EVT TrTy = N->getValueType(0);
6110
6111     unsigned NumElem = VecTy.getVectorNumElements();
6112     unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
6113
6114     EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
6115     assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
6116
6117     SDValue EltNo = N0->getOperand(1);
6118     if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
6119       int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
6120       EVT IndexTy = TLI.getVectorIdxTy();
6121       int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
6122
6123       SDValue V = DAG.getNode(ISD::BITCAST, SDLoc(N),
6124                               NVT, N0.getOperand(0));
6125
6126       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
6127                          SDLoc(N), TrTy, V,
6128                          DAG.getConstant(Index, IndexTy));
6129     }
6130   }
6131
6132   // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
6133   if (N0.getOpcode() == ISD::SELECT) {
6134     EVT SrcVT = N0.getValueType();
6135     if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
6136         TLI.isTruncateFree(SrcVT, VT)) {
6137       SDLoc SL(N0);
6138       SDValue Cond = N0.getOperand(0);
6139       SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
6140       SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
6141       return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
6142     }
6143   }
6144
6145   // Fold a series of buildvector, bitcast, and truncate if possible.
6146   // For example fold
6147   //   (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
6148   //   (2xi32 (buildvector x, y)).
6149   if (Level == AfterLegalizeVectorOps && VT.isVector() &&
6150       N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
6151       N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
6152       N0.getOperand(0).hasOneUse()) {
6153
6154     SDValue BuildVect = N0.getOperand(0);
6155     EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
6156     EVT TruncVecEltTy = VT.getVectorElementType();
6157
6158     // Check that the element types match.
6159     if (BuildVectEltTy == TruncVecEltTy) {
6160       // Now we only need to compute the offset of the truncated elements.
6161       unsigned BuildVecNumElts =  BuildVect.getNumOperands();
6162       unsigned TruncVecNumElts = VT.getVectorNumElements();
6163       unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
6164
6165       assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
6166              "Invalid number of elements");
6167
6168       SmallVector<SDValue, 8> Opnds;
6169       for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
6170         Opnds.push_back(BuildVect.getOperand(i));
6171
6172       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
6173     }
6174   }
6175
6176   // See if we can simplify the input to this truncate through knowledge that
6177   // only the low bits are being used.
6178   // For example "trunc (or (shl x, 8), y)" // -> trunc y
6179   // Currently we only perform this optimization on scalars because vectors
6180   // may have different active low bits.
6181   if (!VT.isVector()) {
6182     SDValue Shorter =
6183       GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
6184                                                VT.getSizeInBits()));
6185     if (Shorter.getNode())
6186       return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
6187   }
6188   // fold (truncate (load x)) -> (smaller load x)
6189   // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
6190   if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
6191     SDValue Reduced = ReduceLoadWidth(N);
6192     if (Reduced.getNode())
6193       return Reduced;
6194     // Handle the case where the load remains an extending load even
6195     // after truncation.
6196     if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
6197       LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6198       if (!LN0->isVolatile() &&
6199           LN0->getMemoryVT().getStoreSizeInBits() < VT.getSizeInBits()) {
6200         SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
6201                                          VT, LN0->getChain(), LN0->getBasePtr(),
6202                                          LN0->getMemoryVT(),
6203                                          LN0->getMemOperand());
6204         DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
6205         return NewLoad;
6206       }
6207     }
6208   }
6209   // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
6210   // where ... are all 'undef'.
6211   if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
6212     SmallVector<EVT, 8> VTs;
6213     SDValue V;
6214     unsigned Idx = 0;
6215     unsigned NumDefs = 0;
6216
6217     for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
6218       SDValue X = N0.getOperand(i);
6219       if (X.getOpcode() != ISD::UNDEF) {
6220         V = X;
6221         Idx = i;
6222         NumDefs++;
6223       }
6224       // Stop if more than one members are non-undef.
6225       if (NumDefs > 1)
6226         break;
6227       VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
6228                                      VT.getVectorElementType(),
6229                                      X.getValueType().getVectorNumElements()));
6230     }
6231
6232     if (NumDefs == 0)
6233       return DAG.getUNDEF(VT);
6234
6235     if (NumDefs == 1) {
6236       assert(V.getNode() && "The single defined operand is empty!");
6237       SmallVector<SDValue, 8> Opnds;
6238       for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
6239         if (i != Idx) {
6240           Opnds.push_back(DAG.getUNDEF(VTs[i]));
6241           continue;
6242         }
6243         SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
6244         AddToWorklist(NV.getNode());
6245         Opnds.push_back(NV);
6246       }
6247       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
6248     }
6249   }
6250
6251   // Simplify the operands using demanded-bits information.
6252   if (!VT.isVector() &&
6253       SimplifyDemandedBits(SDValue(N, 0)))
6254     return SDValue(N, 0);
6255
6256   return SDValue();
6257 }
6258
6259 static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
6260   SDValue Elt = N->getOperand(i);
6261   if (Elt.getOpcode() != ISD::MERGE_VALUES)
6262     return Elt.getNode();
6263   return Elt.getOperand(Elt.getResNo()).getNode();
6264 }
6265
6266 /// build_pair (load, load) -> load
6267 /// if load locations are consecutive.
6268 SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
6269   assert(N->getOpcode() == ISD::BUILD_PAIR);
6270
6271   LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
6272   LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
6273   if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
6274       LD1->getAddressSpace() != LD2->getAddressSpace())
6275     return SDValue();
6276   EVT LD1VT = LD1->getValueType(0);
6277
6278   if (ISD::isNON_EXTLoad(LD2) &&
6279       LD2->hasOneUse() &&
6280       // If both are volatile this would reduce the number of volatile loads.
6281       // If one is volatile it might be ok, but play conservative and bail out.
6282       !LD1->isVolatile() &&
6283       !LD2->isVolatile() &&
6284       DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
6285     unsigned Align = LD1->getAlignment();
6286     unsigned NewAlign = TLI.getDataLayout()->
6287       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6288
6289     if (NewAlign <= Align &&
6290         (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
6291       return DAG.getLoad(VT, SDLoc(N), LD1->getChain(),
6292                          LD1->getBasePtr(), LD1->getPointerInfo(),
6293                          false, false, false, Align);
6294   }
6295
6296   return SDValue();
6297 }
6298
6299 SDValue DAGCombiner::visitBITCAST(SDNode *N) {
6300   SDValue N0 = N->getOperand(0);
6301   EVT VT = N->getValueType(0);
6302
6303   // If the input is a BUILD_VECTOR with all constant elements, fold this now.
6304   // Only do this before legalize, since afterward the target may be depending
6305   // on the bitconvert.
6306   // First check to see if this is all constant.
6307   if (!LegalTypes &&
6308       N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
6309       VT.isVector()) {
6310     bool isSimple = cast<BuildVectorSDNode>(N0)->isConstant();
6311
6312     EVT DestEltVT = N->getValueType(0).getVectorElementType();
6313     assert(!DestEltVT.isVector() &&
6314            "Element type of vector ValueType must not be vector!");
6315     if (isSimple)
6316       return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
6317   }
6318
6319   // If the input is a constant, let getNode fold it.
6320   if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
6321     SDValue Res = DAG.getNode(ISD::BITCAST, SDLoc(N), VT, N0);
6322     if (Res.getNode() != N) {
6323       if (!LegalOperations ||
6324           TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
6325         return Res;
6326
6327       // Folding it resulted in an illegal node, and it's too late to
6328       // do that. Clean up the old node and forego the transformation.
6329       // Ideally this won't happen very often, because instcombine
6330       // and the earlier dagcombine runs (where illegal nodes are
6331       // permitted) should have folded most of them already.
6332       deleteAndRecombine(Res.getNode());
6333     }
6334   }
6335
6336   // (conv (conv x, t1), t2) -> (conv x, t2)
6337   if (N0.getOpcode() == ISD::BITCAST)
6338     return DAG.getNode(ISD::BITCAST, SDLoc(N), VT,
6339                        N0.getOperand(0));
6340
6341   // fold (conv (load x)) -> (load (conv*)x)
6342   // If the resultant load doesn't need a higher alignment than the original!
6343   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
6344       // Do not change the width of a volatile load.
6345       !cast<LoadSDNode>(N0)->isVolatile() &&
6346       // Do not remove the cast if the types differ in endian layout.
6347       TLI.hasBigEndianPartOrdering(N0.getValueType()) ==
6348       TLI.hasBigEndianPartOrdering(VT) &&
6349       (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
6350       TLI.isLoadBitCastBeneficial(N0.getValueType(), VT)) {
6351     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
6352     unsigned Align = TLI.getDataLayout()->
6353       getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
6354     unsigned OrigAlign = LN0->getAlignment();
6355
6356     if (Align <= OrigAlign) {
6357       SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(),
6358                                  LN0->getBasePtr(), LN0->getPointerInfo(),
6359                                  LN0->isVolatile(), LN0->isNonTemporal(),
6360                                  LN0->isInvariant(), OrigAlign,
6361                                  LN0->getAAInfo());
6362       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
6363       return Load;
6364     }
6365   }
6366
6367   // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
6368   // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
6369   // This often reduces constant pool loads.
6370   if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
6371        (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
6372       N0.getNode()->hasOneUse() && VT.isInteger() &&
6373       !VT.isVector() && !N0.getValueType().isVector()) {
6374     SDValue NewConv = DAG.getNode(ISD::BITCAST, SDLoc(N0), VT,
6375                                   N0.getOperand(0));
6376     AddToWorklist(NewConv.getNode());
6377
6378     APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6379     if (N0.getOpcode() == ISD::FNEG)
6380       return DAG.getNode(ISD::XOR, SDLoc(N), VT,
6381                          NewConv, DAG.getConstant(SignBit, VT));
6382     assert(N0.getOpcode() == ISD::FABS);
6383     return DAG.getNode(ISD::AND, SDLoc(N), VT,
6384                        NewConv, DAG.getConstant(~SignBit, VT));
6385   }
6386
6387   // fold (bitconvert (fcopysign cst, x)) ->
6388   //         (or (and (bitconvert x), sign), (and cst, (not sign)))
6389   // Note that we don't handle (copysign x, cst) because this can always be
6390   // folded to an fneg or fabs.
6391   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
6392       isa<ConstantFPSDNode>(N0.getOperand(0)) &&
6393       VT.isInteger() && !VT.isVector()) {
6394     unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
6395     EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
6396     if (isTypeLegal(IntXVT)) {
6397       SDValue X = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6398                               IntXVT, N0.getOperand(1));
6399       AddToWorklist(X.getNode());
6400
6401       // If X has a different width than the result/lhs, sext it or truncate it.
6402       unsigned VTWidth = VT.getSizeInBits();
6403       if (OrigXWidth < VTWidth) {
6404         X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
6405         AddToWorklist(X.getNode());
6406       } else if (OrigXWidth > VTWidth) {
6407         // To get the sign bit in the right place, we have to shift it right
6408         // before truncating.
6409         X = DAG.getNode(ISD::SRL, SDLoc(X),
6410                         X.getValueType(), X,
6411                         DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
6412         AddToWorklist(X.getNode());
6413         X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
6414         AddToWorklist(X.getNode());
6415       }
6416
6417       APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
6418       X = DAG.getNode(ISD::AND, SDLoc(X), VT,
6419                       X, DAG.getConstant(SignBit, VT));
6420       AddToWorklist(X.getNode());
6421
6422       SDValue Cst = DAG.getNode(ISD::BITCAST, SDLoc(N0),
6423                                 VT, N0.getOperand(0));
6424       Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
6425                         Cst, DAG.getConstant(~SignBit, VT));
6426       AddToWorklist(Cst.getNode());
6427
6428       return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
6429     }
6430   }
6431
6432   // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
6433   if (N0.getOpcode() == ISD::BUILD_PAIR) {
6434     SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
6435     if (CombineLD.getNode())
6436       return CombineLD;
6437   }
6438
6439   return SDValue();
6440 }
6441
6442 SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
6443   EVT VT = N->getValueType(0);
6444   return CombineConsecutiveLoads(N, VT);
6445 }
6446
6447 /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
6448 /// operands. DstEltVT indicates the destination element value type.
6449 SDValue DAGCombiner::
6450 ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
6451   EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
6452
6453   // If this is already the right type, we're done.
6454   if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
6455
6456   unsigned SrcBitSize = SrcEltVT.getSizeInBits();
6457   unsigned DstBitSize = DstEltVT.getSizeInBits();
6458
6459   // If this is a conversion of N elements of one type to N elements of another
6460   // type, convert each element.  This handles FP<->INT cases.
6461   if (SrcBitSize == DstBitSize) {
6462     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6463                               BV->getValueType(0).getVectorNumElements());
6464
6465     // Due to the FP element handling below calling this routine recursively,
6466     // we can end up with a scalar-to-vector node here.
6467     if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
6468       return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6469                          DAG.getNode(ISD::BITCAST, SDLoc(BV),
6470                                      DstEltVT, BV->getOperand(0)));
6471
6472     SmallVector<SDValue, 8> Ops;
6473     for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6474       SDValue Op = BV->getOperand(i);
6475       // If the vector element type is not legal, the BUILD_VECTOR operands
6476       // are promoted and implicitly truncated.  Make that explicit here.
6477       if (Op.getValueType() != SrcEltVT)
6478         Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
6479       Ops.push_back(DAG.getNode(ISD::BITCAST, SDLoc(BV),
6480                                 DstEltVT, Op));
6481       AddToWorklist(Ops.back().getNode());
6482     }
6483     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6484   }
6485
6486   // Otherwise, we're growing or shrinking the elements.  To avoid having to
6487   // handle annoying details of growing/shrinking FP values, we convert them to
6488   // int first.
6489   if (SrcEltVT.isFloatingPoint()) {
6490     // Convert the input float vector to a int vector where the elements are the
6491     // same sizes.
6492     assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
6493     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
6494     BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
6495     SrcEltVT = IntVT;
6496   }
6497
6498   // Now we know the input is an integer vector.  If the output is a FP type,
6499   // convert to integer first, then to FP of the right size.
6500   if (DstEltVT.isFloatingPoint()) {
6501     assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
6502     EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
6503     SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
6504
6505     // Next, convert to FP elements of the same size.
6506     return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
6507   }
6508
6509   // Okay, we know the src/dst types are both integers of differing types.
6510   // Handling growing first.
6511   assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
6512   if (SrcBitSize < DstBitSize) {
6513     unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
6514
6515     SmallVector<SDValue, 8> Ops;
6516     for (unsigned i = 0, e = BV->getNumOperands(); i != e;
6517          i += NumInputsPerOutput) {
6518       bool isLE = TLI.isLittleEndian();
6519       APInt NewBits = APInt(DstBitSize, 0);
6520       bool EltIsUndef = true;
6521       for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
6522         // Shift the previously computed bits over.
6523         NewBits <<= SrcBitSize;
6524         SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
6525         if (Op.getOpcode() == ISD::UNDEF) continue;
6526         EltIsUndef = false;
6527
6528         NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
6529                    zextOrTrunc(SrcBitSize).zext(DstBitSize);
6530       }
6531
6532       if (EltIsUndef)
6533         Ops.push_back(DAG.getUNDEF(DstEltVT));
6534       else
6535         Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
6536     }
6537
6538     EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
6539     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6540   }
6541
6542   // Finally, this must be the case where we are shrinking elements: each input
6543   // turns into multiple outputs.
6544   bool isS2V = ISD::isScalarToVector(BV);
6545   unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
6546   EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
6547                             NumOutputsPerInput*BV->getNumOperands());
6548   SmallVector<SDValue, 8> Ops;
6549
6550   for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
6551     if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
6552       for (unsigned j = 0; j != NumOutputsPerInput; ++j)
6553         Ops.push_back(DAG.getUNDEF(DstEltVT));
6554       continue;
6555     }
6556
6557     APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
6558                   getAPIntValue().zextOrTrunc(SrcBitSize);
6559
6560     for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
6561       APInt ThisVal = OpVal.trunc(DstBitSize);
6562       Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
6563       if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
6564         // Simply turn this into a SCALAR_TO_VECTOR of the new type.
6565         return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(BV), VT,
6566                            Ops[0]);
6567       OpVal = OpVal.lshr(DstBitSize);
6568     }
6569
6570     // For big endian targets, swap the order of the pieces of each element.
6571     if (TLI.isBigEndian())
6572       std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
6573   }
6574
6575   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(BV), VT, Ops);
6576 }
6577
6578 SDValue DAGCombiner::visitFADD(SDNode *N) {
6579   SDValue N0 = N->getOperand(0);
6580   SDValue N1 = N->getOperand(1);
6581   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6582   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6583   EVT VT = N->getValueType(0);
6584   const TargetOptions &Options = DAG.getTarget().Options;
6585
6586   // fold vector ops
6587   if (VT.isVector()) {
6588     SDValue FoldedVOp = SimplifyVBinOp(N);
6589     if (FoldedVOp.getNode()) return FoldedVOp;
6590   }
6591
6592   // fold (fadd c1, c2) -> c1 + c2
6593   if (N0CFP && N1CFP)
6594     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N1);
6595
6596   // canonicalize constant to RHS
6597   if (N0CFP && !N1CFP)
6598     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N0);
6599
6600   // fold (fadd A, (fneg B)) -> (fsub A, B)
6601   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6602       isNegatibleForFree(N1, LegalOperations, TLI, &Options) == 2)
6603     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0,
6604                        GetNegatedExpression(N1, DAG, LegalOperations));
6605
6606   // fold (fadd (fneg A), B) -> (fsub B, A)
6607   if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
6608       isNegatibleForFree(N0, LegalOperations, TLI, &Options) == 2)
6609     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N1,
6610                        GetNegatedExpression(N0, DAG, LegalOperations));
6611
6612   // If 'unsafe math' is enabled, fold lots of things.
6613   if (Options.UnsafeFPMath) {
6614     // No FP constant should be created after legalization as Instruction
6615     // Selection pass has a hard time dealing with FP constants.
6616     bool AllowNewConst = (Level < AfterLegalizeDAG);
6617
6618     // fold (fadd A, 0) -> A
6619     if (N1CFP && N1CFP->getValueAPF().isZero())
6620       return N0;
6621
6622     // fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
6623     if (N1CFP && N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
6624         isa<ConstantFPSDNode>(N0.getOperand(1)))
6625       return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0.getOperand(0),
6626                          DAG.getNode(ISD::FADD, SDLoc(N), VT,
6627                                      N0.getOperand(1), N1));
6628
6629     // If allowed, fold (fadd (fneg x), x) -> 0.0
6630     if (AllowNewConst && N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
6631       return DAG.getConstantFP(0.0, VT);
6632
6633     // If allowed, fold (fadd x, (fneg x)) -> 0.0
6634     if (AllowNewConst && N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
6635       return DAG.getConstantFP(0.0, VT);
6636
6637     // We can fold chains of FADD's of the same value into multiplications.
6638     // This transform is not safe in general because we are reducing the number
6639     // of rounding steps.
6640     if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
6641       if (N0.getOpcode() == ISD::FMUL) {
6642         ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6643         ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
6644
6645         // (fadd (fmul x, c), x) -> (fmul x, c+1)
6646         if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
6647           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6648                                        SDValue(CFP01, 0),
6649                                        DAG.getConstantFP(1.0, VT));
6650           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, NewCFP);
6651         }
6652
6653         // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
6654         if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
6655             N1.getOperand(0) == N1.getOperand(1) &&
6656             N0.getOperand(0) == N1.getOperand(0)) {
6657           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6658                                        SDValue(CFP01, 0),
6659                                        DAG.getConstantFP(2.0, VT));
6660           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6661                              N0.getOperand(0), NewCFP);
6662         }
6663       }
6664
6665       if (N1.getOpcode() == ISD::FMUL) {
6666         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6667         ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
6668
6669         // (fadd x, (fmul x, c)) -> (fmul x, c+1)
6670         if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
6671           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6672                                        SDValue(CFP11, 0),
6673                                        DAG.getConstantFP(1.0, VT));
6674           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, NewCFP);
6675         }
6676
6677         // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
6678         if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
6679             N0.getOperand(0) == N0.getOperand(1) &&
6680             N1.getOperand(0) == N0.getOperand(0)) {
6681           SDValue NewCFP = DAG.getNode(ISD::FADD, SDLoc(N), VT,
6682                                        SDValue(CFP11, 0),
6683                                        DAG.getConstantFP(2.0, VT));
6684           return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1.getOperand(0), NewCFP);
6685         }
6686       }
6687
6688       if (N0.getOpcode() == ISD::FADD && AllowNewConst) {
6689         ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
6690         // (fadd (fadd x, x), x) -> (fmul x, 3.0)
6691         if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
6692             (N0.getOperand(0) == N1))
6693           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6694                              N1, DAG.getConstantFP(3.0, VT));
6695       }
6696
6697       if (N1.getOpcode() == ISD::FADD && AllowNewConst) {
6698         ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
6699         // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
6700         if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
6701             N1.getOperand(0) == N0)
6702           return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6703                              N0, DAG.getConstantFP(3.0, VT));
6704       }
6705
6706       // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
6707       if (AllowNewConst &&
6708           N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
6709           N0.getOperand(0) == N0.getOperand(1) &&
6710           N1.getOperand(0) == N1.getOperand(1) &&
6711           N0.getOperand(0) == N1.getOperand(0))
6712         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6713                            N0.getOperand(0), DAG.getConstantFP(4.0, VT));
6714     }
6715   } // enable-unsafe-fp-math
6716
6717   // FADD -> FMA combines:
6718   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6719       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6720       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6721
6722     // fold (fadd (fmul x, y), z) -> (fma x, y, z)
6723     if (N0.getOpcode() == ISD::FMUL &&
6724         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6725       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6726                          N0.getOperand(0), N0.getOperand(1), N1);
6727
6728     // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
6729     // Note: Commutes FADD operands.
6730     if (N1.getOpcode() == ISD::FMUL &&
6731         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6732       return DAG.getNode(ISD::FMA, SDLoc(N), VT,
6733                          N1.getOperand(0), N1.getOperand(1), N0);
6734   }
6735
6736   return SDValue();
6737 }
6738
6739 SDValue DAGCombiner::visitFSUB(SDNode *N) {
6740   SDValue N0 = N->getOperand(0);
6741   SDValue N1 = N->getOperand(1);
6742   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6743   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6744   EVT VT = N->getValueType(0);
6745   SDLoc dl(N);
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 (fsub c1, c2) -> c1-c2
6755   if (N0CFP && N1CFP)
6756     return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0, N1);
6757
6758   // fold (fsub A, (fneg B)) -> (fadd A, B)
6759   if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6760     return DAG.getNode(ISD::FADD, dl, VT, N0,
6761                        GetNegatedExpression(N1, DAG, LegalOperations));
6762
6763   // If 'unsafe math' is enabled, fold lots of things.
6764   if (Options.UnsafeFPMath) {
6765     // (fsub A, 0) -> A
6766     if (N1CFP && N1CFP->getValueAPF().isZero())
6767       return N0;
6768
6769     // (fsub 0, B) -> -B
6770     if (N0CFP && N0CFP->getValueAPF().isZero()) {
6771       if (isNegatibleForFree(N1, LegalOperations, TLI, &Options))
6772         return GetNegatedExpression(N1, DAG, LegalOperations);
6773       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6774         return DAG.getNode(ISD::FNEG, dl, VT, N1);
6775     }
6776
6777     // (fsub x, x) -> 0.0
6778     if (N0 == N1)
6779       return DAG.getConstantFP(0.0f, VT);
6780
6781     // (fsub x, (fadd x, y)) -> (fneg y)
6782     // (fsub x, (fadd y, x)) -> (fneg y)
6783     if (N1.getOpcode() == ISD::FADD) {
6784       SDValue N10 = N1->getOperand(0);
6785       SDValue N11 = N1->getOperand(1);
6786
6787       if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI, &Options))
6788         return GetNegatedExpression(N11, DAG, LegalOperations);
6789
6790       if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI, &Options))
6791         return GetNegatedExpression(N10, DAG, LegalOperations);
6792     }
6793   }
6794
6795   // FSUB -> FMA combines:
6796   if ((Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath) &&
6797       TLI.isFMAFasterThanFMulAndFAdd(VT) &&
6798       (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT))) {
6799
6800     // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
6801     if (N0.getOpcode() == ISD::FMUL &&
6802         (N0->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6803       return DAG.getNode(ISD::FMA, dl, VT,
6804                          N0.getOperand(0), N0.getOperand(1),
6805                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6806
6807     // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
6808     // Note: Commutes FSUB operands.
6809     if (N1.getOpcode() == ISD::FMUL &&
6810         (N1->hasOneUse() || TLI.enableAggressiveFMAFusion(VT)))
6811       return DAG.getNode(ISD::FMA, dl, VT,
6812                          DAG.getNode(ISD::FNEG, dl, VT,
6813                          N1.getOperand(0)),
6814                          N1.getOperand(1), N0);
6815
6816     // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
6817     if (N0.getOpcode() == ISD::FNEG &&
6818         N0.getOperand(0).getOpcode() == ISD::FMUL &&
6819         ((N0->hasOneUse() && N0.getOperand(0).hasOneUse()) ||
6820             TLI.enableAggressiveFMAFusion(VT))) {
6821       SDValue N00 = N0.getOperand(0).getOperand(0);
6822       SDValue N01 = N0.getOperand(0).getOperand(1);
6823       return DAG.getNode(ISD::FMA, dl, VT,
6824                          DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
6825                          DAG.getNode(ISD::FNEG, dl, VT, N1));
6826     }
6827   }
6828
6829   return SDValue();
6830 }
6831
6832 SDValue DAGCombiner::visitFMUL(SDNode *N) {
6833   SDValue N0 = N->getOperand(0);
6834   SDValue N1 = N->getOperand(1);
6835   ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0);
6836   ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1);
6837   EVT VT = N->getValueType(0);
6838   const TargetOptions &Options = DAG.getTarget().Options;
6839
6840   // fold vector ops
6841   if (VT.isVector()) {
6842     // This just handles C1 * C2 for vectors. Other vector folds are below.
6843     SDValue FoldedVOp = SimplifyVBinOp(N);
6844     if (FoldedVOp.getNode())
6845       return FoldedVOp;
6846     // Canonicalize vector constant to RHS.
6847     if (N0.getOpcode() == ISD::BUILD_VECTOR &&
6848         N1.getOpcode() != ISD::BUILD_VECTOR)
6849       if (auto *BV0 = dyn_cast<BuildVectorSDNode>(N0))
6850         if (BV0->isConstant())
6851           return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
6852   }
6853
6854   // fold (fmul c1, c2) -> c1*c2
6855   if (N0CFP && N1CFP)
6856     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0, N1);
6857
6858   // canonicalize constant to RHS
6859   if (N0CFP && !N1CFP)
6860     return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N1, N0);
6861
6862   // fold (fmul A, 1.0) -> A
6863   if (N1CFP && N1CFP->isExactlyValue(1.0))
6864     return N0;
6865
6866   if (Options.UnsafeFPMath) {
6867     // fold (fmul A, 0) -> 0
6868     if (N1CFP && N1CFP->getValueAPF().isZero())
6869       return N1;
6870
6871     // fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
6872     if (N0.getOpcode() == ISD::FMUL) {
6873       // Fold scalars or any vector constants (not just splats).
6874       // This fold is done in general by InstCombine, but extra fmul insts
6875       // may have been generated during lowering.
6876       SDValue N01 = N0.getOperand(1);
6877       auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
6878       auto *BV01 = dyn_cast<BuildVectorSDNode>(N01);
6879       if ((N1CFP && isConstOrConstSplatFP(N01)) ||
6880           (BV1 && BV01 && BV1->isConstant() && BV01->isConstant())) {
6881         SDLoc SL(N);
6882         SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, N01, N1);
6883         return DAG.getNode(ISD::FMUL, SL, VT, N0.getOperand(0), MulConsts);
6884       }
6885     }
6886
6887     // fold (fmul (fadd x, x), c) -> (fmul x, (fmul 2.0, c))
6888     // Undo the fmul 2.0, x -> fadd x, x transformation, since if it occurs
6889     // during an early run of DAGCombiner can prevent folding with fmuls
6890     // inserted during lowering.
6891     if (N0.getOpcode() == ISD::FADD && N0.getOperand(0) == N0.getOperand(1)) {
6892       SDLoc SL(N);
6893       const SDValue Two = DAG.getConstantFP(2.0, VT);
6894       SDValue MulConsts = DAG.getNode(ISD::FMUL, SL, VT, Two, N1);
6895       return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0.getOperand(0), MulConsts);
6896     }
6897   }
6898
6899   // fold (fmul X, 2.0) -> (fadd X, X)
6900   if (N1CFP && N1CFP->isExactlyValue(+2.0))
6901     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N0);
6902
6903   // fold (fmul X, -1.0) -> (fneg X)
6904   if (N1CFP && N1CFP->isExactlyValue(-1.0))
6905     if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
6906       return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
6907
6908   // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
6909   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
6910     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
6911       // Both can be negated for free, check to see if at least one is cheaper
6912       // negated.
6913       if (LHSNeg == 2 || RHSNeg == 2)
6914         return DAG.getNode(ISD::FMUL, SDLoc(N), VT,
6915                            GetNegatedExpression(N0, DAG, LegalOperations),
6916                            GetNegatedExpression(N1, DAG, LegalOperations));
6917     }
6918   }
6919
6920   return SDValue();
6921 }
6922
6923 SDValue DAGCombiner::visitFMA(SDNode *N) {
6924   SDValue N0 = N->getOperand(0);
6925   SDValue N1 = N->getOperand(1);
6926   SDValue N2 = N->getOperand(2);
6927   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
6928   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
6929   EVT VT = N->getValueType(0);
6930   SDLoc dl(N);
6931   const TargetOptions &Options = DAG.getTarget().Options;
6932
6933   // Constant fold FMA.
6934   if (isa<ConstantFPSDNode>(N0) &&
6935       isa<ConstantFPSDNode>(N1) &&
6936       isa<ConstantFPSDNode>(N2)) {
6937     return DAG.getNode(ISD::FMA, dl, VT, N0, N1, N2);
6938   }
6939
6940   if (Options.UnsafeFPMath) {
6941     if (N0CFP && N0CFP->isZero())
6942       return N2;
6943     if (N1CFP && N1CFP->isZero())
6944       return N2;
6945   }
6946   if (N0CFP && N0CFP->isExactlyValue(1.0))
6947     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
6948   if (N1CFP && N1CFP->isExactlyValue(1.0))
6949     return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
6950
6951   // Canonicalize (fma c, x, y) -> (fma x, c, y)
6952   if (N0CFP && !N1CFP)
6953     return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
6954
6955   // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
6956   if (Options.UnsafeFPMath && N1CFP &&
6957       N2.getOpcode() == ISD::FMUL &&
6958       N0 == N2.getOperand(0) &&
6959       N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
6960     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6961                        DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
6962   }
6963
6964
6965   // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
6966   if (Options.UnsafeFPMath &&
6967       N0.getOpcode() == ISD::FMUL && N1CFP &&
6968       N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
6969     return DAG.getNode(ISD::FMA, dl, VT,
6970                        N0.getOperand(0),
6971                        DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
6972                        N2);
6973   }
6974
6975   // (fma x, 1, y) -> (fadd x, y)
6976   // (fma x, -1, y) -> (fadd (fneg x), y)
6977   if (N1CFP) {
6978     if (N1CFP->isExactlyValue(1.0))
6979       return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
6980
6981     if (N1CFP->isExactlyValue(-1.0) &&
6982         (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
6983       SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
6984       AddToWorklist(RHSNeg.getNode());
6985       return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
6986     }
6987   }
6988
6989   // (fma x, c, x) -> (fmul x, (c+1))
6990   if (Options.UnsafeFPMath && N1CFP && N0 == N2)
6991     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6992                        DAG.getNode(ISD::FADD, dl, VT,
6993                                    N1, DAG.getConstantFP(1.0, VT)));
6994
6995   // (fma x, c, (fneg x)) -> (fmul x, (c-1))
6996   if (Options.UnsafeFPMath && N1CFP &&
6997       N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0)
6998     return DAG.getNode(ISD::FMUL, dl, VT, N0,
6999                        DAG.getNode(ISD::FADD, dl, VT,
7000                                    N1, DAG.getConstantFP(-1.0, VT)));
7001
7002
7003   return SDValue();
7004 }
7005
7006 SDValue DAGCombiner::visitFDIV(SDNode *N) {
7007   SDValue N0 = N->getOperand(0);
7008   SDValue N1 = N->getOperand(1);
7009   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7010   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7011   EVT VT = N->getValueType(0);
7012   SDLoc DL(N);
7013   const TargetOptions &Options = DAG.getTarget().Options;
7014
7015   // fold vector ops
7016   if (VT.isVector()) {
7017     SDValue FoldedVOp = SimplifyVBinOp(N);
7018     if (FoldedVOp.getNode()) return FoldedVOp;
7019   }
7020
7021   // fold (fdiv c1, c2) -> c1/c2
7022   if (N0CFP && N1CFP)
7023     return DAG.getNode(ISD::FDIV, SDLoc(N), VT, N0, N1);
7024
7025   if (Options.UnsafeFPMath) {
7026     // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
7027     if (N1CFP) {
7028       // Compute the reciprocal 1.0 / c2.
7029       APFloat N1APF = N1CFP->getValueAPF();
7030       APFloat Recip(N1APF.getSemantics(), 1); // 1.0
7031       APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
7032       // Only do the transform if the reciprocal is a legal fp immediate that
7033       // isn't too nasty (eg NaN, denormal, ...).
7034       if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
7035           (!LegalOperations ||
7036            // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
7037            // backend)... we should handle this gracefully after Legalize.
7038            // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
7039            TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
7040            TLI.isFPImmLegal(Recip, VT)))
7041         return DAG.getNode(ISD::FMUL, SDLoc(N), VT, N0,
7042                            DAG.getConstantFP(Recip, VT));
7043     }
7044
7045     // If this FDIV is part of a reciprocal square root, it may be folded
7046     // into a target-specific square root estimate instruction.
7047     if (N1.getOpcode() == ISD::FSQRT) {
7048       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0))) {
7049         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7050       }
7051     } else if (N1.getOpcode() == ISD::FP_EXTEND &&
7052                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7053       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7054         RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
7055         AddToWorklist(RV.getNode());
7056         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7057       }
7058     } else if (N1.getOpcode() == ISD::FP_ROUND &&
7059                N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7060       if (SDValue RV = BuildRsqrtEstimate(N1.getOperand(0).getOperand(0))) {
7061         RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
7062         AddToWorklist(RV.getNode());
7063         return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7064       }
7065     } else if (N1.getOpcode() == ISD::FMUL) {
7066       // Look through an FMUL. Even though this won't remove the FDIV directly,
7067       // it's still worthwhile to get rid of the FSQRT if possible.
7068       SDValue SqrtOp;
7069       SDValue OtherOp;
7070       if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
7071         SqrtOp = N1.getOperand(0);
7072         OtherOp = N1.getOperand(1);
7073       } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
7074         SqrtOp = N1.getOperand(1);
7075         OtherOp = N1.getOperand(0);
7076       }
7077       if (SqrtOp.getNode()) {
7078         // We found a FSQRT, so try to make this fold:
7079         // x / (y * sqrt(z)) -> x * (rsqrt(z) / y)
7080         if (SDValue RV = BuildRsqrtEstimate(SqrtOp.getOperand(0))) {
7081           RV = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, RV, OtherOp);
7082           AddToWorklist(RV.getNode());
7083           return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7084         }
7085       }
7086     }
7087
7088     // Fold into a reciprocal estimate and multiply instead of a real divide.
7089     if (SDValue RV = BuildReciprocalEstimate(N1)) {
7090       AddToWorklist(RV.getNode());
7091       return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
7092     }
7093   }
7094
7095   // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
7096   if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI, &Options)) {
7097     if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI, &Options)) {
7098       // Both can be negated for free, check to see if at least one is cheaper
7099       // negated.
7100       if (LHSNeg == 2 || RHSNeg == 2)
7101         return DAG.getNode(ISD::FDIV, SDLoc(N), VT,
7102                            GetNegatedExpression(N0, DAG, LegalOperations),
7103                            GetNegatedExpression(N1, DAG, LegalOperations));
7104     }
7105   }
7106
7107   // Combine multiple FDIVs with the same divisor into multiple FMULs by the
7108   // reciprocal.
7109   // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
7110   // Notice that this is not always beneficial. One reason is different target
7111   // may have different costs for FDIV and FMUL, so sometimes the cost of two
7112   // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
7113   // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
7114   if (Options.UnsafeFPMath) {
7115     // Skip if current node is a reciprocal.
7116     if (N0CFP && N0CFP->isExactlyValue(1.0))
7117       return SDValue();
7118
7119     SmallVector<SDNode *, 4> Users;
7120     // Find all FDIV users of the same divisor.
7121     for (SDNode::use_iterator UI = N1.getNode()->use_begin(),
7122                               UE = N1.getNode()->use_end();
7123          UI != UE; ++UI) {
7124       SDNode *User = UI.getUse().getUser();
7125       if (User->getOpcode() == ISD::FDIV && User->getOperand(1) == N1)
7126         Users.push_back(User);
7127     }
7128
7129     if (TLI.combineRepeatedFPDivisors(Users.size())) {
7130       SDValue FPOne = DAG.getConstantFP(1.0, VT); // floating point 1.0
7131       SDValue Reciprocal = DAG.getNode(ISD::FDIV, SDLoc(N), VT, FPOne, N1);
7132
7133       // Dividend / Divisor -> Dividend * Reciprocal
7134       for (auto I = Users.begin(), E = Users.end(); I != E; ++I) {
7135         if ((*I)->getOperand(0) != FPOne) {
7136           SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(*I), VT,
7137                                         (*I)->getOperand(0), Reciprocal);
7138           DAG.ReplaceAllUsesWith(*I, NewNode.getNode());
7139         }
7140       }
7141       return SDValue();
7142     }
7143   }
7144
7145   return SDValue();
7146 }
7147
7148 SDValue DAGCombiner::visitFREM(SDNode *N) {
7149   SDValue N0 = N->getOperand(0);
7150   SDValue N1 = N->getOperand(1);
7151   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7152   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7153   EVT VT = N->getValueType(0);
7154
7155   // fold (frem c1, c2) -> fmod(c1,c2)
7156   if (N0CFP && N1CFP)
7157     return DAG.getNode(ISD::FREM, SDLoc(N), VT, N0, N1);
7158
7159   return SDValue();
7160 }
7161
7162 SDValue DAGCombiner::visitFSQRT(SDNode *N) {
7163   if (DAG.getTarget().Options.UnsafeFPMath) {
7164     // Compute this as X * (1/sqrt(X)) = X * (X ** -0.5)
7165     if (SDValue RV = BuildRsqrtEstimate(N->getOperand(0))) {
7166       EVT VT = RV.getValueType();
7167       RV = DAG.getNode(ISD::FMUL, SDLoc(N), VT, N->getOperand(0), RV);
7168       AddToWorklist(RV.getNode());
7169
7170       // Unfortunately, RV is now NaN if the input was exactly 0.
7171       // Select out this case and force the answer to 0.
7172       SDValue Zero = DAG.getConstantFP(0.0, VT);
7173       SDValue ZeroCmp =
7174         DAG.getSetCC(SDLoc(N), TLI.getSetCCResultType(*DAG.getContext(), VT),
7175                      N->getOperand(0), Zero, ISD::SETEQ);
7176       AddToWorklist(ZeroCmp.getNode());
7177       AddToWorklist(RV.getNode());
7178
7179       RV = DAG.getNode(VT.isVector() ? ISD::VSELECT : ISD::SELECT,
7180                        SDLoc(N), VT, ZeroCmp, Zero, RV);
7181       return RV;
7182     }
7183   }
7184   return SDValue();
7185 }
7186
7187 SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
7188   SDValue N0 = N->getOperand(0);
7189   SDValue N1 = N->getOperand(1);
7190   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7191   ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7192   EVT VT = N->getValueType(0);
7193
7194   if (N0CFP && N1CFP)  // Constant fold
7195     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1);
7196
7197   if (N1CFP) {
7198     const APFloat& V = N1CFP->getValueAPF();
7199     // copysign(x, c1) -> fabs(x)       iff ispos(c1)
7200     // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
7201     if (!V.isNegative()) {
7202       if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
7203         return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7204     } else {
7205       if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
7206         return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
7207                            DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
7208     }
7209   }
7210
7211   // copysign(fabs(x), y) -> copysign(x, y)
7212   // copysign(fneg(x), y) -> copysign(x, y)
7213   // copysign(copysign(x,z), y) -> copysign(x, y)
7214   if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
7215       N0.getOpcode() == ISD::FCOPYSIGN)
7216     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7217                        N0.getOperand(0), N1);
7218
7219   // copysign(x, abs(y)) -> abs(x)
7220   if (N1.getOpcode() == ISD::FABS)
7221     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7222
7223   // copysign(x, copysign(y,z)) -> copysign(x, z)
7224   if (N1.getOpcode() == ISD::FCOPYSIGN)
7225     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7226                        N0, N1.getOperand(1));
7227
7228   // copysign(x, fp_extend(y)) -> copysign(x, y)
7229   // copysign(x, fp_round(y)) -> copysign(x, y)
7230   if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
7231     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7232                        N0, N1.getOperand(0));
7233
7234   return SDValue();
7235 }
7236
7237 SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
7238   SDValue N0 = N->getOperand(0);
7239   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7240   EVT VT = N->getValueType(0);
7241   EVT OpVT = N0.getValueType();
7242
7243   // fold (sint_to_fp c1) -> c1fp
7244   if (N0C &&
7245       // ...but only if the target supports immediate floating-point values
7246       (!LegalOperations ||
7247        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7248     return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7249
7250   // If the input is a legal type, and SINT_TO_FP is not legal on this target,
7251   // but UINT_TO_FP is legal on this target, try to convert.
7252   if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
7253       TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
7254     // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
7255     if (DAG.SignBitIsZero(N0))
7256       return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7257   }
7258
7259   // The next optimizations are desirable only if SELECT_CC can be lowered.
7260   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7261     // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7262     if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
7263         !VT.isVector() &&
7264         (!LegalOperations ||
7265          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7266       SDValue Ops[] =
7267         { N0.getOperand(0), N0.getOperand(1),
7268           DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
7269           N0.getOperand(2) };
7270       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7271     }
7272
7273     // fold (sint_to_fp (zext (setcc x, y, cc))) ->
7274     //      (select_cc x, y, 1.0, 0.0,, cc)
7275     if (N0.getOpcode() == ISD::ZERO_EXTEND &&
7276         N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
7277         (!LegalOperations ||
7278          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7279       SDValue Ops[] =
7280         { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
7281           DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
7282           N0.getOperand(0).getOperand(2) };
7283       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7284     }
7285   }
7286
7287   return SDValue();
7288 }
7289
7290 SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
7291   SDValue N0 = N->getOperand(0);
7292   ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
7293   EVT VT = N->getValueType(0);
7294   EVT OpVT = N0.getValueType();
7295
7296   // fold (uint_to_fp c1) -> c1fp
7297   if (N0C &&
7298       // ...but only if the target supports immediate floating-point values
7299       (!LegalOperations ||
7300        TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
7301     return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
7302
7303   // If the input is a legal type, and UINT_TO_FP is not legal on this target,
7304   // but SINT_TO_FP is legal on this target, try to convert.
7305   if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
7306       TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
7307     // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
7308     if (DAG.SignBitIsZero(N0))
7309       return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
7310   }
7311
7312   // The next optimizations are desirable only if SELECT_CC can be lowered.
7313   if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT) || !LegalOperations) {
7314     // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
7315
7316     if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
7317         (!LegalOperations ||
7318          TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
7319       SDValue Ops[] =
7320         { N0.getOperand(0), N0.getOperand(1),
7321           DAG.getConstantFP(1.0, VT),  DAG.getConstantFP(0.0, VT),
7322           N0.getOperand(2) };
7323       return DAG.getNode(ISD::SELECT_CC, SDLoc(N), VT, Ops);
7324     }
7325   }
7326
7327   return SDValue();
7328 }
7329
7330 SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
7331   SDValue N0 = N->getOperand(0);
7332   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7333   EVT VT = N->getValueType(0);
7334
7335   // fold (fp_to_sint c1fp) -> c1
7336   if (N0CFP)
7337     return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
7338
7339   return SDValue();
7340 }
7341
7342 SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
7343   SDValue N0 = N->getOperand(0);
7344   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7345   EVT VT = N->getValueType(0);
7346
7347   // fold (fp_to_uint c1fp) -> c1
7348   if (N0CFP)
7349     return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
7350
7351   return SDValue();
7352 }
7353
7354 SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
7355   SDValue N0 = N->getOperand(0);
7356   SDValue N1 = N->getOperand(1);
7357   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7358   EVT VT = N->getValueType(0);
7359
7360   // fold (fp_round c1fp) -> c1fp
7361   if (N0CFP)
7362     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
7363
7364   // fold (fp_round (fp_extend x)) -> x
7365   if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
7366     return N0.getOperand(0);
7367
7368   // fold (fp_round (fp_round x)) -> (fp_round x)
7369   if (N0.getOpcode() == ISD::FP_ROUND) {
7370     // This is a value preserving truncation if both round's are.
7371     bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
7372                    N0.getNode()->getConstantOperandVal(1) == 1;
7373     return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0.getOperand(0),
7374                        DAG.getIntPtrConstant(IsTrunc));
7375   }
7376
7377   // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
7378   if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
7379     SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
7380                               N0.getOperand(0), N1);
7381     AddToWorklist(Tmp.getNode());
7382     return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
7383                        Tmp, N0.getOperand(1));
7384   }
7385
7386   return SDValue();
7387 }
7388
7389 SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
7390   SDValue N0 = N->getOperand(0);
7391   EVT VT = N->getValueType(0);
7392   EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
7393   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7394
7395   // fold (fp_round_inreg c1fp) -> c1fp
7396   if (N0CFP && isTypeLegal(EVT)) {
7397     SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
7398     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, Round);
7399   }
7400
7401   return SDValue();
7402 }
7403
7404 SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
7405   SDValue N0 = N->getOperand(0);
7406   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7407   EVT VT = N->getValueType(0);
7408
7409   // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
7410   if (N->hasOneUse() &&
7411       N->use_begin()->getOpcode() == ISD::FP_ROUND)
7412     return SDValue();
7413
7414   // fold (fp_extend c1fp) -> c1fp
7415   if (N0CFP)
7416     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
7417
7418   // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
7419   // value of X.
7420   if (N0.getOpcode() == ISD::FP_ROUND
7421       && N0.getNode()->getConstantOperandVal(1) == 1) {
7422     SDValue In = N0.getOperand(0);
7423     if (In.getValueType() == VT) return In;
7424     if (VT.bitsLT(In.getValueType()))
7425       return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
7426                          In, N0.getOperand(1));
7427     return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
7428   }
7429
7430   // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
7431   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
7432        TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType())) {
7433     LoadSDNode *LN0 = cast<LoadSDNode>(N0);
7434     SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
7435                                      LN0->getChain(),
7436                                      LN0->getBasePtr(), N0.getValueType(),
7437                                      LN0->getMemOperand());
7438     CombineTo(N, ExtLoad);
7439     CombineTo(N0.getNode(),
7440               DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
7441                           N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
7442               ExtLoad.getValue(1));
7443     return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7444   }
7445
7446   return SDValue();
7447 }
7448
7449 SDValue DAGCombiner::visitFCEIL(SDNode *N) {
7450   SDValue N0 = N->getOperand(0);
7451   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7452   EVT VT = N->getValueType(0);
7453
7454   // fold (fceil c1) -> fceil(c1)
7455   if (N0CFP)
7456     return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
7457
7458   return SDValue();
7459 }
7460
7461 SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
7462   SDValue N0 = N->getOperand(0);
7463   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7464   EVT VT = N->getValueType(0);
7465
7466   // fold (ftrunc c1) -> ftrunc(c1)
7467   if (N0CFP)
7468     return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
7469
7470   return SDValue();
7471 }
7472
7473 SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
7474   SDValue N0 = N->getOperand(0);
7475   ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7476   EVT VT = N->getValueType(0);
7477
7478   // fold (ffloor c1) -> ffloor(c1)
7479   if (N0CFP)
7480     return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
7481
7482   return SDValue();
7483 }
7484
7485 // FIXME: FNEG and FABS have a lot in common; refactor.
7486 SDValue DAGCombiner::visitFNEG(SDNode *N) {
7487   SDValue N0 = N->getOperand(0);
7488   EVT VT = N->getValueType(0);
7489
7490   if (VT.isVector()) {
7491     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7492     if (FoldedVOp.getNode()) return FoldedVOp;
7493   }
7494
7495   // Constant fold FNEG.
7496   if (isa<ConstantFPSDNode>(N0))
7497     return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N->getOperand(0));
7498
7499   if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
7500                          &DAG.getTarget().Options))
7501     return GetNegatedExpression(N0, DAG, LegalOperations);
7502
7503   // Transform fneg(bitconvert(x)) -> bitconvert(x ^ sign) to avoid loading
7504   // constant pool values.
7505   if (!TLI.isFNegFree(VT) &&
7506       N0.getOpcode() == ISD::BITCAST &&
7507       N0.getNode()->hasOneUse()) {
7508     SDValue Int = N0.getOperand(0);
7509     EVT IntVT = Int.getValueType();
7510     if (IntVT.isInteger() && !IntVT.isVector()) {
7511       APInt SignMask;
7512       if (N0.getValueType().isVector()) {
7513         // For a vector, get a mask such as 0x80... per scalar element
7514         // and splat it.
7515         SignMask = APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7516         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7517       } else {
7518         // For a scalar, just generate 0x80...
7519         SignMask = APInt::getSignBit(IntVT.getSizeInBits());
7520       }
7521       Int = DAG.getNode(ISD::XOR, SDLoc(N0), IntVT, Int,
7522                         DAG.getConstant(SignMask, IntVT));
7523       AddToWorklist(Int.getNode());
7524       return DAG.getNode(ISD::BITCAST, SDLoc(N), VT, Int);
7525     }
7526   }
7527
7528   // (fneg (fmul c, x)) -> (fmul -c, x)
7529   if (N0.getOpcode() == ISD::FMUL) {
7530     ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
7531     if (CFP1) {
7532       APFloat CVal = CFP1->getValueAPF();
7533       CVal.changeSign();
7534       if (Level >= AfterLegalizeDAG &&
7535           (TLI.isFPImmLegal(CVal, N->getValueType(0)) ||
7536            TLI.isOperationLegal(ISD::ConstantFP, N->getValueType(0))))
7537         return DAG.getNode(
7538             ISD::FMUL, SDLoc(N), VT, N0.getOperand(0),
7539             DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0.getOperand(1)));
7540     }
7541   }
7542
7543   return SDValue();
7544 }
7545
7546 SDValue DAGCombiner::visitFMINNUM(SDNode *N) {
7547   SDValue N0 = N->getOperand(0);
7548   SDValue N1 = N->getOperand(1);
7549   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7550   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7551
7552   if (N0CFP && N1CFP) {
7553     const APFloat &C0 = N0CFP->getValueAPF();
7554     const APFloat &C1 = N1CFP->getValueAPF();
7555     return DAG.getConstantFP(minnum(C0, C1), N->getValueType(0));
7556   }
7557
7558   if (N0CFP) {
7559     EVT VT = N->getValueType(0);
7560     // Canonicalize to constant on RHS.
7561     return DAG.getNode(ISD::FMINNUM, SDLoc(N), VT, N1, N0);
7562   }
7563
7564   return SDValue();
7565 }
7566
7567 SDValue DAGCombiner::visitFMAXNUM(SDNode *N) {
7568   SDValue N0 = N->getOperand(0);
7569   SDValue N1 = N->getOperand(1);
7570   const ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
7571   const ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
7572
7573   if (N0CFP && N1CFP) {
7574     const APFloat &C0 = N0CFP->getValueAPF();
7575     const APFloat &C1 = N1CFP->getValueAPF();
7576     return DAG.getConstantFP(maxnum(C0, C1), N->getValueType(0));
7577   }
7578
7579   if (N0CFP) {
7580     EVT VT = N->getValueType(0);
7581     // Canonicalize to constant on RHS.
7582     return DAG.getNode(ISD::FMAXNUM, SDLoc(N), VT, N1, N0);
7583   }
7584
7585   return SDValue();
7586 }
7587
7588 SDValue DAGCombiner::visitFABS(SDNode *N) {
7589   SDValue N0 = N->getOperand(0);
7590   EVT VT = N->getValueType(0);
7591
7592   if (VT.isVector()) {
7593     SDValue FoldedVOp = SimplifyVUnaryOp(N);
7594     if (FoldedVOp.getNode()) return FoldedVOp;
7595   }
7596
7597   // fold (fabs c1) -> fabs(c1)
7598   if (isa<ConstantFPSDNode>(N0))
7599     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
7600
7601   // fold (fabs (fabs x)) -> (fabs x)
7602   if (N0.getOpcode() == ISD::FABS)
7603     return N->getOperand(0);
7604
7605   // fold (fabs (fneg x)) -> (fabs x)
7606   // fold (fabs (fcopysign x, y)) -> (fabs x)
7607   if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
7608     return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
7609
7610   // Transform fabs(bitconvert(x)) -> bitconvert(x & ~sign) to avoid loading
7611   // constant pool values.
7612   if (!TLI.isFAbsFree(VT) &&
7613       N0.getOpcode() == ISD::BITCAST &&
7614       N0.getNode()->hasOneUse()) {
7615     SDValue Int = N0.getOperand(0);
7616     EVT IntVT = Int.getValueType();
7617     if (IntVT.isInteger() && !IntVT.isVector()) {
7618       APInt SignMask;
7619       if (N0.getValueType().isVector()) {
7620         // For a vector, get a mask such as 0x7f... per scalar element
7621         // and splat it.
7622         SignMask = ~APInt::getSignBit(N0.getValueType().getScalarSizeInBits());
7623         SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
7624       } else {
7625         // For a scalar, just generate 0x7f...
7626         SignMask = ~APInt::getSignBit(IntVT.getSizeInBits());
7627       }
7628       Int = DAG.getNode(ISD::AND, SDLoc(N0), IntVT, Int,
7629                         DAG.getConstant(SignMask, IntVT));
7630       AddToWorklist(Int.getNode());
7631       return DAG.getNode(ISD::BITCAST, SDLoc(N), N->getValueType(0), Int);
7632     }
7633   }
7634
7635   return SDValue();
7636 }
7637
7638 SDValue DAGCombiner::visitBRCOND(SDNode *N) {
7639   SDValue Chain = N->getOperand(0);
7640   SDValue N1 = N->getOperand(1);
7641   SDValue N2 = N->getOperand(2);
7642
7643   // If N is a constant we could fold this into a fallthrough or unconditional
7644   // branch. However that doesn't happen very often in normal code, because
7645   // Instcombine/SimplifyCFG should have handled the available opportunities.
7646   // If we did this folding here, it would be necessary to update the
7647   // MachineBasicBlock CFG, which is awkward.
7648
7649   // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
7650   // on the target.
7651   if (N1.getOpcode() == ISD::SETCC &&
7652       TLI.isOperationLegalOrCustom(ISD::BR_CC,
7653                                    N1.getOperand(0).getValueType())) {
7654     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7655                        Chain, N1.getOperand(2),
7656                        N1.getOperand(0), N1.getOperand(1), N2);
7657   }
7658
7659   if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
7660       ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
7661        (N1.getOperand(0).hasOneUse() &&
7662         N1.getOperand(0).getOpcode() == ISD::SRL))) {
7663     SDNode *Trunc = nullptr;
7664     if (N1.getOpcode() == ISD::TRUNCATE) {
7665       // Look pass the truncate.
7666       Trunc = N1.getNode();
7667       N1 = N1.getOperand(0);
7668     }
7669
7670     // Match this pattern so that we can generate simpler code:
7671     //
7672     //   %a = ...
7673     //   %b = and i32 %a, 2
7674     //   %c = srl i32 %b, 1
7675     //   brcond i32 %c ...
7676     //
7677     // into
7678     //
7679     //   %a = ...
7680     //   %b = and i32 %a, 2
7681     //   %c = setcc eq %b, 0
7682     //   brcond %c ...
7683     //
7684     // This applies only when the AND constant value has one bit set and the
7685     // SRL constant is equal to the log2 of the AND constant. The back-end is
7686     // smart enough to convert the result into a TEST/JMP sequence.
7687     SDValue Op0 = N1.getOperand(0);
7688     SDValue Op1 = N1.getOperand(1);
7689
7690     if (Op0.getOpcode() == ISD::AND &&
7691         Op1.getOpcode() == ISD::Constant) {
7692       SDValue AndOp1 = Op0.getOperand(1);
7693
7694       if (AndOp1.getOpcode() == ISD::Constant) {
7695         const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
7696
7697         if (AndConst.isPowerOf2() &&
7698             cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
7699           SDValue SetCC =
7700             DAG.getSetCC(SDLoc(N),
7701                          getSetCCResultType(Op0.getValueType()),
7702                          Op0, DAG.getConstant(0, Op0.getValueType()),
7703                          ISD::SETNE);
7704
7705           SDValue NewBRCond = DAG.getNode(ISD::BRCOND, SDLoc(N),
7706                                           MVT::Other, Chain, SetCC, N2);
7707           // Don't add the new BRCond into the worklist or else SimplifySelectCC
7708           // will convert it back to (X & C1) >> C2.
7709           CombineTo(N, NewBRCond, false);
7710           // Truncate is dead.
7711           if (Trunc)
7712             deleteAndRecombine(Trunc);
7713           // Replace the uses of SRL with SETCC
7714           WorklistRemover DeadNodes(*this);
7715           DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7716           deleteAndRecombine(N1.getNode());
7717           return SDValue(N, 0);   // Return N so it doesn't get rechecked!
7718         }
7719       }
7720     }
7721
7722     if (Trunc)
7723       // Restore N1 if the above transformation doesn't match.
7724       N1 = N->getOperand(1);
7725   }
7726
7727   // Transform br(xor(x, y)) -> br(x != y)
7728   // Transform br(xor(xor(x,y), 1)) -> br (x == y)
7729   if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
7730     SDNode *TheXor = N1.getNode();
7731     SDValue Op0 = TheXor->getOperand(0);
7732     SDValue Op1 = TheXor->getOperand(1);
7733     if (Op0.getOpcode() == Op1.getOpcode()) {
7734       // Avoid missing important xor optimizations.
7735       SDValue Tmp = visitXOR(TheXor);
7736       if (Tmp.getNode()) {
7737         if (Tmp.getNode() != TheXor) {
7738           DEBUG(dbgs() << "\nReplacing.8 ";
7739                 TheXor->dump(&DAG);
7740                 dbgs() << "\nWith: ";
7741                 Tmp.getNode()->dump(&DAG);
7742                 dbgs() << '\n');
7743           WorklistRemover DeadNodes(*this);
7744           DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
7745           deleteAndRecombine(TheXor);
7746           return DAG.getNode(ISD::BRCOND, SDLoc(N),
7747                              MVT::Other, Chain, Tmp, N2);
7748         }
7749
7750         // visitXOR has changed XOR's operands or replaced the XOR completely,
7751         // bail out.
7752         return SDValue(N, 0);
7753       }
7754     }
7755
7756     if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
7757       bool Equal = false;
7758       if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
7759         if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
7760             Op0.getOpcode() == ISD::XOR) {
7761           TheXor = Op0.getNode();
7762           Equal = true;
7763         }
7764
7765       EVT SetCCVT = N1.getValueType();
7766       if (LegalTypes)
7767         SetCCVT = getSetCCResultType(SetCCVT);
7768       SDValue SetCC = DAG.getSetCC(SDLoc(TheXor),
7769                                    SetCCVT,
7770                                    Op0, Op1,
7771                                    Equal ? ISD::SETEQ : ISD::SETNE);
7772       // Replace the uses of XOR with SETCC
7773       WorklistRemover DeadNodes(*this);
7774       DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
7775       deleteAndRecombine(N1.getNode());
7776       return DAG.getNode(ISD::BRCOND, SDLoc(N),
7777                          MVT::Other, Chain, SetCC, N2);
7778     }
7779   }
7780
7781   return SDValue();
7782 }
7783
7784 // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
7785 //
7786 SDValue DAGCombiner::visitBR_CC(SDNode *N) {
7787   CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
7788   SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
7789
7790   // If N is a constant we could fold this into a fallthrough or unconditional
7791   // branch. However that doesn't happen very often in normal code, because
7792   // Instcombine/SimplifyCFG should have handled the available opportunities.
7793   // If we did this folding here, it would be necessary to update the
7794   // MachineBasicBlock CFG, which is awkward.
7795
7796   // Use SimplifySetCC to simplify SETCC's.
7797   SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
7798                                CondLHS, CondRHS, CC->get(), SDLoc(N),
7799                                false);
7800   if (Simp.getNode()) AddToWorklist(Simp.getNode());
7801
7802   // fold to a simpler setcc
7803   if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
7804     return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
7805                        N->getOperand(0), Simp.getOperand(2),
7806                        Simp.getOperand(0), Simp.getOperand(1),
7807                        N->getOperand(4));
7808
7809   return SDValue();
7810 }
7811
7812 /// Return true if 'Use' is a load or a store that uses N as its base pointer
7813 /// and that N may be folded in the load / store addressing mode.
7814 static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
7815                                     SelectionDAG &DAG,
7816                                     const TargetLowering &TLI) {
7817   EVT VT;
7818   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(Use)) {
7819     if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
7820       return false;
7821     VT = Use->getValueType(0);
7822   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(Use)) {
7823     if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
7824       return false;
7825     VT = ST->getValue().getValueType();
7826   } else
7827     return false;
7828
7829   TargetLowering::AddrMode AM;
7830   if (N->getOpcode() == ISD::ADD) {
7831     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7832     if (Offset)
7833       // [reg +/- imm]
7834       AM.BaseOffs = Offset->getSExtValue();
7835     else
7836       // [reg +/- reg]
7837       AM.Scale = 1;
7838   } else if (N->getOpcode() == ISD::SUB) {
7839     ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
7840     if (Offset)
7841       // [reg +/- imm]
7842       AM.BaseOffs = -Offset->getSExtValue();
7843     else
7844       // [reg +/- reg]
7845       AM.Scale = 1;
7846   } else
7847     return false;
7848
7849   return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
7850 }
7851
7852 /// Try turning a load/store into a pre-indexed load/store when the base
7853 /// pointer is an add or subtract and it has other uses besides the load/store.
7854 /// After the transformation, the new indexed load/store has effectively folded
7855 /// the add/subtract in and all of its other uses are redirected to the
7856 /// new load/store.
7857 bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
7858   if (Level < AfterLegalizeDAG)
7859     return false;
7860
7861   bool isLoad = true;
7862   SDValue Ptr;
7863   EVT VT;
7864   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
7865     if (LD->isIndexed())
7866       return false;
7867     VT = LD->getMemoryVT();
7868     if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
7869         !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
7870       return false;
7871     Ptr = LD->getBasePtr();
7872   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
7873     if (ST->isIndexed())
7874       return false;
7875     VT = ST->getMemoryVT();
7876     if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
7877         !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
7878       return false;
7879     Ptr = ST->getBasePtr();
7880     isLoad = false;
7881   } else {
7882     return false;
7883   }
7884
7885   // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
7886   // out.  There is no reason to make this a preinc/predec.
7887   if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
7888       Ptr.getNode()->hasOneUse())
7889     return false;
7890
7891   // Ask the target to do addressing mode selection.
7892   SDValue BasePtr;
7893   SDValue Offset;
7894   ISD::MemIndexedMode AM = ISD::UNINDEXED;
7895   if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
7896     return false;
7897
7898   // Backends without true r+i pre-indexed forms may need to pass a
7899   // constant base with a variable offset so that constant coercion
7900   // will work with the patterns in canonical form.
7901   bool Swapped = false;
7902   if (isa<ConstantSDNode>(BasePtr)) {
7903     std::swap(BasePtr, Offset);
7904     Swapped = true;
7905   }
7906
7907   // Don't create a indexed load / store with zero offset.
7908   if (isa<ConstantSDNode>(Offset) &&
7909       cast<ConstantSDNode>(Offset)->isNullValue())
7910     return false;
7911
7912   // Try turning it into a pre-indexed load / store except when:
7913   // 1) The new base ptr is a frame index.
7914   // 2) If N is a store and the new base ptr is either the same as or is a
7915   //    predecessor of the value being stored.
7916   // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
7917   //    that would create a cycle.
7918   // 4) All uses are load / store ops that use it as old base ptr.
7919
7920   // Check #1.  Preinc'ing a frame index would require copying the stack pointer
7921   // (plus the implicit offset) to a register to preinc anyway.
7922   if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
7923     return false;
7924
7925   // Check #2.
7926   if (!isLoad) {
7927     SDValue Val = cast<StoreSDNode>(N)->getValue();
7928     if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
7929       return false;
7930   }
7931
7932   // If the offset is a constant, there may be other adds of constants that
7933   // can be folded with this one. We should do this to avoid having to keep
7934   // a copy of the original base pointer.
7935   SmallVector<SDNode *, 16> OtherUses;
7936   if (isa<ConstantSDNode>(Offset))
7937     for (SDNode *Use : BasePtr.getNode()->uses()) {
7938       if (Use == Ptr.getNode())
7939         continue;
7940
7941       if (Use->isPredecessorOf(N))
7942         continue;
7943
7944       if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
7945         OtherUses.clear();
7946         break;
7947       }
7948
7949       SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
7950       if (Op1.getNode() == BasePtr.getNode())
7951         std::swap(Op0, Op1);
7952       assert(Op0.getNode() == BasePtr.getNode() &&
7953              "Use of ADD/SUB but not an operand");
7954
7955       if (!isa<ConstantSDNode>(Op1)) {
7956         OtherUses.clear();
7957         break;
7958       }
7959
7960       // FIXME: In some cases, we can be smarter about this.
7961       if (Op1.getValueType() != Offset.getValueType()) {
7962         OtherUses.clear();
7963         break;
7964       }
7965
7966       OtherUses.push_back(Use);
7967     }
7968
7969   if (Swapped)
7970     std::swap(BasePtr, Offset);
7971
7972   // Now check for #3 and #4.
7973   bool RealUse = false;
7974
7975   // Caches for hasPredecessorHelper
7976   SmallPtrSet<const SDNode *, 32> Visited;
7977   SmallVector<const SDNode *, 16> Worklist;
7978
7979   for (SDNode *Use : Ptr.getNode()->uses()) {
7980     if (Use == N)
7981       continue;
7982     if (N->hasPredecessorHelper(Use, Visited, Worklist))
7983       return false;
7984
7985     // If Ptr may be folded in addressing mode of other use, then it's
7986     // not profitable to do this transformation.
7987     if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
7988       RealUse = true;
7989   }
7990
7991   if (!RealUse)
7992     return false;
7993
7994   SDValue Result;
7995   if (isLoad)
7996     Result = DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
7997                                 BasePtr, Offset, AM);
7998   else
7999     Result = DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8000                                  BasePtr, Offset, AM);
8001   ++PreIndexedNodes;
8002   ++NodesCombined;
8003   DEBUG(dbgs() << "\nReplacing.4 ";
8004         N->dump(&DAG);
8005         dbgs() << "\nWith: ";
8006         Result.getNode()->dump(&DAG);
8007         dbgs() << '\n');
8008   WorklistRemover DeadNodes(*this);
8009   if (isLoad) {
8010     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8011     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8012   } else {
8013     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8014   }
8015
8016   // Finally, since the node is now dead, remove it from the graph.
8017   deleteAndRecombine(N);
8018
8019   if (Swapped)
8020     std::swap(BasePtr, Offset);
8021
8022   // Replace other uses of BasePtr that can be updated to use Ptr
8023   for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
8024     unsigned OffsetIdx = 1;
8025     if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
8026       OffsetIdx = 0;
8027     assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
8028            BasePtr.getNode() && "Expected BasePtr operand");
8029
8030     // We need to replace ptr0 in the following expression:
8031     //   x0 * offset0 + y0 * ptr0 = t0
8032     // knowing that
8033     //   x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
8034     //
8035     // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
8036     // indexed load/store and the expresion that needs to be re-written.
8037     //
8038     // Therefore, we have:
8039     //   t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
8040
8041     ConstantSDNode *CN =
8042       cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
8043     int X0, X1, Y0, Y1;
8044     APInt Offset0 = CN->getAPIntValue();
8045     APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
8046
8047     X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
8048     Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
8049     X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
8050     Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
8051
8052     unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
8053
8054     APInt CNV = Offset0;
8055     if (X0 < 0) CNV = -CNV;
8056     if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
8057     else CNV = CNV - Offset1;
8058
8059     // We can now generate the new expression.
8060     SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
8061     SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
8062
8063     SDValue NewUse = DAG.getNode(Opcode,
8064                                  SDLoc(OtherUses[i]),
8065                                  OtherUses[i]->getValueType(0), NewOp1, NewOp2);
8066     DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
8067     deleteAndRecombine(OtherUses[i]);
8068   }
8069
8070   // Replace the uses of Ptr with uses of the updated base value.
8071   DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
8072   deleteAndRecombine(Ptr.getNode());
8073
8074   return true;
8075 }
8076
8077 /// Try to combine a load/store with a add/sub of the base pointer node into a
8078 /// post-indexed load/store. The transformation folded the add/subtract into the
8079 /// new indexed load/store effectively and all of its uses are redirected to the
8080 /// new load/store.
8081 bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
8082   if (Level < AfterLegalizeDAG)
8083     return false;
8084
8085   bool isLoad = true;
8086   SDValue Ptr;
8087   EVT VT;
8088   if (LoadSDNode *LD  = dyn_cast<LoadSDNode>(N)) {
8089     if (LD->isIndexed())
8090       return false;
8091     VT = LD->getMemoryVT();
8092     if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
8093         !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
8094       return false;
8095     Ptr = LD->getBasePtr();
8096   } else if (StoreSDNode *ST  = dyn_cast<StoreSDNode>(N)) {
8097     if (ST->isIndexed())
8098       return false;
8099     VT = ST->getMemoryVT();
8100     if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
8101         !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
8102       return false;
8103     Ptr = ST->getBasePtr();
8104     isLoad = false;
8105   } else {
8106     return false;
8107   }
8108
8109   if (Ptr.getNode()->hasOneUse())
8110     return false;
8111
8112   for (SDNode *Op : Ptr.getNode()->uses()) {
8113     if (Op == N ||
8114         (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
8115       continue;
8116
8117     SDValue BasePtr;
8118     SDValue Offset;
8119     ISD::MemIndexedMode AM = ISD::UNINDEXED;
8120     if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
8121       // Don't create a indexed load / store with zero offset.
8122       if (isa<ConstantSDNode>(Offset) &&
8123           cast<ConstantSDNode>(Offset)->isNullValue())
8124         continue;
8125
8126       // Try turning it into a post-indexed load / store except when
8127       // 1) All uses are load / store ops that use it as base ptr (and
8128       //    it may be folded as addressing mmode).
8129       // 2) Op must be independent of N, i.e. Op is neither a predecessor
8130       //    nor a successor of N. Otherwise, if Op is folded that would
8131       //    create a cycle.
8132
8133       if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
8134         continue;
8135
8136       // Check for #1.
8137       bool TryNext = false;
8138       for (SDNode *Use : BasePtr.getNode()->uses()) {
8139         if (Use == Ptr.getNode())
8140           continue;
8141
8142         // If all the uses are load / store addresses, then don't do the
8143         // transformation.
8144         if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
8145           bool RealUse = false;
8146           for (SDNode *UseUse : Use->uses()) {
8147             if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
8148               RealUse = true;
8149           }
8150
8151           if (!RealUse) {
8152             TryNext = true;
8153             break;
8154           }
8155         }
8156       }
8157
8158       if (TryNext)
8159         continue;
8160
8161       // Check for #2
8162       if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
8163         SDValue Result = isLoad
8164           ? DAG.getIndexedLoad(SDValue(N,0), SDLoc(N),
8165                                BasePtr, Offset, AM)
8166           : DAG.getIndexedStore(SDValue(N,0), SDLoc(N),
8167                                 BasePtr, Offset, AM);
8168         ++PostIndexedNodes;
8169         ++NodesCombined;
8170         DEBUG(dbgs() << "\nReplacing.5 ";
8171               N->dump(&DAG);
8172               dbgs() << "\nWith: ";
8173               Result.getNode()->dump(&DAG);
8174               dbgs() << '\n');
8175         WorklistRemover DeadNodes(*this);
8176         if (isLoad) {
8177           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
8178           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
8179         } else {
8180           DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
8181         }
8182
8183         // Finally, since the node is now dead, remove it from the graph.
8184         deleteAndRecombine(N);
8185
8186         // Replace the uses of Use with uses of the updated base value.
8187         DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
8188                                       Result.getValue(isLoad ? 1 : 0));
8189         deleteAndRecombine(Op);
8190         return true;
8191       }
8192     }
8193   }
8194
8195   return false;
8196 }
8197
8198 /// \brief Return the base-pointer arithmetic from an indexed \p LD.
8199 SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
8200   ISD::MemIndexedMode AM = LD->getAddressingMode();
8201   assert(AM != ISD::UNINDEXED);
8202   SDValue BP = LD->getOperand(1);
8203   SDValue Inc = LD->getOperand(2);
8204
8205   // Some backends use TargetConstants for load offsets, but don't expect
8206   // TargetConstants in general ADD nodes. We can convert these constants into
8207   // regular Constants (if the constant is not opaque).
8208   assert((Inc.getOpcode() != ISD::TargetConstant ||
8209           !cast<ConstantSDNode>(Inc)->isOpaque()) &&
8210          "Cannot split out indexing using opaque target constants");
8211   if (Inc.getOpcode() == ISD::TargetConstant) {
8212     ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
8213     Inc = DAG.getConstant(*ConstInc->getConstantIntValue(),
8214                           ConstInc->getValueType(0));
8215   }
8216
8217   unsigned Opc =
8218       (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
8219   return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
8220 }
8221
8222 SDValue DAGCombiner::visitLOAD(SDNode *N) {
8223   LoadSDNode *LD  = cast<LoadSDNode>(N);
8224   SDValue Chain = LD->getChain();
8225   SDValue Ptr   = LD->getBasePtr();
8226
8227   // If load is not volatile and there are no uses of the loaded value (and
8228   // the updated indexed value in case of indexed loads), change uses of the
8229   // chain value into uses of the chain input (i.e. delete the dead load).
8230   if (!LD->isVolatile()) {
8231     if (N->getValueType(1) == MVT::Other) {
8232       // Unindexed loads.
8233       if (!N->hasAnyUseOfValue(0)) {
8234         // It's not safe to use the two value CombineTo variant here. e.g.
8235         // v1, chain2 = load chain1, loc
8236         // v2, chain3 = load chain2, loc
8237         // v3         = add v2, c
8238         // Now we replace use of chain2 with chain1.  This makes the second load
8239         // isomorphic to the one we are deleting, and thus makes this load live.
8240         DEBUG(dbgs() << "\nReplacing.6 ";
8241               N->dump(&DAG);
8242               dbgs() << "\nWith chain: ";
8243               Chain.getNode()->dump(&DAG);
8244               dbgs() << "\n");
8245         WorklistRemover DeadNodes(*this);
8246         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8247
8248         if (N->use_empty())
8249           deleteAndRecombine(N);
8250
8251         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8252       }
8253     } else {
8254       // Indexed loads.
8255       assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
8256
8257       // If this load has an opaque TargetConstant offset, then we cannot split
8258       // the indexing into an add/sub directly (that TargetConstant may not be
8259       // valid for a different type of node, and we cannot convert an opaque
8260       // target constant into a regular constant).
8261       bool HasOTCInc = LD->getOperand(2).getOpcode() == ISD::TargetConstant &&
8262                        cast<ConstantSDNode>(LD->getOperand(2))->isOpaque();
8263
8264       if (!N->hasAnyUseOfValue(0) &&
8265           ((MaySplitLoadIndex && !HasOTCInc) || !N->hasAnyUseOfValue(1))) {
8266         SDValue Undef = DAG.getUNDEF(N->getValueType(0));
8267         SDValue Index;
8268         if (N->hasAnyUseOfValue(1) && MaySplitLoadIndex && !HasOTCInc) {
8269           Index = SplitIndexingFromLoad(LD);
8270           // Try to fold the base pointer arithmetic into subsequent loads and
8271           // stores.
8272           AddUsersToWorklist(N);
8273         } else
8274           Index = DAG.getUNDEF(N->getValueType(1));
8275         DEBUG(dbgs() << "\nReplacing.7 ";
8276               N->dump(&DAG);
8277               dbgs() << "\nWith: ";
8278               Undef.getNode()->dump(&DAG);
8279               dbgs() << " and 2 other values\n");
8280         WorklistRemover DeadNodes(*this);
8281         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
8282         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
8283         DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
8284         deleteAndRecombine(N);
8285         return SDValue(N, 0);   // Return N so it doesn't get rechecked!
8286       }
8287     }
8288   }
8289
8290   // If this load is directly stored, replace the load value with the stored
8291   // value.
8292   // TODO: Handle store large -> read small portion.
8293   // TODO: Handle TRUNCSTORE/LOADEXT
8294   if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
8295     if (ISD::isNON_TRUNCStore(Chain.getNode())) {
8296       StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
8297       if (PrevST->getBasePtr() == Ptr &&
8298           PrevST->getValue().getValueType() == N->getValueType(0))
8299       return CombineTo(N, Chain.getOperand(1), Chain);
8300     }
8301   }
8302
8303   // Try to infer better alignment information than the load already has.
8304   if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
8305     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
8306       if (Align > LD->getMemOperand()->getBaseAlignment()) {
8307         SDValue NewLoad =
8308                DAG.getExtLoad(LD->getExtensionType(), SDLoc(N),
8309                               LD->getValueType(0),
8310                               Chain, Ptr, LD->getPointerInfo(),
8311                               LD->getMemoryVT(),
8312                               LD->isVolatile(), LD->isNonTemporal(),
8313                               LD->isInvariant(), Align, LD->getAAInfo());
8314         return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
8315       }
8316     }
8317   }
8318
8319   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
8320                                                   : DAG.getSubtarget().useAA();
8321 #ifndef NDEBUG
8322   if (CombinerAAOnlyFunc.getNumOccurrences() &&
8323       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
8324     UseAA = false;
8325 #endif
8326   if (UseAA && LD->isUnindexed()) {
8327     // Walk up chain skipping non-aliasing memory nodes.
8328     SDValue BetterChain = FindBetterChain(N, Chain);
8329
8330     // If there is a better chain.
8331     if (Chain != BetterChain) {
8332       SDValue ReplLoad;
8333
8334       // Replace the chain to void dependency.
8335       if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
8336         ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
8337                                BetterChain, Ptr, LD->getMemOperand());
8338       } else {
8339         ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
8340                                   LD->getValueType(0),
8341                                   BetterChain, Ptr, LD->getMemoryVT(),
8342                                   LD->getMemOperand());
8343       }
8344
8345       // Create token factor to keep old chain connected.
8346       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
8347                                   MVT::Other, Chain, ReplLoad.getValue(1));
8348
8349       // Make sure the new and old chains are cleaned up.
8350       AddToWorklist(Token.getNode());
8351
8352       // Replace uses with load result and token factor. Don't add users
8353       // to work list.
8354       return CombineTo(N, ReplLoad.getValue(0), Token, false);
8355     }
8356   }
8357
8358   // Try transforming N to an indexed load.
8359   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
8360     return SDValue(N, 0);
8361
8362   // Try to slice up N to more direct loads if the slices are mapped to
8363   // different register banks or pairing can take place.
8364   if (SliceUpLoad(N))
8365     return SDValue(N, 0);
8366
8367   return SDValue();
8368 }
8369
8370 namespace {
8371 /// \brief Helper structure used to slice a load in smaller loads.
8372 /// Basically a slice is obtained from the following sequence:
8373 /// Origin = load Ty1, Base
8374 /// Shift = srl Ty1 Origin, CstTy Amount
8375 /// Inst = trunc Shift to Ty2
8376 ///
8377 /// Then, it will be rewriten into:
8378 /// Slice = load SliceTy, Base + SliceOffset
8379 /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
8380 ///
8381 /// SliceTy is deduced from the number of bits that are actually used to
8382 /// build Inst.
8383 struct LoadedSlice {
8384   /// \brief Helper structure used to compute the cost of a slice.
8385   struct Cost {
8386     /// Are we optimizing for code size.
8387     bool ForCodeSize;
8388     /// Various cost.
8389     unsigned Loads;
8390     unsigned Truncates;
8391     unsigned CrossRegisterBanksCopies;
8392     unsigned ZExts;
8393     unsigned Shift;
8394
8395     Cost(bool ForCodeSize = false)
8396         : ForCodeSize(ForCodeSize), Loads(0), Truncates(0),
8397           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {}
8398
8399     /// \brief Get the cost of one isolated slice.
8400     Cost(const LoadedSlice &LS, bool ForCodeSize = false)
8401         : ForCodeSize(ForCodeSize), Loads(1), Truncates(0),
8402           CrossRegisterBanksCopies(0), ZExts(0), Shift(0) {
8403       EVT TruncType = LS.Inst->getValueType(0);
8404       EVT LoadedType = LS.getLoadedType();
8405       if (TruncType != LoadedType &&
8406           !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
8407         ZExts = 1;
8408     }
8409
8410     /// \brief Account for slicing gain in the current cost.
8411     /// Slicing provide a few gains like removing a shift or a
8412     /// truncate. This method allows to grow the cost of the original
8413     /// load with the gain from this slice.
8414     void addSliceGain(const LoadedSlice &LS) {
8415       // Each slice saves a truncate.
8416       const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
8417       if (!TLI.isTruncateFree(LS.Inst->getValueType(0),
8418                               LS.Inst->getOperand(0).getValueType()))
8419         ++Truncates;
8420       // If there is a shift amount, this slice gets rid of it.
8421       if (LS.Shift)
8422         ++Shift;
8423       // If this slice can merge a cross register bank copy, account for it.
8424       if (LS.canMergeExpensiveCrossRegisterBankCopy())
8425         ++CrossRegisterBanksCopies;
8426     }
8427
8428     Cost &operator+=(const Cost &RHS) {
8429       Loads += RHS.Loads;
8430       Truncates += RHS.Truncates;
8431       CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
8432       ZExts += RHS.ZExts;
8433       Shift += RHS.Shift;
8434       return *this;
8435     }
8436
8437     bool operator==(const Cost &RHS) const {
8438       return Loads == RHS.Loads && Truncates == RHS.Truncates &&
8439              CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
8440              ZExts == RHS.ZExts && Shift == RHS.Shift;
8441     }
8442
8443     bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
8444
8445     bool operator<(const Cost &RHS) const {
8446       // Assume cross register banks copies are as expensive as loads.
8447       // FIXME: Do we want some more target hooks?
8448       unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
8449       unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
8450       // Unless we are optimizing for code size, consider the
8451       // expensive operation first.
8452       if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
8453         return ExpensiveOpsLHS < ExpensiveOpsRHS;
8454       return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
8455              (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
8456     }
8457
8458     bool operator>(const Cost &RHS) const { return RHS < *this; }
8459
8460     bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
8461
8462     bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
8463   };
8464   // The last instruction that represent the slice. This should be a
8465   // truncate instruction.
8466   SDNode *Inst;
8467   // The original load instruction.
8468   LoadSDNode *Origin;
8469   // The right shift amount in bits from the original load.
8470   unsigned Shift;
8471   // The DAG from which Origin came from.
8472   // This is used to get some contextual information about legal types, etc.
8473   SelectionDAG *DAG;
8474
8475   LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
8476               unsigned Shift = 0, SelectionDAG *DAG = nullptr)
8477       : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
8478
8479   LoadedSlice(const LoadedSlice &LS)
8480       : Inst(LS.Inst), Origin(LS.Origin), Shift(LS.Shift), DAG(LS.DAG) {}
8481
8482   /// \brief Get the bits used in a chunk of bits \p BitWidth large.
8483   /// \return Result is \p BitWidth and has used bits set to 1 and
8484   ///         not used bits set to 0.
8485   APInt getUsedBits() const {
8486     // Reproduce the trunc(lshr) sequence:
8487     // - Start from the truncated value.
8488     // - Zero extend to the desired bit width.
8489     // - Shift left.
8490     assert(Origin && "No original load to compare against.");
8491     unsigned BitWidth = Origin->getValueSizeInBits(0);
8492     assert(Inst && "This slice is not bound to an instruction");
8493     assert(Inst->getValueSizeInBits(0) <= BitWidth &&
8494            "Extracted slice is bigger than the whole type!");
8495     APInt UsedBits(Inst->getValueSizeInBits(0), 0);
8496     UsedBits.setAllBits();
8497     UsedBits = UsedBits.zext(BitWidth);
8498     UsedBits <<= Shift;
8499     return UsedBits;
8500   }
8501
8502   /// \brief Get the size of the slice to be loaded in bytes.
8503   unsigned getLoadedSize() const {
8504     unsigned SliceSize = getUsedBits().countPopulation();
8505     assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
8506     return SliceSize / 8;
8507   }
8508
8509   /// \brief Get the type that will be loaded for this slice.
8510   /// Note: This may not be the final type for the slice.
8511   EVT getLoadedType() const {
8512     assert(DAG && "Missing context");
8513     LLVMContext &Ctxt = *DAG->getContext();
8514     return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
8515   }
8516
8517   /// \brief Get the alignment of the load used for this slice.
8518   unsigned getAlignment() const {
8519     unsigned Alignment = Origin->getAlignment();
8520     unsigned Offset = getOffsetFromBase();
8521     if (Offset != 0)
8522       Alignment = MinAlign(Alignment, Alignment + Offset);
8523     return Alignment;
8524   }
8525
8526   /// \brief Check if this slice can be rewritten with legal operations.
8527   bool isLegal() const {
8528     // An invalid slice is not legal.
8529     if (!Origin || !Inst || !DAG)
8530       return false;
8531
8532     // Offsets are for indexed load only, we do not handle that.
8533     if (Origin->getOffset().getOpcode() != ISD::UNDEF)
8534       return false;
8535
8536     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8537
8538     // Check that the type is legal.
8539     EVT SliceType = getLoadedType();
8540     if (!TLI.isTypeLegal(SliceType))
8541       return false;
8542
8543     // Check that the load is legal for this type.
8544     if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
8545       return false;
8546
8547     // Check that the offset can be computed.
8548     // 1. Check its type.
8549     EVT PtrType = Origin->getBasePtr().getValueType();
8550     if (PtrType == MVT::Untyped || PtrType.isExtended())
8551       return false;
8552
8553     // 2. Check that it fits in the immediate.
8554     if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
8555       return false;
8556
8557     // 3. Check that the computation is legal.
8558     if (!TLI.isOperationLegal(ISD::ADD, PtrType))
8559       return false;
8560
8561     // Check that the zext is legal if it needs one.
8562     EVT TruncateType = Inst->getValueType(0);
8563     if (TruncateType != SliceType &&
8564         !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
8565       return false;
8566
8567     return true;
8568   }
8569
8570   /// \brief Get the offset in bytes of this slice in the original chunk of
8571   /// bits.
8572   /// \pre DAG != nullptr.
8573   uint64_t getOffsetFromBase() const {
8574     assert(DAG && "Missing context.");
8575     bool IsBigEndian =
8576         DAG->getTargetLoweringInfo().getDataLayout()->isBigEndian();
8577     assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
8578     uint64_t Offset = Shift / 8;
8579     unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
8580     assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
8581            "The size of the original loaded type is not a multiple of a"
8582            " byte.");
8583     // If Offset is bigger than TySizeInBytes, it means we are loading all
8584     // zeros. This should have been optimized before in the process.
8585     assert(TySizeInBytes > Offset &&
8586            "Invalid shift amount for given loaded size");
8587     if (IsBigEndian)
8588       Offset = TySizeInBytes - Offset - getLoadedSize();
8589     return Offset;
8590   }
8591
8592   /// \brief Generate the sequence of instructions to load the slice
8593   /// represented by this object and redirect the uses of this slice to
8594   /// this new sequence of instructions.
8595   /// \pre this->Inst && this->Origin are valid Instructions and this
8596   /// object passed the legal check: LoadedSlice::isLegal returned true.
8597   /// \return The last instruction of the sequence used to load the slice.
8598   SDValue loadSlice() const {
8599     assert(Inst && Origin && "Unable to replace a non-existing slice.");
8600     const SDValue &OldBaseAddr = Origin->getBasePtr();
8601     SDValue BaseAddr = OldBaseAddr;
8602     // Get the offset in that chunk of bytes w.r.t. the endianess.
8603     int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
8604     assert(Offset >= 0 && "Offset too big to fit in int64_t!");
8605     if (Offset) {
8606       // BaseAddr = BaseAddr + Offset.
8607       EVT ArithType = BaseAddr.getValueType();
8608       BaseAddr = DAG->getNode(ISD::ADD, SDLoc(Origin), ArithType, BaseAddr,
8609                               DAG->getConstant(Offset, ArithType));
8610     }
8611
8612     // Create the type of the loaded slice according to its size.
8613     EVT SliceType = getLoadedType();
8614
8615     // Create the load for the slice.
8616     SDValue LastInst = DAG->getLoad(
8617         SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
8618         Origin->getPointerInfo().getWithOffset(Offset), Origin->isVolatile(),
8619         Origin->isNonTemporal(), Origin->isInvariant(), getAlignment());
8620     // If the final type is not the same as the loaded type, this means that
8621     // we have to pad with zero. Create a zero extend for that.
8622     EVT FinalType = Inst->getValueType(0);
8623     if (SliceType != FinalType)
8624       LastInst =
8625           DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
8626     return LastInst;
8627   }
8628
8629   /// \brief Check if this slice can be merged with an expensive cross register
8630   /// bank copy. E.g.,
8631   /// i = load i32
8632   /// f = bitcast i32 i to float
8633   bool canMergeExpensiveCrossRegisterBankCopy() const {
8634     if (!Inst || !Inst->hasOneUse())
8635       return false;
8636     SDNode *Use = *Inst->use_begin();
8637     if (Use->getOpcode() != ISD::BITCAST)
8638       return false;
8639     assert(DAG && "Missing context");
8640     const TargetLowering &TLI = DAG->getTargetLoweringInfo();
8641     EVT ResVT = Use->getValueType(0);
8642     const TargetRegisterClass *ResRC = TLI.getRegClassFor(ResVT.getSimpleVT());
8643     const TargetRegisterClass *ArgRC =
8644         TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT());
8645     if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
8646       return false;
8647
8648     // At this point, we know that we perform a cross-register-bank copy.
8649     // Check if it is expensive.
8650     const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
8651     // Assume bitcasts are cheap, unless both register classes do not
8652     // explicitly share a common sub class.
8653     if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
8654       return false;
8655
8656     // Check if it will be merged with the load.
8657     // 1. Check the alignment constraint.
8658     unsigned RequiredAlignment = TLI.getDataLayout()->getABITypeAlignment(
8659         ResVT.getTypeForEVT(*DAG->getContext()));
8660
8661     if (RequiredAlignment > getAlignment())
8662       return false;
8663
8664     // 2. Check that the load is a legal operation for that type.
8665     if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
8666       return false;
8667
8668     // 3. Check that we do not have a zext in the way.
8669     if (Inst->getValueType(0) != getLoadedType())
8670       return false;
8671
8672     return true;
8673   }
8674 };
8675 }
8676
8677 /// \brief Check that all bits set in \p UsedBits form a dense region, i.e.,
8678 /// \p UsedBits looks like 0..0 1..1 0..0.
8679 static bool areUsedBitsDense(const APInt &UsedBits) {
8680   // If all the bits are one, this is dense!
8681   if (UsedBits.isAllOnesValue())
8682     return true;
8683
8684   // Get rid of the unused bits on the right.
8685   APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
8686   // Get rid of the unused bits on the left.
8687   if (NarrowedUsedBits.countLeadingZeros())
8688     NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
8689   // Check that the chunk of bits is completely used.
8690   return NarrowedUsedBits.isAllOnesValue();
8691 }
8692
8693 /// \brief Check whether or not \p First and \p Second are next to each other
8694 /// in memory. This means that there is no hole between the bits loaded
8695 /// by \p First and the bits loaded by \p Second.
8696 static bool areSlicesNextToEachOther(const LoadedSlice &First,
8697                                      const LoadedSlice &Second) {
8698   assert(First.Origin == Second.Origin && First.Origin &&
8699          "Unable to match different memory origins.");
8700   APInt UsedBits = First.getUsedBits();
8701   assert((UsedBits & Second.getUsedBits()) == 0 &&
8702          "Slices are not supposed to overlap.");
8703   UsedBits |= Second.getUsedBits();
8704   return areUsedBitsDense(UsedBits);
8705 }
8706
8707 /// \brief Adjust the \p GlobalLSCost according to the target
8708 /// paring capabilities and the layout of the slices.
8709 /// \pre \p GlobalLSCost should account for at least as many loads as
8710 /// there is in the slices in \p LoadedSlices.
8711 static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8712                                  LoadedSlice::Cost &GlobalLSCost) {
8713   unsigned NumberOfSlices = LoadedSlices.size();
8714   // If there is less than 2 elements, no pairing is possible.
8715   if (NumberOfSlices < 2)
8716     return;
8717
8718   // Sort the slices so that elements that are likely to be next to each
8719   // other in memory are next to each other in the list.
8720   std::sort(LoadedSlices.begin(), LoadedSlices.end(),
8721             [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
8722     assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
8723     return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
8724   });
8725   const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
8726   // First (resp. Second) is the first (resp. Second) potentially candidate
8727   // to be placed in a paired load.
8728   const LoadedSlice *First = nullptr;
8729   const LoadedSlice *Second = nullptr;
8730   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
8731                 // Set the beginning of the pair.
8732                                                            First = Second) {
8733
8734     Second = &LoadedSlices[CurrSlice];
8735
8736     // If First is NULL, it means we start a new pair.
8737     // Get to the next slice.
8738     if (!First)
8739       continue;
8740
8741     EVT LoadedType = First->getLoadedType();
8742
8743     // If the types of the slices are different, we cannot pair them.
8744     if (LoadedType != Second->getLoadedType())
8745       continue;
8746
8747     // Check if the target supplies paired loads for this type.
8748     unsigned RequiredAlignment = 0;
8749     if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
8750       // move to the next pair, this type is hopeless.
8751       Second = nullptr;
8752       continue;
8753     }
8754     // Check if we meet the alignment requirement.
8755     if (RequiredAlignment > First->getAlignment())
8756       continue;
8757
8758     // Check that both loads are next to each other in memory.
8759     if (!areSlicesNextToEachOther(*First, *Second))
8760       continue;
8761
8762     assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
8763     --GlobalLSCost.Loads;
8764     // Move to the next pair.
8765     Second = nullptr;
8766   }
8767 }
8768
8769 /// \brief Check the profitability of all involved LoadedSlice.
8770 /// Currently, it is considered profitable if there is exactly two
8771 /// involved slices (1) which are (2) next to each other in memory, and
8772 /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
8773 ///
8774 /// Note: The order of the elements in \p LoadedSlices may be modified, but not
8775 /// the elements themselves.
8776 ///
8777 /// FIXME: When the cost model will be mature enough, we can relax
8778 /// constraints (1) and (2).
8779 static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
8780                                 const APInt &UsedBits, bool ForCodeSize) {
8781   unsigned NumberOfSlices = LoadedSlices.size();
8782   if (StressLoadSlicing)
8783     return NumberOfSlices > 1;
8784
8785   // Check (1).
8786   if (NumberOfSlices != 2)
8787     return false;
8788
8789   // Check (2).
8790   if (!areUsedBitsDense(UsedBits))
8791     return false;
8792
8793   // Check (3).
8794   LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
8795   // The original code has one big load.
8796   OrigCost.Loads = 1;
8797   for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
8798     const LoadedSlice &LS = LoadedSlices[CurrSlice];
8799     // Accumulate the cost of all the slices.
8800     LoadedSlice::Cost SliceCost(LS, ForCodeSize);
8801     GlobalSlicingCost += SliceCost;
8802
8803     // Account as cost in the original configuration the gain obtained
8804     // with the current slices.
8805     OrigCost.addSliceGain(LS);
8806   }
8807
8808   // If the target supports paired load, adjust the cost accordingly.
8809   adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
8810   return OrigCost > GlobalSlicingCost;
8811 }
8812
8813 /// \brief If the given load, \p LI, is used only by trunc or trunc(lshr)
8814 /// operations, split it in the various pieces being extracted.
8815 ///
8816 /// This sort of thing is introduced by SROA.
8817 /// This slicing takes care not to insert overlapping loads.
8818 /// \pre LI is a simple load (i.e., not an atomic or volatile load).
8819 bool DAGCombiner::SliceUpLoad(SDNode *N) {
8820   if (Level < AfterLegalizeDAG)
8821     return false;
8822
8823   LoadSDNode *LD = cast<LoadSDNode>(N);
8824   if (LD->isVolatile() || !ISD::isNormalLoad(LD) ||
8825       !LD->getValueType(0).isInteger())
8826     return false;
8827
8828   // Keep track of already used bits to detect overlapping values.
8829   // In that case, we will just abort the transformation.
8830   APInt UsedBits(LD->getValueSizeInBits(0), 0);
8831
8832   SmallVector<LoadedSlice, 4> LoadedSlices;
8833
8834   // Check if this load is used as several smaller chunks of bits.
8835   // Basically, look for uses in trunc or trunc(lshr) and record a new chain
8836   // of computation for each trunc.
8837   for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
8838        UI != UIEnd; ++UI) {
8839     // Skip the uses of the chain.
8840     if (UI.getUse().getResNo() != 0)
8841       continue;
8842
8843     SDNode *User = *UI;
8844     unsigned Shift = 0;
8845
8846     // Check if this is a trunc(lshr).
8847     if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
8848         isa<ConstantSDNode>(User->getOperand(1))) {
8849       Shift = cast<ConstantSDNode>(User->getOperand(1))->getZExtValue();
8850       User = *User->use_begin();
8851     }
8852
8853     // At this point, User is a Truncate, iff we encountered, trunc or
8854     // trunc(lshr).
8855     if (User->getOpcode() != ISD::TRUNCATE)
8856       return false;
8857
8858     // The width of the type must be a power of 2 and greater than 8-bits.
8859     // Otherwise the load cannot be represented in LLVM IR.
8860     // Moreover, if we shifted with a non-8-bits multiple, the slice
8861     // will be across several bytes. We do not support that.
8862     unsigned Width = User->getValueSizeInBits(0);
8863     if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
8864       return 0;
8865
8866     // Build the slice for this chain of computations.
8867     LoadedSlice LS(User, LD, Shift, &DAG);
8868     APInt CurrentUsedBits = LS.getUsedBits();
8869
8870     // Check if this slice overlaps with another.
8871     if ((CurrentUsedBits & UsedBits) != 0)
8872       return false;
8873     // Update the bits used globally.
8874     UsedBits |= CurrentUsedBits;
8875
8876     // Check if the new slice would be legal.
8877     if (!LS.isLegal())
8878       return false;
8879
8880     // Record the slice.
8881     LoadedSlices.push_back(LS);
8882   }
8883
8884   // Abort slicing if it does not seem to be profitable.
8885   if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
8886     return false;
8887
8888   ++SlicedLoads;
8889
8890   // Rewrite each chain to use an independent load.
8891   // By construction, each chain can be represented by a unique load.
8892
8893   // Prepare the argument for the new token factor for all the slices.
8894   SmallVector<SDValue, 8> ArgChains;
8895   for (SmallVectorImpl<LoadedSlice>::const_iterator
8896            LSIt = LoadedSlices.begin(),
8897            LSItEnd = LoadedSlices.end();
8898        LSIt != LSItEnd; ++LSIt) {
8899     SDValue SliceInst = LSIt->loadSlice();
8900     CombineTo(LSIt->Inst, SliceInst, true);
8901     if (SliceInst.getNode()->getOpcode() != ISD::LOAD)
8902       SliceInst = SliceInst.getOperand(0);
8903     assert(SliceInst->getOpcode() == ISD::LOAD &&
8904            "It takes more than a zext to get to the loaded slice!!");
8905     ArgChains.push_back(SliceInst.getValue(1));
8906   }
8907
8908   SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
8909                               ArgChains);
8910   DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
8911   return true;
8912 }
8913
8914 /// Check to see if V is (and load (ptr), imm), where the load is having
8915 /// specific bytes cleared out.  If so, return the byte size being masked out
8916 /// and the shift amount.
8917 static std::pair<unsigned, unsigned>
8918 CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
8919   std::pair<unsigned, unsigned> Result(0, 0);
8920
8921   // Check for the structure we're looking for.
8922   if (V->getOpcode() != ISD::AND ||
8923       !isa<ConstantSDNode>(V->getOperand(1)) ||
8924       !ISD::isNormalLoad(V->getOperand(0).getNode()))
8925     return Result;
8926
8927   // Check the chain and pointer.
8928   LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
8929   if (LD->getBasePtr() != Ptr) return Result;  // Not from same pointer.
8930
8931   // The store should be chained directly to the load or be an operand of a
8932   // tokenfactor.
8933   if (LD == Chain.getNode())
8934     ; // ok.
8935   else if (Chain->getOpcode() != ISD::TokenFactor)
8936     return Result; // Fail.
8937   else {
8938     bool isOk = false;
8939     for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
8940       if (Chain->getOperand(i).getNode() == LD) {
8941         isOk = true;
8942         break;
8943       }
8944     if (!isOk) return Result;
8945   }
8946
8947   // This only handles simple types.
8948   if (V.getValueType() != MVT::i16 &&
8949       V.getValueType() != MVT::i32 &&
8950       V.getValueType() != MVT::i64)
8951     return Result;
8952
8953   // Check the constant mask.  Invert it so that the bits being masked out are
8954   // 0 and the bits being kept are 1.  Use getSExtValue so that leading bits
8955   // follow the sign bit for uniformity.
8956   uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
8957   unsigned NotMaskLZ = countLeadingZeros(NotMask);
8958   if (NotMaskLZ & 7) return Result;  // Must be multiple of a byte.
8959   unsigned NotMaskTZ = countTrailingZeros(NotMask);
8960   if (NotMaskTZ & 7) return Result;  // Must be multiple of a byte.
8961   if (NotMaskLZ == 64) return Result;  // All zero mask.
8962
8963   // See if we have a continuous run of bits.  If so, we have 0*1+0*
8964   if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
8965     return Result;
8966
8967   // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
8968   if (V.getValueType() != MVT::i64 && NotMaskLZ)
8969     NotMaskLZ -= 64-V.getValueSizeInBits();
8970
8971   unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
8972   switch (MaskedBytes) {
8973   case 1:
8974   case 2:
8975   case 4: break;
8976   default: return Result; // All one mask, or 5-byte mask.
8977   }
8978
8979   // Verify that the first bit starts at a multiple of mask so that the access
8980   // is aligned the same as the access width.
8981   if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
8982
8983   Result.first = MaskedBytes;
8984   Result.second = NotMaskTZ/8;
8985   return Result;
8986 }
8987
8988
8989 /// Check to see if IVal is something that provides a value as specified by
8990 /// MaskInfo. If so, replace the specified store with a narrower store of
8991 /// truncated IVal.
8992 static SDNode *
8993 ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
8994                                 SDValue IVal, StoreSDNode *St,
8995                                 DAGCombiner *DC) {
8996   unsigned NumBytes = MaskInfo.first;
8997   unsigned ByteShift = MaskInfo.second;
8998   SelectionDAG &DAG = DC->getDAG();
8999
9000   // Check to see if IVal is all zeros in the part being masked in by the 'or'
9001   // that uses this.  If not, this is not a replacement.
9002   APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
9003                                   ByteShift*8, (ByteShift+NumBytes)*8);
9004   if (!DAG.MaskedValueIsZero(IVal, Mask)) return nullptr;
9005
9006   // Check that it is legal on the target to do this.  It is legal if the new
9007   // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
9008   // legalization.
9009   MVT VT = MVT::getIntegerVT(NumBytes*8);
9010   if (!DC->isTypeLegal(VT))
9011     return nullptr;
9012
9013   // Okay, we can do this!  Replace the 'St' store with a store of IVal that is
9014   // shifted by ByteShift and truncated down to NumBytes.
9015   if (ByteShift)
9016     IVal = DAG.getNode(ISD::SRL, SDLoc(IVal), IVal.getValueType(), IVal,
9017                        DAG.getConstant(ByteShift*8,
9018                                     DC->getShiftAmountTy(IVal.getValueType())));
9019
9020   // Figure out the offset for the store and the alignment of the access.
9021   unsigned StOffset;
9022   unsigned NewAlign = St->getAlignment();
9023
9024   if (DAG.getTargetLoweringInfo().isLittleEndian())
9025     StOffset = ByteShift;
9026   else
9027     StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
9028
9029   SDValue Ptr = St->getBasePtr();
9030   if (StOffset) {
9031     Ptr = DAG.getNode(ISD::ADD, SDLoc(IVal), Ptr.getValueType(),
9032                       Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
9033     NewAlign = MinAlign(NewAlign, StOffset);
9034   }
9035
9036   // Truncate down to the new size.
9037   IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
9038
9039   ++OpsNarrowed;
9040   return DAG.getStore(St->getChain(), SDLoc(St), IVal, Ptr,
9041                       St->getPointerInfo().getWithOffset(StOffset),
9042                       false, false, NewAlign).getNode();
9043 }
9044
9045
9046 /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
9047 /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
9048 /// narrowing the load and store if it would end up being a win for performance
9049 /// or code size.
9050 SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
9051   StoreSDNode *ST  = cast<StoreSDNode>(N);
9052   if (ST->isVolatile())
9053     return SDValue();
9054
9055   SDValue Chain = ST->getChain();
9056   SDValue Value = ST->getValue();
9057   SDValue Ptr   = ST->getBasePtr();
9058   EVT VT = Value.getValueType();
9059
9060   if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
9061     return SDValue();
9062
9063   unsigned Opc = Value.getOpcode();
9064
9065   // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
9066   // is a byte mask indicating a consecutive number of bytes, check to see if
9067   // Y is known to provide just those bytes.  If so, we try to replace the
9068   // load + replace + store sequence with a single (narrower) store, which makes
9069   // the load dead.
9070   if (Opc == ISD::OR) {
9071     std::pair<unsigned, unsigned> MaskedLoad;
9072     MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
9073     if (MaskedLoad.first)
9074       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9075                                                   Value.getOperand(1), ST,this))
9076         return SDValue(NewST, 0);
9077
9078     // Or is commutative, so try swapping X and Y.
9079     MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
9080     if (MaskedLoad.first)
9081       if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
9082                                                   Value.getOperand(0), ST,this))
9083         return SDValue(NewST, 0);
9084   }
9085
9086   if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
9087       Value.getOperand(1).getOpcode() != ISD::Constant)
9088     return SDValue();
9089
9090   SDValue N0 = Value.getOperand(0);
9091   if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
9092       Chain == SDValue(N0.getNode(), 1)) {
9093     LoadSDNode *LD = cast<LoadSDNode>(N0);
9094     if (LD->getBasePtr() != Ptr ||
9095         LD->getPointerInfo().getAddrSpace() !=
9096         ST->getPointerInfo().getAddrSpace())
9097       return SDValue();
9098
9099     // Find the type to narrow it the load / op / store to.
9100     SDValue N1 = Value.getOperand(1);
9101     unsigned BitWidth = N1.getValueSizeInBits();
9102     APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
9103     if (Opc == ISD::AND)
9104       Imm ^= APInt::getAllOnesValue(BitWidth);
9105     if (Imm == 0 || Imm.isAllOnesValue())
9106       return SDValue();
9107     unsigned ShAmt = Imm.countTrailingZeros();
9108     unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
9109     unsigned NewBW = NextPowerOf2(MSB - ShAmt);
9110     EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9111     while (NewBW < BitWidth &&
9112            !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
9113              TLI.isNarrowingProfitable(VT, NewVT))) {
9114       NewBW = NextPowerOf2(NewBW);
9115       NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
9116     }
9117     if (NewBW >= BitWidth)
9118       return SDValue();
9119
9120     // If the lsb changed does not start at the type bitwidth boundary,
9121     // start at the previous one.
9122     if (ShAmt % NewBW)
9123       ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
9124     APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
9125                                    std::min(BitWidth, ShAmt + NewBW));
9126     if ((Imm & Mask) == Imm) {
9127       APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
9128       if (Opc == ISD::AND)
9129         NewImm ^= APInt::getAllOnesValue(NewBW);
9130       uint64_t PtrOff = ShAmt / 8;
9131       // For big endian targets, we need to adjust the offset to the pointer to
9132       // load the correct bytes.
9133       if (TLI.isBigEndian())
9134         PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
9135
9136       unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
9137       Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
9138       if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
9139         return SDValue();
9140
9141       SDValue NewPtr = DAG.getNode(ISD::ADD, SDLoc(LD),
9142                                    Ptr.getValueType(), Ptr,
9143                                    DAG.getConstant(PtrOff, Ptr.getValueType()));
9144       SDValue NewLD = DAG.getLoad(NewVT, SDLoc(N0),
9145                                   LD->getChain(), NewPtr,
9146                                   LD->getPointerInfo().getWithOffset(PtrOff),
9147                                   LD->isVolatile(), LD->isNonTemporal(),
9148                                   LD->isInvariant(), NewAlign,
9149                                   LD->getAAInfo());
9150       SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
9151                                    DAG.getConstant(NewImm, NewVT));
9152       SDValue NewST = DAG.getStore(Chain, SDLoc(N),
9153                                    NewVal, NewPtr,
9154                                    ST->getPointerInfo().getWithOffset(PtrOff),
9155                                    false, false, NewAlign);
9156
9157       AddToWorklist(NewPtr.getNode());
9158       AddToWorklist(NewLD.getNode());
9159       AddToWorklist(NewVal.getNode());
9160       WorklistRemover DeadNodes(*this);
9161       DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
9162       ++OpsNarrowed;
9163       return NewST;
9164     }
9165   }
9166
9167   return SDValue();
9168 }
9169
9170 /// For a given floating point load / store pair, if the load value isn't used
9171 /// by any other operations, then consider transforming the pair to integer
9172 /// load / store operations if the target deems the transformation profitable.
9173 SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
9174   StoreSDNode *ST  = cast<StoreSDNode>(N);
9175   SDValue Chain = ST->getChain();
9176   SDValue Value = ST->getValue();
9177   if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
9178       Value.hasOneUse() &&
9179       Chain == SDValue(Value.getNode(), 1)) {
9180     LoadSDNode *LD = cast<LoadSDNode>(Value);
9181     EVT VT = LD->getMemoryVT();
9182     if (!VT.isFloatingPoint() ||
9183         VT != ST->getMemoryVT() ||
9184         LD->isNonTemporal() ||
9185         ST->isNonTemporal() ||
9186         LD->getPointerInfo().getAddrSpace() != 0 ||
9187         ST->getPointerInfo().getAddrSpace() != 0)
9188       return SDValue();
9189
9190     EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
9191     if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
9192         !TLI.isOperationLegal(ISD::STORE, IntVT) ||
9193         !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
9194         !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
9195       return SDValue();
9196
9197     unsigned LDAlign = LD->getAlignment();
9198     unsigned STAlign = ST->getAlignment();
9199     Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
9200     unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
9201     if (LDAlign < ABIAlign || STAlign < ABIAlign)
9202       return SDValue();
9203
9204     SDValue NewLD = DAG.getLoad(IntVT, SDLoc(Value),
9205                                 LD->getChain(), LD->getBasePtr(),
9206                                 LD->getPointerInfo(),
9207                                 false, false, false, LDAlign);
9208
9209     SDValue NewST = DAG.getStore(NewLD.getValue(1), SDLoc(N),
9210                                  NewLD, ST->getBasePtr(),
9211                                  ST->getPointerInfo(),
9212                                  false, false, STAlign);
9213
9214     AddToWorklist(NewLD.getNode());
9215     AddToWorklist(NewST.getNode());
9216     WorklistRemover DeadNodes(*this);
9217     DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
9218     ++LdStFP2Int;
9219     return NewST;
9220   }
9221
9222   return SDValue();
9223 }
9224
9225 /// Helper struct to parse and store a memory address as base + index + offset.
9226 /// We ignore sign extensions when it is safe to do so.
9227 /// The following two expressions are not equivalent. To differentiate we need
9228 /// to store whether there was a sign extension involved in the index
9229 /// computation.
9230 ///  (load (i64 add (i64 copyfromreg %c)
9231 ///                 (i64 signextend (add (i8 load %index)
9232 ///                                      (i8 1))))
9233 /// vs
9234 ///
9235 /// (load (i64 add (i64 copyfromreg %c)
9236 ///                (i64 signextend (i32 add (i32 signextend (i8 load %index))
9237 ///                                         (i32 1)))))
9238 struct BaseIndexOffset {
9239   SDValue Base;
9240   SDValue Index;
9241   int64_t Offset;
9242   bool IsIndexSignExt;
9243
9244   BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
9245
9246   BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
9247                   bool IsIndexSignExt) :
9248     Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
9249
9250   bool equalBaseIndex(const BaseIndexOffset &Other) {
9251     return Other.Base == Base && Other.Index == Index &&
9252       Other.IsIndexSignExt == IsIndexSignExt;
9253   }
9254
9255   /// Parses tree in Ptr for base, index, offset addresses.
9256   static BaseIndexOffset match(SDValue Ptr) {
9257     bool IsIndexSignExt = false;
9258
9259     // We only can pattern match BASE + INDEX + OFFSET. If Ptr is not an ADD
9260     // instruction, then it could be just the BASE or everything else we don't
9261     // know how to handle. Just use Ptr as BASE and give up.
9262     if (Ptr->getOpcode() != ISD::ADD)
9263       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9264
9265     // We know that we have at least an ADD instruction. Try to pattern match
9266     // the simple case of BASE + OFFSET.
9267     if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
9268       int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
9269       return  BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
9270                               IsIndexSignExt);
9271     }
9272
9273     // Inside a loop the current BASE pointer is calculated using an ADD and a
9274     // MUL instruction. In this case Ptr is the actual BASE pointer.
9275     // (i64 add (i64 %array_ptr)
9276     //          (i64 mul (i64 %induction_var)
9277     //                   (i64 %element_size)))
9278     if (Ptr->getOperand(1)->getOpcode() == ISD::MUL)
9279       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9280
9281     // Look at Base + Index + Offset cases.
9282     SDValue Base = Ptr->getOperand(0);
9283     SDValue IndexOffset = Ptr->getOperand(1);
9284
9285     // Skip signextends.
9286     if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
9287       IndexOffset = IndexOffset->getOperand(0);
9288       IsIndexSignExt = true;
9289     }
9290
9291     // Either the case of Base + Index (no offset) or something else.
9292     if (IndexOffset->getOpcode() != ISD::ADD)
9293       return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
9294
9295     // Now we have the case of Base + Index + offset.
9296     SDValue Index = IndexOffset->getOperand(0);
9297     SDValue Offset = IndexOffset->getOperand(1);
9298
9299     if (!isa<ConstantSDNode>(Offset))
9300       return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
9301
9302     // Ignore signextends.
9303     if (Index->getOpcode() == ISD::SIGN_EXTEND) {
9304       Index = Index->getOperand(0);
9305       IsIndexSignExt = true;
9306     } else IsIndexSignExt = false;
9307
9308     int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
9309     return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
9310   }
9311 };
9312
9313 /// Holds a pointer to an LSBaseSDNode as well as information on where it
9314 /// is located in a sequence of memory operations connected by a chain.
9315 struct MemOpLink {
9316   MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
9317     MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
9318   // Ptr to the mem node.
9319   LSBaseSDNode *MemNode;
9320   // Offset from the base ptr.
9321   int64_t OffsetFromBase;
9322   // What is the sequence number of this mem node.
9323   // Lowest mem operand in the DAG starts at zero.
9324   unsigned SequenceNum;
9325 };
9326
9327 bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
9328   EVT MemVT = St->getMemoryVT();
9329   int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
9330   bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
9331     hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
9332
9333   // Don't merge vectors into wider inputs.
9334   if (MemVT.isVector() || !MemVT.isSimple())
9335     return false;
9336
9337   // Perform an early exit check. Do not bother looking at stored values that
9338   // are not constants or loads.
9339   SDValue StoredVal = St->getValue();
9340   bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
9341   if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
9342       !IsLoadSrc)
9343     return false;
9344
9345   // Only look at ends of store sequences.
9346   SDValue Chain = SDValue(St, 0);
9347   if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
9348     return false;
9349
9350   // This holds the base pointer, index, and the offset in bytes from the base
9351   // pointer.
9352   BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
9353
9354   // We must have a base and an offset.
9355   if (!BasePtr.Base.getNode())
9356     return false;
9357
9358   // Do not handle stores to undef base pointers.
9359   if (BasePtr.Base.getOpcode() == ISD::UNDEF)
9360     return false;
9361
9362   // Save the LoadSDNodes that we find in the chain.
9363   // We need to make sure that these nodes do not interfere with
9364   // any of the store nodes.
9365   SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
9366
9367   // Save the StoreSDNodes that we find in the chain.
9368   SmallVector<MemOpLink, 8> StoreNodes;
9369
9370   // Walk up the chain and look for nodes with offsets from the same
9371   // base pointer. Stop when reaching an instruction with a different kind
9372   // or instruction which has a different base pointer.
9373   unsigned Seq = 0;
9374   StoreSDNode *Index = St;
9375   while (Index) {
9376     // If the chain has more than one use, then we can't reorder the mem ops.
9377     if (Index != St && !SDValue(Index, 0)->hasOneUse())
9378       break;
9379
9380     // Find the base pointer and offset for this memory node.
9381     BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
9382
9383     // Check that the base pointer is the same as the original one.
9384     if (!Ptr.equalBaseIndex(BasePtr))
9385       break;
9386
9387     // Check that the alignment is the same.
9388     if (Index->getAlignment() != St->getAlignment())
9389       break;
9390
9391     // The memory operands must not be volatile.
9392     if (Index->isVolatile() || Index->isIndexed())
9393       break;
9394
9395     // No truncation.
9396     if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
9397       if (St->isTruncatingStore())
9398         break;
9399
9400     // The stored memory type must be the same.
9401     if (Index->getMemoryVT() != MemVT)
9402       break;
9403
9404     // We do not allow unaligned stores because we want to prevent overriding
9405     // stores.
9406     if (Index->getAlignment()*8 != MemVT.getSizeInBits())
9407       break;
9408
9409     // We found a potential memory operand to merge.
9410     StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
9411
9412     // Find the next memory operand in the chain. If the next operand in the
9413     // chain is a store then move up and continue the scan with the next
9414     // memory operand. If the next operand is a load save it and use alias
9415     // information to check if it interferes with anything.
9416     SDNode *NextInChain = Index->getChain().getNode();
9417     while (1) {
9418       if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
9419         // We found a store node. Use it for the next iteration.
9420         Index = STn;
9421         break;
9422       } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
9423         if (Ldn->isVolatile()) {
9424           Index = nullptr;
9425           break;
9426         }
9427
9428         // Save the load node for later. Continue the scan.
9429         AliasLoadNodes.push_back(Ldn);
9430         NextInChain = Ldn->getChain().getNode();
9431         continue;
9432       } else {
9433         Index = nullptr;
9434         break;
9435       }
9436     }
9437   }
9438
9439   // Check if there is anything to merge.
9440   if (StoreNodes.size() < 2)
9441     return false;
9442
9443   // Sort the memory operands according to their distance from the base pointer.
9444   std::sort(StoreNodes.begin(), StoreNodes.end(),
9445             [](MemOpLink LHS, MemOpLink RHS) {
9446     return LHS.OffsetFromBase < RHS.OffsetFromBase ||
9447            (LHS.OffsetFromBase == RHS.OffsetFromBase &&
9448             LHS.SequenceNum > RHS.SequenceNum);
9449   });
9450
9451   // Scan the memory operations on the chain and find the first non-consecutive
9452   // store memory address.
9453   unsigned LastConsecutiveStore = 0;
9454   int64_t StartAddress = StoreNodes[0].OffsetFromBase;
9455   for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
9456
9457     // Check that the addresses are consecutive starting from the second
9458     // element in the list of stores.
9459     if (i > 0) {
9460       int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
9461       if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9462         break;
9463     }
9464
9465     bool Alias = false;
9466     // Check if this store interferes with any of the loads that we found.
9467     for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
9468       if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
9469         Alias = true;
9470         break;
9471       }
9472     // We found a load that alias with this store. Stop the sequence.
9473     if (Alias)
9474       break;
9475
9476     // Mark this node as useful.
9477     LastConsecutiveStore = i;
9478   }
9479
9480   // The node with the lowest store address.
9481   LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
9482
9483   // Store the constants into memory as one consecutive store.
9484   if (!IsLoadSrc) {
9485     unsigned LastLegalType = 0;
9486     unsigned LastLegalVectorType = 0;
9487     bool NonZero = false;
9488     for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9489       StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9490       SDValue StoredVal = St->getValue();
9491
9492       if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
9493         NonZero |= !C->isNullValue();
9494       } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
9495         NonZero |= !C->getConstantFPValue()->isNullValue();
9496       } else {
9497         // Non-constant.
9498         break;
9499       }
9500
9501       // Find a legal type for the constant store.
9502       unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9503       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9504       if (TLI.isTypeLegal(StoreTy))
9505         LastLegalType = i+1;
9506       // Or check whether a truncstore is legal.
9507       else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9508                TargetLowering::TypePromoteInteger) {
9509         EVT LegalizedStoredValueTy =
9510           TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
9511         if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
9512           LastLegalType = i+1;
9513       }
9514
9515       // Find a legal type for the vector store.
9516       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9517       if (TLI.isTypeLegal(Ty))
9518         LastLegalVectorType = i + 1;
9519     }
9520
9521     // We only use vectors if the constant is known to be zero and the
9522     // function is not marked with the noimplicitfloat attribute.
9523     if (NonZero || NoVectors)
9524       LastLegalVectorType = 0;
9525
9526     // Check if we found a legal integer type to store.
9527     if (LastLegalType == 0 && LastLegalVectorType == 0)
9528       return false;
9529
9530     bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
9531     unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
9532
9533     // Make sure we have something to merge.
9534     if (NumElem < 2)
9535       return false;
9536
9537     unsigned EarliestNodeUsed = 0;
9538     for (unsigned i=0; i < NumElem; ++i) {
9539       // Find a chain for the new wide-store operand. Notice that some
9540       // of the store nodes that we found may not be selected for inclusion
9541       // in the wide store. The chain we use needs to be the chain of the
9542       // earliest store node which is *used* and replaced by the wide store.
9543       if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9544         EarliestNodeUsed = i;
9545     }
9546
9547     // The earliest Node in the DAG.
9548     LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9549     SDLoc DL(StoreNodes[0].MemNode);
9550
9551     SDValue StoredVal;
9552     if (UseVector) {
9553       // Find a legal type for the vector store.
9554       EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9555       assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
9556       StoredVal = DAG.getConstant(0, Ty);
9557     } else {
9558       unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9559       APInt StoreInt(StoreBW, 0);
9560
9561       // Construct a single integer constant which is made of the smaller
9562       // constant inputs.
9563       bool IsLE = TLI.isLittleEndian();
9564       for (unsigned i = 0; i < NumElem ; ++i) {
9565         unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
9566         StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
9567         SDValue Val = St->getValue();
9568         StoreInt<<=ElementSizeBytes*8;
9569         if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
9570           StoreInt|=C->getAPIntValue().zext(StoreBW);
9571         } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
9572           StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
9573         } else {
9574           assert(false && "Invalid constant element type");
9575         }
9576       }
9577
9578       // Create the new Load and Store operations.
9579       EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9580       StoredVal = DAG.getConstant(StoreInt, StoreTy);
9581     }
9582
9583     SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
9584                                     FirstInChain->getBasePtr(),
9585                                     FirstInChain->getPointerInfo(),
9586                                     false, false,
9587                                     FirstInChain->getAlignment());
9588
9589     // Replace the first store with the new store
9590     CombineTo(EarliestOp, NewStore);
9591     // Erase all other stores.
9592     for (unsigned i = 0; i < NumElem ; ++i) {
9593       if (StoreNodes[i].MemNode == EarliestOp)
9594         continue;
9595       StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9596       // ReplaceAllUsesWith will replace all uses that existed when it was
9597       // called, but graph optimizations may cause new ones to appear. For
9598       // example, the case in pr14333 looks like
9599       //
9600       //  St's chain -> St -> another store -> X
9601       //
9602       // And the only difference from St to the other store is the chain.
9603       // When we change it's chain to be St's chain they become identical,
9604       // get CSEed and the net result is that X is now a use of St.
9605       // Since we know that St is redundant, just iterate.
9606       while (!St->use_empty())
9607         DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
9608       deleteAndRecombine(St);
9609     }
9610
9611     return true;
9612   }
9613
9614   // Below we handle the case of multiple consecutive stores that
9615   // come from multiple consecutive loads. We merge them into a single
9616   // wide load and a single wide store.
9617
9618   // Look for load nodes which are used by the stored values.
9619   SmallVector<MemOpLink, 8> LoadNodes;
9620
9621   // Find acceptable loads. Loads need to have the same chain (token factor),
9622   // must not be zext, volatile, indexed, and they must be consecutive.
9623   BaseIndexOffset LdBasePtr;
9624   for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
9625     StoreSDNode *St  = cast<StoreSDNode>(StoreNodes[i].MemNode);
9626     LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
9627     if (!Ld) break;
9628
9629     // Loads must only have one use.
9630     if (!Ld->hasNUsesOfValue(1, 0))
9631       break;
9632
9633     // Check that the alignment is the same as the stores.
9634     if (Ld->getAlignment() != St->getAlignment())
9635       break;
9636
9637     // The memory operands must not be volatile.
9638     if (Ld->isVolatile() || Ld->isIndexed())
9639       break;
9640
9641     // We do not accept ext loads.
9642     if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
9643       break;
9644
9645     // The stored memory type must be the same.
9646     if (Ld->getMemoryVT() != MemVT)
9647       break;
9648
9649     BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
9650     // If this is not the first ptr that we check.
9651     if (LdBasePtr.Base.getNode()) {
9652       // The base ptr must be the same.
9653       if (!LdPtr.equalBaseIndex(LdBasePtr))
9654         break;
9655     } else {
9656       // Check that all other base pointers are the same as this one.
9657       LdBasePtr = LdPtr;
9658     }
9659
9660     // We found a potential memory operand to merge.
9661     LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
9662   }
9663
9664   if (LoadNodes.size() < 2)
9665     return false;
9666
9667   // If we have load/store pair instructions and we only have two values,
9668   // don't bother.
9669   unsigned RequiredAlignment;
9670   if (LoadNodes.size() == 2 && TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
9671       St->getAlignment() >= RequiredAlignment)
9672     return false;
9673
9674   // Scan the memory operations on the chain and find the first non-consecutive
9675   // load memory address. These variables hold the index in the store node
9676   // array.
9677   unsigned LastConsecutiveLoad = 0;
9678   // This variable refers to the size and not index in the array.
9679   unsigned LastLegalVectorType = 0;
9680   unsigned LastLegalIntegerType = 0;
9681   StartAddress = LoadNodes[0].OffsetFromBase;
9682   SDValue FirstChain = LoadNodes[0].MemNode->getChain();
9683   for (unsigned i = 1; i < LoadNodes.size(); ++i) {
9684     // All loads much share the same chain.
9685     if (LoadNodes[i].MemNode->getChain() != FirstChain)
9686       break;
9687
9688     int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
9689     if (CurrAddress - StartAddress != (ElementSizeBytes * i))
9690       break;
9691     LastConsecutiveLoad = i;
9692
9693     // Find a legal type for the vector store.
9694     EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
9695     if (TLI.isTypeLegal(StoreTy))
9696       LastLegalVectorType = i + 1;
9697
9698     // Find a legal type for the integer store.
9699     unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
9700     StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9701     if (TLI.isTypeLegal(StoreTy))
9702       LastLegalIntegerType = i + 1;
9703     // Or check whether a truncstore and extload is legal.
9704     else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
9705              TargetLowering::TypePromoteInteger) {
9706       EVT LegalizedStoredValueTy =
9707         TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
9708       if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
9709           TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
9710           TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
9711           TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
9712         LastLegalIntegerType = i+1;
9713     }
9714   }
9715
9716   // Only use vector types if the vector type is larger than the integer type.
9717   // If they are the same, use integers.
9718   bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
9719   unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
9720
9721   // We add +1 here because the LastXXX variables refer to location while
9722   // the NumElem refers to array/index size.
9723   unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
9724   NumElem = std::min(LastLegalType, NumElem);
9725
9726   if (NumElem < 2)
9727     return false;
9728
9729   // The earliest Node in the DAG.
9730   unsigned EarliestNodeUsed = 0;
9731   LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
9732   for (unsigned i=1; i<NumElem; ++i) {
9733     // Find a chain for the new wide-store operand. Notice that some
9734     // of the store nodes that we found may not be selected for inclusion
9735     // in the wide store. The chain we use needs to be the chain of the
9736     // earliest store node which is *used* and replaced by the wide store.
9737     if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
9738       EarliestNodeUsed = i;
9739   }
9740
9741   // Find if it is better to use vectors or integers to load and store
9742   // to memory.
9743   EVT JointMemOpVT;
9744   if (UseVectorTy) {
9745     JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
9746   } else {
9747     unsigned StoreBW = NumElem * ElementSizeBytes * 8;
9748     JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
9749   }
9750
9751   SDLoc LoadDL(LoadNodes[0].MemNode);
9752   SDLoc StoreDL(StoreNodes[0].MemNode);
9753
9754   LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
9755   SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
9756                                 FirstLoad->getChain(),
9757                                 FirstLoad->getBasePtr(),
9758                                 FirstLoad->getPointerInfo(),
9759                                 false, false, false,
9760                                 FirstLoad->getAlignment());
9761
9762   SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
9763                                   FirstInChain->getBasePtr(),
9764                                   FirstInChain->getPointerInfo(), false, false,
9765                                   FirstInChain->getAlignment());
9766
9767   // Replace one of the loads with the new load.
9768   LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
9769   DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
9770                                 SDValue(NewLoad.getNode(), 1));
9771
9772   // Remove the rest of the load chains.
9773   for (unsigned i = 1; i < NumElem ; ++i) {
9774     // Replace all chain users of the old load nodes with the chain of the new
9775     // load node.
9776     LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
9777     DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
9778   }
9779
9780   // Replace the first store with the new store.
9781   CombineTo(EarliestOp, NewStore);
9782   // Erase all other stores.
9783   for (unsigned i = 0; i < NumElem ; ++i) {
9784     // Remove all Store nodes.
9785     if (StoreNodes[i].MemNode == EarliestOp)
9786       continue;
9787     StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
9788     DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
9789     deleteAndRecombine(St);
9790   }
9791
9792   return true;
9793 }
9794
9795 SDValue DAGCombiner::visitSTORE(SDNode *N) {
9796   StoreSDNode *ST  = cast<StoreSDNode>(N);
9797   SDValue Chain = ST->getChain();
9798   SDValue Value = ST->getValue();
9799   SDValue Ptr   = ST->getBasePtr();
9800
9801   // If this is a store of a bit convert, store the input value if the
9802   // resultant store does not need a higher alignment than the original.
9803   if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
9804       ST->isUnindexed()) {
9805     unsigned OrigAlign = ST->getAlignment();
9806     EVT SVT = Value.getOperand(0).getValueType();
9807     unsigned Align = TLI.getDataLayout()->
9808       getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
9809     if (Align <= OrigAlign &&
9810         ((!LegalOperations && !ST->isVolatile()) ||
9811          TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
9812       return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0),
9813                           Ptr, ST->getPointerInfo(), ST->isVolatile(),
9814                           ST->isNonTemporal(), OrigAlign,
9815                           ST->getAAInfo());
9816   }
9817
9818   // Turn 'store undef, Ptr' -> nothing.
9819   if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
9820     return Chain;
9821
9822   // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
9823   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
9824     // NOTE: If the original store is volatile, this transform must not increase
9825     // the number of stores.  For example, on x86-32 an f64 can be stored in one
9826     // processor operation but an i64 (which is not legal) requires two.  So the
9827     // transform should not be done in this case.
9828     if (Value.getOpcode() != ISD::TargetConstantFP) {
9829       SDValue Tmp;
9830       switch (CFP->getSimpleValueType(0).SimpleTy) {
9831       default: llvm_unreachable("Unknown FP type");
9832       case MVT::f16:    // We don't do this for these yet.
9833       case MVT::f80:
9834       case MVT::f128:
9835       case MVT::ppcf128:
9836         break;
9837       case MVT::f32:
9838         if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
9839             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9840           Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
9841                               bitcastToAPInt().getZExtValue(), MVT::i32);
9842           return DAG.getStore(Chain, SDLoc(N), Tmp,
9843                               Ptr, ST->getMemOperand());
9844         }
9845         break;
9846       case MVT::f64:
9847         if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
9848              !ST->isVolatile()) ||
9849             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
9850           Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
9851                                 getZExtValue(), MVT::i64);
9852           return DAG.getStore(Chain, SDLoc(N), Tmp,
9853                               Ptr, ST->getMemOperand());
9854         }
9855
9856         if (!ST->isVolatile() &&
9857             TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
9858           // Many FP stores are not made apparent until after legalize, e.g. for
9859           // argument passing.  Since this is so common, custom legalize the
9860           // 64-bit integer store into two 32-bit stores.
9861           uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
9862           SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
9863           SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
9864           if (TLI.isBigEndian()) std::swap(Lo, Hi);
9865
9866           unsigned Alignment = ST->getAlignment();
9867           bool isVolatile = ST->isVolatile();
9868           bool isNonTemporal = ST->isNonTemporal();
9869           AAMDNodes AAInfo = ST->getAAInfo();
9870
9871           SDValue St0 = DAG.getStore(Chain, SDLoc(ST), Lo,
9872                                      Ptr, ST->getPointerInfo(),
9873                                      isVolatile, isNonTemporal,
9874                                      ST->getAlignment(), AAInfo);
9875           Ptr = DAG.getNode(ISD::ADD, SDLoc(N), Ptr.getValueType(), Ptr,
9876                             DAG.getConstant(4, Ptr.getValueType()));
9877           Alignment = MinAlign(Alignment, 4U);
9878           SDValue St1 = DAG.getStore(Chain, SDLoc(ST), Hi,
9879                                      Ptr, ST->getPointerInfo().getWithOffset(4),
9880                                      isVolatile, isNonTemporal,
9881                                      Alignment, AAInfo);
9882           return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
9883                              St0, St1);
9884         }
9885
9886         break;
9887       }
9888     }
9889   }
9890
9891   // Try to infer better alignment information than the store already has.
9892   if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
9893     if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
9894       if (Align > ST->getAlignment())
9895         return DAG.getTruncStore(Chain, SDLoc(N), Value,
9896                                  Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
9897                                  ST->isVolatile(), ST->isNonTemporal(), Align,
9898                                  ST->getAAInfo());
9899     }
9900   }
9901
9902   // Try transforming a pair floating point load / store ops to integer
9903   // load / store ops.
9904   SDValue NewST = TransformFPLoadStorePair(N);
9905   if (NewST.getNode())
9906     return NewST;
9907
9908   bool UseAA = CombinerAA.getNumOccurrences() > 0 ? CombinerAA
9909                                                   : DAG.getSubtarget().useAA();
9910 #ifndef NDEBUG
9911   if (CombinerAAOnlyFunc.getNumOccurrences() &&
9912       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
9913     UseAA = false;
9914 #endif
9915   if (UseAA && ST->isUnindexed()) {
9916     // Walk up chain skipping non-aliasing memory nodes.
9917     SDValue BetterChain = FindBetterChain(N, Chain);
9918
9919     // If there is a better chain.
9920     if (Chain != BetterChain) {
9921       SDValue ReplStore;
9922
9923       // Replace the chain to avoid dependency.
9924       if (ST->isTruncatingStore()) {
9925         ReplStore = DAG.getTruncStore(BetterChain, SDLoc(N), Value, Ptr,
9926                                       ST->getMemoryVT(), ST->getMemOperand());
9927       } else {
9928         ReplStore = DAG.getStore(BetterChain, SDLoc(N), Value, Ptr,
9929                                  ST->getMemOperand());
9930       }
9931
9932       // Create token to keep both nodes around.
9933       SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
9934                                   MVT::Other, Chain, ReplStore);
9935
9936       // Make sure the new and old chains are cleaned up.
9937       AddToWorklist(Token.getNode());
9938
9939       // Don't add users to work list.
9940       return CombineTo(N, Token, false);
9941     }
9942   }
9943
9944   // Try transforming N to an indexed store.
9945   if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
9946     return SDValue(N, 0);
9947
9948   // FIXME: is there such a thing as a truncating indexed store?
9949   if (ST->isTruncatingStore() && ST->isUnindexed() &&
9950       Value.getValueType().isInteger()) {
9951     // See if we can simplify the input to this truncstore with knowledge that
9952     // only the low bits are being used.  For example:
9953     // "truncstore (or (shl x, 8), y), i8"  -> "truncstore y, i8"
9954     SDValue Shorter =
9955       GetDemandedBits(Value,
9956                       APInt::getLowBitsSet(
9957                         Value.getValueType().getScalarType().getSizeInBits(),
9958                         ST->getMemoryVT().getScalarType().getSizeInBits()));
9959     AddToWorklist(Value.getNode());
9960     if (Shorter.getNode())
9961       return DAG.getTruncStore(Chain, SDLoc(N), Shorter,
9962                                Ptr, ST->getMemoryVT(), ST->getMemOperand());
9963
9964     // Otherwise, see if we can simplify the operation with
9965     // SimplifyDemandedBits, which only works if the value has a single use.
9966     if (SimplifyDemandedBits(Value,
9967                         APInt::getLowBitsSet(
9968                           Value.getValueType().getScalarType().getSizeInBits(),
9969                           ST->getMemoryVT().getScalarType().getSizeInBits())))
9970       return SDValue(N, 0);
9971   }
9972
9973   // If this is a load followed by a store to the same location, then the store
9974   // is dead/noop.
9975   if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
9976     if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
9977         ST->isUnindexed() && !ST->isVolatile() &&
9978         // There can't be any side effects between the load and store, such as
9979         // a call or store.
9980         Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
9981       // The store is dead, remove it.
9982       return Chain;
9983     }
9984   }
9985
9986   // If this is a store followed by a store with the same value to the same
9987   // location, then the store is dead/noop.
9988   if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
9989     if (ST1->getBasePtr() == Ptr && ST->getMemoryVT() == ST1->getMemoryVT() &&
9990         ST1->getValue() == Value && ST->isUnindexed() && !ST->isVolatile() &&
9991         ST1->isUnindexed() && !ST1->isVolatile()) {
9992       // The store is dead, remove it.
9993       return Chain;
9994     }
9995   }
9996
9997   // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
9998   // truncating store.  We can do this even if this is already a truncstore.
9999   if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
10000       && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
10001       TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
10002                             ST->getMemoryVT())) {
10003     return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
10004                              Ptr, ST->getMemoryVT(), ST->getMemOperand());
10005   }
10006
10007   // Only perform this optimization before the types are legal, because we
10008   // don't want to perform this optimization on every DAGCombine invocation.
10009   if (!LegalTypes) {
10010     bool EverChanged = false;
10011
10012     do {
10013       // There can be multiple store sequences on the same chain.
10014       // Keep trying to merge store sequences until we are unable to do so
10015       // or until we merge the last store on the chain.
10016       bool Changed = MergeConsecutiveStores(ST);
10017       EverChanged |= Changed;
10018       if (!Changed) break;
10019     } while (ST->getOpcode() != ISD::DELETED_NODE);
10020
10021     if (EverChanged)
10022       return SDValue(N, 0);
10023   }
10024
10025   return ReduceLoadOpStoreWidth(N);
10026 }
10027
10028 SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
10029   SDValue InVec = N->getOperand(0);
10030   SDValue InVal = N->getOperand(1);
10031   SDValue EltNo = N->getOperand(2);
10032   SDLoc dl(N);
10033
10034   // If the inserted element is an UNDEF, just use the input vector.
10035   if (InVal.getOpcode() == ISD::UNDEF)
10036     return InVec;
10037
10038   EVT VT = InVec.getValueType();
10039
10040   // If we can't generate a legal BUILD_VECTOR, exit
10041   if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
10042     return SDValue();
10043
10044   // Check that we know which element is being inserted
10045   if (!isa<ConstantSDNode>(EltNo))
10046     return SDValue();
10047   unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10048
10049   // Canonicalize insert_vector_elt dag nodes.
10050   // Example:
10051   // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
10052   // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
10053   //
10054   // Do this only if the child insert_vector node has one use; also
10055   // do this only if indices are both constants and Idx1 < Idx0.
10056   if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
10057       && isa<ConstantSDNode>(InVec.getOperand(2))) {
10058     unsigned OtherElt =
10059       cast<ConstantSDNode>(InVec.getOperand(2))->getZExtValue();
10060     if (Elt < OtherElt) {
10061       // Swap nodes.
10062       SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(N), VT,
10063                                   InVec.getOperand(0), InVal, EltNo);
10064       AddToWorklist(NewOp.getNode());
10065       return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
10066                          VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
10067     }
10068   }
10069
10070   // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
10071   // be converted to a BUILD_VECTOR).  Fill in the Ops vector with the
10072   // vector elements.
10073   SmallVector<SDValue, 8> Ops;
10074   // Do not combine these two vectors if the output vector will not replace
10075   // the input vector.
10076   if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
10077     Ops.append(InVec.getNode()->op_begin(),
10078                InVec.getNode()->op_end());
10079   } else if (InVec.getOpcode() == ISD::UNDEF) {
10080     unsigned NElts = VT.getVectorNumElements();
10081     Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
10082   } else {
10083     return SDValue();
10084   }
10085
10086   // Insert the element
10087   if (Elt < Ops.size()) {
10088     // All the operands of BUILD_VECTOR must have the same type;
10089     // we enforce that here.
10090     EVT OpVT = Ops[0].getValueType();
10091     if (InVal.getValueType() != OpVT)
10092       InVal = OpVT.bitsGT(InVal.getValueType()) ?
10093                 DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
10094                 DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
10095     Ops[Elt] = InVal;
10096   }
10097
10098   // Return the new vector
10099   return DAG.getNode(ISD::BUILD_VECTOR, dl, VT, Ops);
10100 }
10101
10102 SDValue DAGCombiner::ReplaceExtractVectorEltOfLoadWithNarrowedLoad(
10103     SDNode *EVE, EVT InVecVT, SDValue EltNo, LoadSDNode *OriginalLoad) {
10104   EVT ResultVT = EVE->getValueType(0);
10105   EVT VecEltVT = InVecVT.getVectorElementType();
10106   unsigned Align = OriginalLoad->getAlignment();
10107   unsigned NewAlign = TLI.getDataLayout()->getABITypeAlignment(
10108       VecEltVT.getTypeForEVT(*DAG.getContext()));
10109
10110   if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT))
10111     return SDValue();
10112
10113   Align = NewAlign;
10114
10115   SDValue NewPtr = OriginalLoad->getBasePtr();
10116   SDValue Offset;
10117   EVT PtrType = NewPtr.getValueType();
10118   MachinePointerInfo MPI;
10119   if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
10120     int Elt = ConstEltNo->getZExtValue();
10121     unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
10122     if (TLI.isBigEndian())
10123       PtrOff = InVecVT.getSizeInBits() / 8 - PtrOff;
10124     Offset = DAG.getConstant(PtrOff, PtrType);
10125     MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
10126   } else {
10127     Offset = DAG.getNode(
10128         ISD::MUL, SDLoc(EVE), EltNo.getValueType(), EltNo,
10129         DAG.getConstant(VecEltVT.getStoreSize(), EltNo.getValueType()));
10130     if (TLI.isBigEndian())
10131       Offset = DAG.getNode(
10132           ISD::SUB, SDLoc(EVE), EltNo.getValueType(),
10133           DAG.getConstant(InVecVT.getStoreSize(), EltNo.getValueType()), Offset);
10134     MPI = OriginalLoad->getPointerInfo();
10135   }
10136   NewPtr = DAG.getNode(ISD::ADD, SDLoc(EVE), PtrType, NewPtr, Offset);
10137
10138   // The replacement we need to do here is a little tricky: we need to
10139   // replace an extractelement of a load with a load.
10140   // Use ReplaceAllUsesOfValuesWith to do the replacement.
10141   // Note that this replacement assumes that the extractvalue is the only
10142   // use of the load; that's okay because we don't want to perform this
10143   // transformation in other cases anyway.
10144   SDValue Load;
10145   SDValue Chain;
10146   if (ResultVT.bitsGT(VecEltVT)) {
10147     // If the result type of vextract is wider than the load, then issue an
10148     // extending load instead.
10149     ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, VecEltVT)
10150                                    ? ISD::ZEXTLOAD
10151                                    : ISD::EXTLOAD;
10152     Load = DAG.getExtLoad(
10153         ExtType, SDLoc(EVE), ResultVT, OriginalLoad->getChain(), NewPtr, MPI,
10154         VecEltVT, OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10155         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10156     Chain = Load.getValue(1);
10157   } else {
10158     Load = DAG.getLoad(
10159         VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI,
10160         OriginalLoad->isVolatile(), OriginalLoad->isNonTemporal(),
10161         OriginalLoad->isInvariant(), Align, OriginalLoad->getAAInfo());
10162     Chain = Load.getValue(1);
10163     if (ResultVT.bitsLT(VecEltVT))
10164       Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
10165     else
10166       Load = DAG.getNode(ISD::BITCAST, SDLoc(EVE), ResultVT, Load);
10167   }
10168   WorklistRemover DeadNodes(*this);
10169   SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
10170   SDValue To[] = { Load, Chain };
10171   DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
10172   // Since we're explicitly calling ReplaceAllUses, add the new node to the
10173   // worklist explicitly as well.
10174   AddToWorklist(Load.getNode());
10175   AddUsersToWorklist(Load.getNode()); // Add users too
10176   // Make sure to revisit this node to clean it up; it will usually be dead.
10177   AddToWorklist(EVE);
10178   ++OpsNarrowed;
10179   return SDValue(EVE, 0);
10180 }
10181
10182 SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
10183   // (vextract (scalar_to_vector val, 0) -> val
10184   SDValue InVec = N->getOperand(0);
10185   EVT VT = InVec.getValueType();
10186   EVT NVT = N->getValueType(0);
10187
10188   if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
10189     // Check if the result type doesn't match the inserted element type. A
10190     // SCALAR_TO_VECTOR may truncate the inserted element and the
10191     // EXTRACT_VECTOR_ELT may widen the extracted vector.
10192     SDValue InOp = InVec.getOperand(0);
10193     if (InOp.getValueType() != NVT) {
10194       assert(InOp.getValueType().isInteger() && NVT.isInteger());
10195       return DAG.getSExtOrTrunc(InOp, SDLoc(InVec), NVT);
10196     }
10197     return InOp;
10198   }
10199
10200   SDValue EltNo = N->getOperand(1);
10201   bool ConstEltNo = isa<ConstantSDNode>(EltNo);
10202
10203   // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
10204   // We only perform this optimization before the op legalization phase because
10205   // we may introduce new vector instructions which are not backed by TD
10206   // patterns. For example on AVX, extracting elements from a wide vector
10207   // without using extract_subvector. However, if we can find an underlying
10208   // scalar value, then we can always use that.
10209   if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
10210       && ConstEltNo) {
10211     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10212     int NumElem = VT.getVectorNumElements();
10213     ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
10214     // Find the new index to extract from.
10215     int OrigElt = SVOp->getMaskElt(Elt);
10216
10217     // Extracting an undef index is undef.
10218     if (OrigElt == -1)
10219       return DAG.getUNDEF(NVT);
10220
10221     // Select the right vector half to extract from.
10222     SDValue SVInVec;
10223     if (OrigElt < NumElem) {
10224       SVInVec = InVec->getOperand(0);
10225     } else {
10226       SVInVec = InVec->getOperand(1);
10227       OrigElt -= NumElem;
10228     }
10229
10230     if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
10231       SDValue InOp = SVInVec.getOperand(OrigElt);
10232       if (InOp.getValueType() != NVT) {
10233         assert(InOp.getValueType().isInteger() && NVT.isInteger());
10234         InOp = DAG.getSExtOrTrunc(InOp, SDLoc(SVInVec), NVT);
10235       }
10236
10237       return InOp;
10238     }
10239
10240     // FIXME: We should handle recursing on other vector shuffles and
10241     // scalar_to_vector here as well.
10242
10243     if (!LegalOperations) {
10244       EVT IndexTy = TLI.getVectorIdxTy();
10245       return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(N), NVT,
10246                          SVInVec, DAG.getConstant(OrigElt, IndexTy));
10247     }
10248   }
10249
10250   bool BCNumEltsChanged = false;
10251   EVT ExtVT = VT.getVectorElementType();
10252   EVT LVT = ExtVT;
10253
10254   // If the result of load has to be truncated, then it's not necessarily
10255   // profitable.
10256   if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
10257     return SDValue();
10258
10259   if (InVec.getOpcode() == ISD::BITCAST) {
10260     // Don't duplicate a load with other uses.
10261     if (!InVec.hasOneUse())
10262       return SDValue();
10263
10264     EVT BCVT = InVec.getOperand(0).getValueType();
10265     if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
10266       return SDValue();
10267     if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
10268       BCNumEltsChanged = true;
10269     InVec = InVec.getOperand(0);
10270     ExtVT = BCVT.getVectorElementType();
10271   }
10272
10273   // (vextract (vN[if]M load $addr), i) -> ([if]M load $addr + i * size)
10274   if (!LegalOperations && !ConstEltNo && InVec.hasOneUse() &&
10275       ISD::isNormalLoad(InVec.getNode()) &&
10276       !N->getOperand(1)->hasPredecessor(InVec.getNode())) {
10277     SDValue Index = N->getOperand(1);
10278     if (LoadSDNode *OrigLoad = dyn_cast<LoadSDNode>(InVec))
10279       return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, Index,
10280                                                            OrigLoad);
10281   }
10282
10283   // Perform only after legalization to ensure build_vector / vector_shuffle
10284   // optimizations have already been done.
10285   if (!LegalOperations) return SDValue();
10286
10287   // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
10288   // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
10289   // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
10290
10291   if (ConstEltNo) {
10292     int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
10293
10294     LoadSDNode *LN0 = nullptr;
10295     const ShuffleVectorSDNode *SVN = nullptr;
10296     if (ISD::isNormalLoad(InVec.getNode())) {
10297       LN0 = cast<LoadSDNode>(InVec);
10298     } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
10299                InVec.getOperand(0).getValueType() == ExtVT &&
10300                ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
10301       // Don't duplicate a load with other uses.
10302       if (!InVec.hasOneUse())
10303         return SDValue();
10304
10305       LN0 = cast<LoadSDNode>(InVec.getOperand(0));
10306     } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
10307       // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
10308       // =>
10309       // (load $addr+1*size)
10310
10311       // Don't duplicate a load with other uses.
10312       if (!InVec.hasOneUse())
10313         return SDValue();
10314
10315       // If the bit convert changed the number of elements, it is unsafe
10316       // to examine the mask.
10317       if (BCNumEltsChanged)
10318         return SDValue();
10319
10320       // Select the input vector, guarding against out of range extract vector.
10321       unsigned NumElems = VT.getVectorNumElements();
10322       int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
10323       InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
10324
10325       if (InVec.getOpcode() == ISD::BITCAST) {
10326         // Don't duplicate a load with other uses.
10327         if (!InVec.hasOneUse())
10328           return SDValue();
10329
10330         InVec = InVec.getOperand(0);
10331       }
10332       if (ISD::isNormalLoad(InVec.getNode())) {
10333         LN0 = cast<LoadSDNode>(InVec);
10334         Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
10335         EltNo = DAG.getConstant(Elt, EltNo.getValueType());
10336       }
10337     }
10338
10339     // Make sure we found a non-volatile load and the extractelement is
10340     // the only use.
10341     if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
10342       return SDValue();
10343
10344     // If Idx was -1 above, Elt is going to be -1, so just return undef.
10345     if (Elt == -1)
10346       return DAG.getUNDEF(LVT);
10347
10348     return ReplaceExtractVectorEltOfLoadWithNarrowedLoad(N, VT, EltNo, LN0);
10349   }
10350
10351   return SDValue();
10352 }
10353
10354 // Simplify (build_vec (ext )) to (bitcast (build_vec ))
10355 SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
10356   // We perform this optimization post type-legalization because
10357   // the type-legalizer often scalarizes integer-promoted vectors.
10358   // Performing this optimization before may create bit-casts which
10359   // will be type-legalized to complex code sequences.
10360   // We perform this optimization only before the operation legalizer because we
10361   // may introduce illegal operations.
10362   if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
10363     return SDValue();
10364
10365   unsigned NumInScalars = N->getNumOperands();
10366   SDLoc dl(N);
10367   EVT VT = N->getValueType(0);
10368
10369   // Check to see if this is a BUILD_VECTOR of a bunch of values
10370   // which come from any_extend or zero_extend nodes. If so, we can create
10371   // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
10372   // optimizations. We do not handle sign-extend because we can't fill the sign
10373   // using shuffles.
10374   EVT SourceType = MVT::Other;
10375   bool AllAnyExt = true;
10376
10377   for (unsigned i = 0; i != NumInScalars; ++i) {
10378     SDValue In = N->getOperand(i);
10379     // Ignore undef inputs.
10380     if (In.getOpcode() == ISD::UNDEF) continue;
10381
10382     bool AnyExt  = In.getOpcode() == ISD::ANY_EXTEND;
10383     bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
10384
10385     // Abort if the element is not an extension.
10386     if (!ZeroExt && !AnyExt) {
10387       SourceType = MVT::Other;
10388       break;
10389     }
10390
10391     // The input is a ZeroExt or AnyExt. Check the original type.
10392     EVT InTy = In.getOperand(0).getValueType();
10393
10394     // Check that all of the widened source types are the same.
10395     if (SourceType == MVT::Other)
10396       // First time.
10397       SourceType = InTy;
10398     else if (InTy != SourceType) {
10399       // Multiple income types. Abort.
10400       SourceType = MVT::Other;
10401       break;
10402     }
10403
10404     // Check if all of the extends are ANY_EXTENDs.
10405     AllAnyExt &= AnyExt;
10406   }
10407
10408   // In order to have valid types, all of the inputs must be extended from the
10409   // same source type and all of the inputs must be any or zero extend.
10410   // Scalar sizes must be a power of two.
10411   EVT OutScalarTy = VT.getScalarType();
10412   bool ValidTypes = SourceType != MVT::Other &&
10413                  isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
10414                  isPowerOf2_32(SourceType.getSizeInBits());
10415
10416   // Create a new simpler BUILD_VECTOR sequence which other optimizations can
10417   // turn into a single shuffle instruction.
10418   if (!ValidTypes)
10419     return SDValue();
10420
10421   bool isLE = TLI.isLittleEndian();
10422   unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
10423   assert(ElemRatio > 1 && "Invalid element size ratio");
10424   SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
10425                                DAG.getConstant(0, SourceType);
10426
10427   unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
10428   SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
10429
10430   // Populate the new build_vector
10431   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10432     SDValue Cast = N->getOperand(i);
10433     assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
10434             Cast.getOpcode() == ISD::ZERO_EXTEND ||
10435             Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
10436     SDValue In;
10437     if (Cast.getOpcode() == ISD::UNDEF)
10438       In = DAG.getUNDEF(SourceType);
10439     else
10440       In = Cast->getOperand(0);
10441     unsigned Index = isLE ? (i * ElemRatio) :
10442                             (i * ElemRatio + (ElemRatio - 1));
10443
10444     assert(Index < Ops.size() && "Invalid index");
10445     Ops[Index] = In;
10446   }
10447
10448   // The type of the new BUILD_VECTOR node.
10449   EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
10450   assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
10451          "Invalid vector size");
10452   // Check if the new vector type is legal.
10453   if (!isTypeLegal(VecVT)) return SDValue();
10454
10455   // Make the new BUILD_VECTOR.
10456   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, Ops);
10457
10458   // The new BUILD_VECTOR node has the potential to be further optimized.
10459   AddToWorklist(BV.getNode());
10460   // Bitcast to the desired type.
10461   return DAG.getNode(ISD::BITCAST, dl, VT, BV);
10462 }
10463
10464 SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
10465   EVT VT = N->getValueType(0);
10466
10467   unsigned NumInScalars = N->getNumOperands();
10468   SDLoc dl(N);
10469
10470   EVT SrcVT = MVT::Other;
10471   unsigned Opcode = ISD::DELETED_NODE;
10472   unsigned NumDefs = 0;
10473
10474   for (unsigned i = 0; i != NumInScalars; ++i) {
10475     SDValue In = N->getOperand(i);
10476     unsigned Opc = In.getOpcode();
10477
10478     if (Opc == ISD::UNDEF)
10479       continue;
10480
10481     // If all scalar values are floats and converted from integers.
10482     if (Opcode == ISD::DELETED_NODE &&
10483         (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
10484       Opcode = Opc;
10485     }
10486
10487     if (Opc != Opcode)
10488       return SDValue();
10489
10490     EVT InVT = In.getOperand(0).getValueType();
10491
10492     // If all scalar values are typed differently, bail out. It's chosen to
10493     // simplify BUILD_VECTOR of integer types.
10494     if (SrcVT == MVT::Other)
10495       SrcVT = InVT;
10496     if (SrcVT != InVT)
10497       return SDValue();
10498     NumDefs++;
10499   }
10500
10501   // If the vector has just one element defined, it's not worth to fold it into
10502   // a vectorized one.
10503   if (NumDefs < 2)
10504     return SDValue();
10505
10506   assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
10507          && "Should only handle conversion from integer to float.");
10508   assert(SrcVT != MVT::Other && "Cannot determine source type!");
10509
10510   EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
10511
10512   if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
10513     return SDValue();
10514
10515   SmallVector<SDValue, 8> Opnds;
10516   for (unsigned i = 0; i != NumInScalars; ++i) {
10517     SDValue In = N->getOperand(i);
10518
10519     if (In.getOpcode() == ISD::UNDEF)
10520       Opnds.push_back(DAG.getUNDEF(SrcVT));
10521     else
10522       Opnds.push_back(In.getOperand(0));
10523   }
10524   SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT, Opnds);
10525   AddToWorklist(BV.getNode());
10526
10527   return DAG.getNode(Opcode, dl, VT, BV);
10528 }
10529
10530 SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
10531   unsigned NumInScalars = N->getNumOperands();
10532   SDLoc dl(N);
10533   EVT VT = N->getValueType(0);
10534
10535   // A vector built entirely of undefs is undef.
10536   if (ISD::allOperandsUndef(N))
10537     return DAG.getUNDEF(VT);
10538
10539   SDValue V = reduceBuildVecExtToExtBuildVec(N);
10540   if (V.getNode())
10541     return V;
10542
10543   V = reduceBuildVecConvertToConvertBuildVec(N);
10544   if (V.getNode())
10545     return V;
10546
10547   // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
10548   // operations.  If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
10549   // at most two distinct vectors, turn this into a shuffle node.
10550
10551   // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
10552   if (!isTypeLegal(VT))
10553     return SDValue();
10554
10555   // May only combine to shuffle after legalize if shuffle is legal.
10556   if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
10557     return SDValue();
10558
10559   SDValue VecIn1, VecIn2;
10560   bool UsesZeroVector = false;
10561   for (unsigned i = 0; i != NumInScalars; ++i) {
10562     SDValue Op = N->getOperand(i);
10563     // Ignore undef inputs.
10564     if (Op.getOpcode() == ISD::UNDEF) continue;
10565
10566     // See if we can combine this build_vector into a blend with a zero vector.
10567     if (!VecIn2.getNode() && ((Op.getOpcode() == ISD::Constant &&
10568         cast<ConstantSDNode>(Op.getNode())->isNullValue()) ||
10569         (Op.getOpcode() == ISD::ConstantFP &&
10570         cast<ConstantFPSDNode>(Op.getNode())->getValueAPF().isZero()))) {
10571       UsesZeroVector = true;
10572       continue;
10573     }
10574
10575     // If this input is something other than a EXTRACT_VECTOR_ELT with a
10576     // constant index, bail out.
10577     if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
10578         !isa<ConstantSDNode>(Op.getOperand(1))) {
10579       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10580       break;
10581     }
10582
10583     // We allow up to two distinct input vectors.
10584     SDValue ExtractedFromVec = Op.getOperand(0);
10585     if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
10586       continue;
10587
10588     if (!VecIn1.getNode()) {
10589       VecIn1 = ExtractedFromVec;
10590     } else if (!VecIn2.getNode() && !UsesZeroVector) {
10591       VecIn2 = ExtractedFromVec;
10592     } else {
10593       // Too many inputs.
10594       VecIn1 = VecIn2 = SDValue(nullptr, 0);
10595       break;
10596     }
10597   }
10598
10599   // If everything is good, we can make a shuffle operation.
10600   if (VecIn1.getNode()) {
10601     SmallVector<int, 8> Mask;
10602     for (unsigned i = 0; i != NumInScalars; ++i) {
10603       unsigned Opcode = N->getOperand(i).getOpcode();
10604       if (Opcode == ISD::UNDEF) {
10605         Mask.push_back(-1);
10606         continue;
10607       }
10608
10609       // Operands can also be zero.
10610       if (Opcode != ISD::EXTRACT_VECTOR_ELT) {
10611         assert(UsesZeroVector &&
10612                (Opcode == ISD::Constant || Opcode == ISD::ConstantFP) &&
10613                "Unexpected node found!");
10614         Mask.push_back(NumInScalars+i);
10615         continue;
10616       }
10617
10618       // If extracting from the first vector, just use the index directly.
10619       SDValue Extract = N->getOperand(i);
10620       SDValue ExtVal = Extract.getOperand(1);
10621       unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
10622       if (Extract.getOperand(0) == VecIn1) {
10623         if (ExtIndex > VT.getVectorNumElements())
10624           return SDValue();
10625
10626         Mask.push_back(ExtIndex);
10627         continue;
10628       }
10629
10630       // Otherwise, use InIdx + VecSize
10631       Mask.push_back(NumInScalars+ExtIndex);
10632     }
10633
10634     // Avoid introducing illegal shuffles with zero.
10635     if (UsesZeroVector && !TLI.isVectorClearMaskLegal(Mask, VT))
10636       return SDValue();
10637
10638     // We can't generate a shuffle node with mismatched input and output types.
10639     // Attempt to transform a single input vector to the correct type.
10640     if ((VT != VecIn1.getValueType())) {
10641       // We don't support shuffeling between TWO values of different types.
10642       if (VecIn2.getNode())
10643         return SDValue();
10644
10645       // We only support widening of vectors which are half the size of the
10646       // output registers. For example XMM->YMM widening on X86 with AVX.
10647       if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
10648         return SDValue();
10649
10650       // If the input vector type has a different base type to the output
10651       // vector type, bail out.
10652       if (VecIn1.getValueType().getVectorElementType() !=
10653           VT.getVectorElementType())
10654         return SDValue();
10655
10656       // Widen the input vector by adding undef values.
10657       VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
10658                            VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
10659     }
10660
10661     if (UsesZeroVector)
10662       VecIn2 = VT.isInteger() ? DAG.getConstant(0, VT) :
10663                                 DAG.getConstantFP(0.0, VT);
10664     else
10665       // If VecIn2 is unused then change it to undef.
10666       VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
10667
10668     // Check that we were able to transform all incoming values to the same
10669     // type.
10670     if (VecIn2.getValueType() != VecIn1.getValueType() ||
10671         VecIn1.getValueType() != VT)
10672           return SDValue();
10673
10674     // Return the new VECTOR_SHUFFLE node.
10675     SDValue Ops[2];
10676     Ops[0] = VecIn1;
10677     Ops[1] = VecIn2;
10678     return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
10679   }
10680
10681   return SDValue();
10682 }
10683
10684 SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
10685   // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
10686   // EXTRACT_SUBVECTOR operations.  If so, and if the EXTRACT_SUBVECTOR vector
10687   // inputs come from at most two distinct vectors, turn this into a shuffle
10688   // node.
10689
10690   // If we only have one input vector, we don't need to do any concatenation.
10691   if (N->getNumOperands() == 1)
10692     return N->getOperand(0);
10693
10694   // Check if all of the operands are undefs.
10695   EVT VT = N->getValueType(0);
10696   if (ISD::allOperandsUndef(N))
10697     return DAG.getUNDEF(VT);
10698
10699   // Optimize concat_vectors where one of the vectors is undef.
10700   if (N->getNumOperands() == 2 &&
10701       N->getOperand(1)->getOpcode() == ISD::UNDEF) {
10702     SDValue In = N->getOperand(0);
10703     assert(In.getValueType().isVector() && "Must concat vectors");
10704
10705     // Transform: concat_vectors(scalar, undef) -> scalar_to_vector(sclr).
10706     if (In->getOpcode() == ISD::BITCAST &&
10707         !In->getOperand(0)->getValueType(0).isVector()) {
10708       SDValue Scalar = In->getOperand(0);
10709       EVT SclTy = Scalar->getValueType(0);
10710
10711       if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
10712         return SDValue();
10713
10714       EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy,
10715                                  VT.getSizeInBits() / SclTy.getSizeInBits());
10716       if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
10717         return SDValue();
10718
10719       SDLoc dl = SDLoc(N);
10720       SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, NVT, Scalar);
10721       return DAG.getNode(ISD::BITCAST, dl, VT, Res);
10722     }
10723   }
10724
10725   // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
10726   // -> (BUILD_VECTOR A, B, ..., C, D, ...)
10727   if (N->getNumOperands() == 2 &&
10728       N->getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
10729       N->getOperand(1).getOpcode() == ISD::BUILD_VECTOR) {
10730     EVT VT = N->getValueType(0);
10731     SDValue N0 = N->getOperand(0);
10732     SDValue N1 = N->getOperand(1);
10733     SmallVector<SDValue, 8> Opnds;
10734     unsigned BuildVecNumElts =  N0.getNumOperands();
10735
10736     EVT SclTy0 = N0.getOperand(0)->getValueType(0);
10737     EVT SclTy1 = N1.getOperand(0)->getValueType(0);
10738     if (SclTy0.isFloatingPoint()) {
10739       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10740         Opnds.push_back(N0.getOperand(i));
10741       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10742         Opnds.push_back(N1.getOperand(i));
10743     } else {
10744       // If BUILD_VECTOR are from built from integer, they may have different
10745       // operand types. Get the smaller type and truncate all operands to it.
10746       EVT MinTy = SclTy0.bitsLE(SclTy1) ? SclTy0 : SclTy1;
10747       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10748         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10749                         N0.getOperand(i)));
10750       for (unsigned i = 0; i != BuildVecNumElts; ++i)
10751         Opnds.push_back(DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinTy,
10752                         N1.getOperand(i)));
10753     }
10754
10755     return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), VT, Opnds);
10756   }
10757
10758   // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
10759   // nodes often generate nop CONCAT_VECTOR nodes.
10760   // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
10761   // place the incoming vectors at the exact same location.
10762   SDValue SingleSource = SDValue();
10763   unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
10764
10765   for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
10766     SDValue Op = N->getOperand(i);
10767
10768     if (Op.getOpcode() == ISD::UNDEF)
10769       continue;
10770
10771     // Check if this is the identity extract:
10772     if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
10773       return SDValue();
10774
10775     // Find the single incoming vector for the extract_subvector.
10776     if (SingleSource.getNode()) {
10777       if (Op.getOperand(0) != SingleSource)
10778         return SDValue();
10779     } else {
10780       SingleSource = Op.getOperand(0);
10781
10782       // Check the source type is the same as the type of the result.
10783       // If not, this concat may extend the vector, so we can not
10784       // optimize it away.
10785       if (SingleSource.getValueType() != N->getValueType(0))
10786         return SDValue();
10787     }
10788
10789     unsigned IdentityIndex = i * PartNumElem;
10790     ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
10791     // The extract index must be constant.
10792     if (!CS)
10793       return SDValue();
10794
10795     // Check that we are reading from the identity index.
10796     if (CS->getZExtValue() != IdentityIndex)
10797       return SDValue();
10798   }
10799
10800   if (SingleSource.getNode())
10801     return SingleSource;
10802
10803   return SDValue();
10804 }
10805
10806 SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
10807   EVT NVT = N->getValueType(0);
10808   SDValue V = N->getOperand(0);
10809
10810   if (V->getOpcode() == ISD::CONCAT_VECTORS) {
10811     // Combine:
10812     //    (extract_subvec (concat V1, V2, ...), i)
10813     // Into:
10814     //    Vi if possible
10815     // Only operand 0 is checked as 'concat' assumes all inputs of the same
10816     // type.
10817     if (V->getOperand(0).getValueType() != NVT)
10818       return SDValue();
10819     unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
10820     unsigned NumElems = NVT.getVectorNumElements();
10821     assert((Idx % NumElems) == 0 &&
10822            "IDX in concat is not a multiple of the result vector length.");
10823     return V->getOperand(Idx / NumElems);
10824   }
10825
10826   // Skip bitcasting
10827   if (V->getOpcode() == ISD::BITCAST)
10828     V = V.getOperand(0);
10829
10830   if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
10831     SDLoc dl(N);
10832     // Handle only simple case where vector being inserted and vector
10833     // being extracted are of same type, and are half size of larger vectors.
10834     EVT BigVT = V->getOperand(0).getValueType();
10835     EVT SmallVT = V->getOperand(1).getValueType();
10836     if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
10837       return SDValue();
10838
10839     // Only handle cases where both indexes are constants with the same type.
10840     ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
10841     ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
10842
10843     if (InsIdx && ExtIdx &&
10844         InsIdx->getValueType(0).getSizeInBits() <= 64 &&
10845         ExtIdx->getValueType(0).getSizeInBits() <= 64) {
10846       // Combine:
10847       //    (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
10848       // Into:
10849       //    indices are equal or bit offsets are equal => V1
10850       //    otherwise => (extract_subvec V1, ExtIdx)
10851       if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
10852           ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
10853         return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
10854       return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
10855                          DAG.getNode(ISD::BITCAST, dl,
10856                                      N->getOperand(0).getValueType(),
10857                                      V->getOperand(0)), N->getOperand(1));
10858     }
10859   }
10860
10861   return SDValue();
10862 }
10863
10864 static SDValue simplifyShuffleOperandRecursively(SmallBitVector &UsedElements,
10865                                                  SDValue V, SelectionDAG &DAG) {
10866   SDLoc DL(V);
10867   EVT VT = V.getValueType();
10868
10869   switch (V.getOpcode()) {
10870   default:
10871     return V;
10872
10873   case ISD::CONCAT_VECTORS: {
10874     EVT OpVT = V->getOperand(0).getValueType();
10875     int OpSize = OpVT.getVectorNumElements();
10876     SmallBitVector OpUsedElements(OpSize, false);
10877     bool FoundSimplification = false;
10878     SmallVector<SDValue, 4> NewOps;
10879     NewOps.reserve(V->getNumOperands());
10880     for (int i = 0, NumOps = V->getNumOperands(); i < NumOps; ++i) {
10881       SDValue Op = V->getOperand(i);
10882       bool OpUsed = false;
10883       for (int j = 0; j < OpSize; ++j)
10884         if (UsedElements[i * OpSize + j]) {
10885           OpUsedElements[j] = true;
10886           OpUsed = true;
10887         }
10888       NewOps.push_back(
10889           OpUsed ? simplifyShuffleOperandRecursively(OpUsedElements, Op, DAG)
10890                  : DAG.getUNDEF(OpVT));
10891       FoundSimplification |= Op == NewOps.back();
10892       OpUsedElements.reset();
10893     }
10894     if (FoundSimplification)
10895       V = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, NewOps);
10896     return V;
10897   }
10898
10899   case ISD::INSERT_SUBVECTOR: {
10900     SDValue BaseV = V->getOperand(0);
10901     SDValue SubV = V->getOperand(1);
10902     auto *IdxN = dyn_cast<ConstantSDNode>(V->getOperand(2));
10903     if (!IdxN)
10904       return V;
10905
10906     int SubSize = SubV.getValueType().getVectorNumElements();
10907     int Idx = IdxN->getZExtValue();
10908     bool SubVectorUsed = false;
10909     SmallBitVector SubUsedElements(SubSize, false);
10910     for (int i = 0; i < SubSize; ++i)
10911       if (UsedElements[i + Idx]) {
10912         SubVectorUsed = true;
10913         SubUsedElements[i] = true;
10914         UsedElements[i + Idx] = false;
10915       }
10916
10917     // Now recurse on both the base and sub vectors.
10918     SDValue SimplifiedSubV =
10919         SubVectorUsed
10920             ? simplifyShuffleOperandRecursively(SubUsedElements, SubV, DAG)
10921             : DAG.getUNDEF(SubV.getValueType());
10922     SDValue SimplifiedBaseV = simplifyShuffleOperandRecursively(UsedElements, BaseV, DAG);
10923     if (SimplifiedSubV != SubV || SimplifiedBaseV != BaseV)
10924       V = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
10925                       SimplifiedBaseV, SimplifiedSubV, V->getOperand(2));
10926     return V;
10927   }
10928   }
10929 }
10930
10931 static SDValue simplifyShuffleOperands(ShuffleVectorSDNode *SVN, SDValue N0,
10932                                        SDValue N1, SelectionDAG &DAG) {
10933   EVT VT = SVN->getValueType(0);
10934   int NumElts = VT.getVectorNumElements();
10935   SmallBitVector N0UsedElements(NumElts, false), N1UsedElements(NumElts, false);
10936   for (int M : SVN->getMask())
10937     if (M >= 0 && M < NumElts)
10938       N0UsedElements[M] = true;
10939     else if (M >= NumElts)
10940       N1UsedElements[M - NumElts] = true;
10941
10942   SDValue S0 = simplifyShuffleOperandRecursively(N0UsedElements, N0, DAG);
10943   SDValue S1 = simplifyShuffleOperandRecursively(N1UsedElements, N1, DAG);
10944   if (S0 == N0 && S1 == N1)
10945     return SDValue();
10946
10947   return DAG.getVectorShuffle(VT, SDLoc(SVN), S0, S1, SVN->getMask());
10948 }
10949
10950 // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
10951 static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
10952   EVT VT = N->getValueType(0);
10953   unsigned NumElts = VT.getVectorNumElements();
10954
10955   SDValue N0 = N->getOperand(0);
10956   SDValue N1 = N->getOperand(1);
10957   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
10958
10959   SmallVector<SDValue, 4> Ops;
10960   EVT ConcatVT = N0.getOperand(0).getValueType();
10961   unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
10962   unsigned NumConcats = NumElts / NumElemsPerConcat;
10963
10964   // Look at every vector that's inserted. We're looking for exact
10965   // subvector-sized copies from a concatenated vector
10966   for (unsigned I = 0; I != NumConcats; ++I) {
10967     // Make sure we're dealing with a copy.
10968     unsigned Begin = I * NumElemsPerConcat;
10969     bool AllUndef = true, NoUndef = true;
10970     for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
10971       if (SVN->getMaskElt(J) >= 0)
10972         AllUndef = false;
10973       else
10974         NoUndef = false;
10975     }
10976
10977     if (NoUndef) {
10978       if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
10979         return SDValue();
10980
10981       for (unsigned J = 1; J != NumElemsPerConcat; ++J)
10982         if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
10983           return SDValue();
10984
10985       unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
10986       if (FirstElt < N0.getNumOperands())
10987         Ops.push_back(N0.getOperand(FirstElt));
10988       else
10989         Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
10990
10991     } else if (AllUndef) {
10992       Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
10993     } else { // Mixed with general masks and undefs, can't do optimization.
10994       return SDValue();
10995     }
10996   }
10997
10998   return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
10999 }
11000
11001 SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
11002   EVT VT = N->getValueType(0);
11003   unsigned NumElts = VT.getVectorNumElements();
11004
11005   SDValue N0 = N->getOperand(0);
11006   SDValue N1 = N->getOperand(1);
11007
11008   assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
11009
11010   // Canonicalize shuffle undef, undef -> undef
11011   if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
11012     return DAG.getUNDEF(VT);
11013
11014   ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
11015
11016   // Canonicalize shuffle v, v -> v, undef
11017   if (N0 == N1) {
11018     SmallVector<int, 8> NewMask;
11019     for (unsigned i = 0; i != NumElts; ++i) {
11020       int Idx = SVN->getMaskElt(i);
11021       if (Idx >= (int)NumElts) Idx -= NumElts;
11022       NewMask.push_back(Idx);
11023     }
11024     return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
11025                                 &NewMask[0]);
11026   }
11027
11028   // Canonicalize shuffle undef, v -> v, undef.  Commute the shuffle mask.
11029   if (N0.getOpcode() == ISD::UNDEF) {
11030     SmallVector<int, 8> NewMask;
11031     for (unsigned i = 0; i != NumElts; ++i) {
11032       int Idx = SVN->getMaskElt(i);
11033       if (Idx >= 0) {
11034         if (Idx >= (int)NumElts)
11035           Idx -= NumElts;
11036         else
11037           Idx = -1; // remove reference to lhs
11038       }
11039       NewMask.push_back(Idx);
11040     }
11041     return DAG.getVectorShuffle(VT, SDLoc(N), N1, DAG.getUNDEF(VT),
11042                                 &NewMask[0]);
11043   }
11044
11045   // Remove references to rhs if it is undef
11046   if (N1.getOpcode() == ISD::UNDEF) {
11047     bool Changed = false;
11048     SmallVector<int, 8> NewMask;
11049     for (unsigned i = 0; i != NumElts; ++i) {
11050       int Idx = SVN->getMaskElt(i);
11051       if (Idx >= (int)NumElts) {
11052         Idx = -1;
11053         Changed = true;
11054       }
11055       NewMask.push_back(Idx);
11056     }
11057     if (Changed)
11058       return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, &NewMask[0]);
11059   }
11060
11061   // If it is a splat, check if the argument vector is another splat or a
11062   // build_vector with all scalar elements the same.
11063   if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
11064     SDNode *V = N0.getNode();
11065
11066     // If this is a bit convert that changes the element type of the vector but
11067     // not the number of vector elements, look through it.  Be careful not to
11068     // look though conversions that change things like v4f32 to v2f64.
11069     if (V->getOpcode() == ISD::BITCAST) {
11070       SDValue ConvInput = V->getOperand(0);
11071       if (ConvInput.getValueType().isVector() &&
11072           ConvInput.getValueType().getVectorNumElements() == NumElts)
11073         V = ConvInput.getNode();
11074     }
11075
11076     if (V->getOpcode() == ISD::BUILD_VECTOR) {
11077       assert(V->getNumOperands() == NumElts &&
11078              "BUILD_VECTOR has wrong number of operands");
11079       SDValue Base;
11080       bool AllSame = true;
11081       for (unsigned i = 0; i != NumElts; ++i) {
11082         if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
11083           Base = V->getOperand(i);
11084           break;
11085         }
11086       }
11087       // Splat of <u, u, u, u>, return <u, u, u, u>
11088       if (!Base.getNode())
11089         return N0;
11090       for (unsigned i = 0; i != NumElts; ++i) {
11091         if (V->getOperand(i) != Base) {
11092           AllSame = false;
11093           break;
11094         }
11095       }
11096       // Splat of <x, x, x, x>, return <x, x, x, x>
11097       if (AllSame)
11098         return N0;
11099     }
11100   }
11101
11102   // There are various patterns used to build up a vector from smaller vectors,
11103   // subvectors, or elements. Scan chains of these and replace unused insertions
11104   // or components with undef.
11105   if (SDValue S = simplifyShuffleOperands(SVN, N0, N1, DAG))
11106     return S;
11107
11108   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11109       Level < AfterLegalizeVectorOps &&
11110       (N1.getOpcode() == ISD::UNDEF ||
11111       (N1.getOpcode() == ISD::CONCAT_VECTORS &&
11112        N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
11113     SDValue V = partitionShuffleOfConcats(N, DAG);
11114
11115     if (V.getNode())
11116       return V;
11117   }
11118
11119   // Canonicalize shuffles according to rules:
11120   //  shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
11121   //  shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
11122   //  shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
11123   if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
11124       N0.getOpcode() != ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11125       TLI.isTypeLegal(VT)) {
11126     // The incoming shuffle must be of the same type as the result of the
11127     // current shuffle.
11128     assert(N1->getOperand(0).getValueType() == VT &&
11129            "Shuffle types don't match");
11130
11131     SDValue SV0 = N1->getOperand(0);
11132     SDValue SV1 = N1->getOperand(1);
11133     bool HasSameOp0 = N0 == SV0;
11134     bool IsSV1Undef = SV1.getOpcode() == ISD::UNDEF;
11135     if (HasSameOp0 || IsSV1Undef || N0 == SV1)
11136       // Commute the operands of this shuffle so that next rule
11137       // will trigger.
11138       return DAG.getCommutedVectorShuffle(*SVN);
11139   }
11140
11141   // Try to fold according to rules:
11142   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11143   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11144   //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11145   // Don't try to fold shuffles with illegal type.
11146   if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
11147       TLI.isTypeLegal(VT)) {
11148     ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
11149
11150     // The incoming shuffle must be of the same type as the result of the
11151     // current shuffle.
11152     assert(OtherSV->getOperand(0).getValueType() == VT &&
11153            "Shuffle types don't match");
11154
11155     SDValue SV0, SV1;
11156     SmallVector<int, 4> Mask;
11157     // Compute the combined shuffle mask for a shuffle with SV0 as the first
11158     // operand, and SV1 as the second operand.
11159     for (unsigned i = 0; i != NumElts; ++i) {
11160       int Idx = SVN->getMaskElt(i);
11161       if (Idx < 0) {
11162         // Propagate Undef.
11163         Mask.push_back(Idx);
11164         continue;
11165       }
11166
11167       SDValue CurrentVec;
11168       if (Idx < (int)NumElts) {
11169         // This shuffle index refers to the inner shuffle N0. Lookup the inner
11170         // shuffle mask to identify which vector is actually referenced.
11171         Idx = OtherSV->getMaskElt(Idx);
11172         if (Idx < 0) {
11173           // Propagate Undef.
11174           Mask.push_back(Idx);
11175           continue;
11176         }
11177
11178         CurrentVec = (Idx < (int) NumElts) ? OtherSV->getOperand(0)
11179                                            : OtherSV->getOperand(1);
11180       } else {
11181         // This shuffle index references an element within N1.
11182         CurrentVec = N1;
11183       }
11184
11185       // Simple case where 'CurrentVec' is UNDEF.
11186       if (CurrentVec.getOpcode() == ISD::UNDEF) {
11187         Mask.push_back(-1);
11188         continue;
11189       }
11190
11191       // Canonicalize the shuffle index. We don't know yet if CurrentVec
11192       // will be the first or second operand of the combined shuffle.
11193       Idx = Idx % NumElts;
11194       if (!SV0.getNode() || SV0 == CurrentVec) {
11195         // Ok. CurrentVec is the left hand side.
11196         // Update the mask accordingly.
11197         SV0 = CurrentVec;
11198         Mask.push_back(Idx);
11199         continue;
11200       }
11201
11202       // Bail out if we cannot convert the shuffle pair into a single shuffle.
11203       if (SV1.getNode() && SV1 != CurrentVec)
11204         return SDValue();
11205
11206       // Ok. CurrentVec is the right hand side.
11207       // Update the mask accordingly.
11208       SV1 = CurrentVec;
11209       Mask.push_back(Idx + NumElts);
11210     }
11211
11212     // Check if all indices in Mask are Undef. In case, propagate Undef.
11213     bool isUndefMask = true;
11214     for (unsigned i = 0; i != NumElts && isUndefMask; ++i)
11215       isUndefMask &= Mask[i] < 0;
11216
11217     if (isUndefMask)
11218       return DAG.getUNDEF(VT);
11219
11220     if (!SV0.getNode())
11221       SV0 = DAG.getUNDEF(VT);
11222     if (!SV1.getNode())
11223       SV1 = DAG.getUNDEF(VT);
11224
11225     // Avoid introducing shuffles with illegal mask.
11226     if (!TLI.isShuffleMaskLegal(Mask, VT)) {
11227       // Compute the commuted shuffle mask and test again.
11228       for (unsigned i = 0; i != NumElts; ++i) {
11229         int idx = Mask[i];
11230         if (idx < 0)
11231           continue;
11232         else if (idx < (int)NumElts)
11233           Mask[i] = idx + NumElts;
11234         else
11235           Mask[i] = idx - NumElts;
11236       }
11237
11238       if (!TLI.isShuffleMaskLegal(Mask, VT))
11239         return SDValue();
11240  
11241       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
11242       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
11243       //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
11244       std::swap(SV0, SV1);
11245     }
11246
11247     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
11248     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
11249     //   shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
11250     return DAG.getVectorShuffle(VT, SDLoc(N), SV0, SV1, &Mask[0]);
11251   }
11252
11253   return SDValue();
11254 }
11255
11256 SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
11257   SDValue N0 = N->getOperand(0);
11258   SDValue N2 = N->getOperand(2);
11259
11260   // If the input vector is a concatenation, and the insert replaces
11261   // one of the halves, we can optimize into a single concat_vectors.
11262   if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
11263       N0->getNumOperands() == 2 && N2.getOpcode() == ISD::Constant) {
11264     APInt InsIdx = cast<ConstantSDNode>(N2)->getAPIntValue();
11265     EVT VT = N->getValueType(0);
11266
11267     // Lower half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11268     // (concat_vectors Z, Y)
11269     if (InsIdx == 0)
11270       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11271                          N->getOperand(1), N0.getOperand(1));
11272
11273     // Upper half: fold (insert_subvector (concat_vectors X, Y), Z) ->
11274     // (concat_vectors X, Z)
11275     if (InsIdx == VT.getVectorNumElements()/2)
11276       return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
11277                          N0.getOperand(0), N->getOperand(1));
11278   }
11279
11280   return SDValue();
11281 }
11282
11283 /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
11284 /// with the destination vector and a zero vector.
11285 /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
11286 ///      vector_shuffle V, Zero, <0, 4, 2, 4>
11287 SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
11288   EVT VT = N->getValueType(0);
11289   SDLoc dl(N);
11290   SDValue LHS = N->getOperand(0);
11291   SDValue RHS = N->getOperand(1);
11292   if (N->getOpcode() == ISD::AND) {
11293     if (RHS.getOpcode() == ISD::BITCAST)
11294       RHS = RHS.getOperand(0);
11295     if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
11296       SmallVector<int, 8> Indices;
11297       unsigned NumElts = RHS.getNumOperands();
11298       for (unsigned i = 0; i != NumElts; ++i) {
11299         SDValue Elt = RHS.getOperand(i);
11300         if (!isa<ConstantSDNode>(Elt))
11301           return SDValue();
11302
11303         if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
11304           Indices.push_back(i);
11305         else if (cast<ConstantSDNode>(Elt)->isNullValue())
11306           Indices.push_back(NumElts+i);
11307         else
11308           return SDValue();
11309       }
11310
11311       // Let's see if the target supports this vector_shuffle.
11312       EVT RVT = RHS.getValueType();
11313       if (!TLI.isVectorClearMaskLegal(Indices, RVT))
11314         return SDValue();
11315
11316       // Return the new VECTOR_SHUFFLE node.
11317       EVT EltVT = RVT.getVectorElementType();
11318       SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
11319                                      DAG.getConstant(0, EltVT));
11320       SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), RVT, ZeroOps);
11321       LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
11322       SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
11323       return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
11324     }
11325   }
11326
11327   return SDValue();
11328 }
11329
11330 /// Visit a binary vector operation, like ADD.
11331 SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
11332   assert(N->getValueType(0).isVector() &&
11333          "SimplifyVBinOp only works on vectors!");
11334
11335   SDValue LHS = N->getOperand(0);
11336   SDValue RHS = N->getOperand(1);
11337   SDValue Shuffle = XformToShuffleWithZero(N);
11338   if (Shuffle.getNode()) return Shuffle;
11339
11340   // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
11341   // this operation.
11342   if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
11343       RHS.getOpcode() == ISD::BUILD_VECTOR) {
11344     // Check if both vectors are constants. If not bail out.
11345     if (!(cast<BuildVectorSDNode>(LHS)->isConstant() &&
11346           cast<BuildVectorSDNode>(RHS)->isConstant()))
11347       return SDValue();
11348
11349     SmallVector<SDValue, 8> Ops;
11350     for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
11351       SDValue LHSOp = LHS.getOperand(i);
11352       SDValue RHSOp = RHS.getOperand(i);
11353
11354       // Can't fold divide by zero.
11355       if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
11356           N->getOpcode() == ISD::FDIV) {
11357         if ((RHSOp.getOpcode() == ISD::Constant &&
11358              cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
11359             (RHSOp.getOpcode() == ISD::ConstantFP &&
11360              cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
11361           break;
11362       }
11363
11364       EVT VT = LHSOp.getValueType();
11365       EVT RVT = RHSOp.getValueType();
11366       if (RVT != VT) {
11367         // Integer BUILD_VECTOR operands may have types larger than the element
11368         // size (e.g., when the element type is not legal).  Prior to type
11369         // legalization, the types may not match between the two BUILD_VECTORS.
11370         // Truncate one of the operands to make them match.
11371         if (RVT.getSizeInBits() > VT.getSizeInBits()) {
11372           RHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, RHSOp);
11373         } else {
11374           LHSOp = DAG.getNode(ISD::TRUNCATE, SDLoc(N), RVT, LHSOp);
11375           VT = RVT;
11376         }
11377       }
11378       SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(LHS), VT,
11379                                    LHSOp, RHSOp);
11380       if (FoldOp.getOpcode() != ISD::UNDEF &&
11381           FoldOp.getOpcode() != ISD::Constant &&
11382           FoldOp.getOpcode() != ISD::ConstantFP)
11383         break;
11384       Ops.push_back(FoldOp);
11385       AddToWorklist(FoldOp.getNode());
11386     }
11387
11388     if (Ops.size() == LHS.getNumOperands())
11389       return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), LHS.getValueType(), Ops);
11390   }
11391
11392   // Type legalization might introduce new shuffles in the DAG.
11393   // Fold (VBinOp (shuffle (A, Undef, Mask)), (shuffle (B, Undef, Mask)))
11394   //   -> (shuffle (VBinOp (A, B)), Undef, Mask).
11395   if (LegalTypes && isa<ShuffleVectorSDNode>(LHS) &&
11396       isa<ShuffleVectorSDNode>(RHS) && LHS.hasOneUse() && RHS.hasOneUse() &&
11397       LHS.getOperand(1).getOpcode() == ISD::UNDEF &&
11398       RHS.getOperand(1).getOpcode() == ISD::UNDEF) {
11399     ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(LHS);
11400     ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(RHS);
11401
11402     if (SVN0->getMask().equals(SVN1->getMask())) {
11403       EVT VT = N->getValueType(0);
11404       SDValue UndefVector = LHS.getOperand(1);
11405       SDValue NewBinOp = DAG.getNode(N->getOpcode(), SDLoc(N), VT,
11406                                      LHS.getOperand(0), RHS.getOperand(0));
11407       AddUsersToWorklist(N);
11408       return DAG.getVectorShuffle(VT, SDLoc(N), NewBinOp, UndefVector,
11409                                   &SVN0->getMask()[0]);
11410     }
11411   }
11412
11413   return SDValue();
11414 }
11415
11416 /// Visit a binary vector operation, like FABS/FNEG.
11417 SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
11418   assert(N->getValueType(0).isVector() &&
11419          "SimplifyVUnaryOp only works on vectors!");
11420
11421   SDValue N0 = N->getOperand(0);
11422
11423   if (N0.getOpcode() != ISD::BUILD_VECTOR)
11424     return SDValue();
11425
11426   // Operand is a BUILD_VECTOR node, see if we can constant fold it.
11427   SmallVector<SDValue, 8> Ops;
11428   for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
11429     SDValue Op = N0.getOperand(i);
11430     if (Op.getOpcode() != ISD::UNDEF &&
11431         Op.getOpcode() != ISD::ConstantFP)
11432       break;
11433     EVT EltVT = Op.getValueType();
11434     SDValue FoldOp = DAG.getNode(N->getOpcode(), SDLoc(N0), EltVT, Op);
11435     if (FoldOp.getOpcode() != ISD::UNDEF &&
11436         FoldOp.getOpcode() != ISD::ConstantFP)
11437       break;
11438     Ops.push_back(FoldOp);
11439     AddToWorklist(FoldOp.getNode());
11440   }
11441
11442   if (Ops.size() != N0.getNumOperands())
11443     return SDValue();
11444
11445   return DAG.getNode(ISD::BUILD_VECTOR, SDLoc(N), N0.getValueType(), Ops);
11446 }
11447
11448 SDValue DAGCombiner::SimplifySelect(SDLoc DL, SDValue N0,
11449                                     SDValue N1, SDValue N2){
11450   assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
11451
11452   SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
11453                                  cast<CondCodeSDNode>(N0.getOperand(2))->get());
11454
11455   // If we got a simplified select_cc node back from SimplifySelectCC, then
11456   // break it down into a new SETCC node, and a new SELECT node, and then return
11457   // the SELECT node, since we were called with a SELECT node.
11458   if (SCC.getNode()) {
11459     // Check to see if we got a select_cc back (to turn into setcc/select).
11460     // Otherwise, just return whatever node we got back, like fabs.
11461     if (SCC.getOpcode() == ISD::SELECT_CC) {
11462       SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
11463                                   N0.getValueType(),
11464                                   SCC.getOperand(0), SCC.getOperand(1),
11465                                   SCC.getOperand(4));
11466       AddToWorklist(SETCC.getNode());
11467       return DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
11468                            SCC.getOperand(2), SCC.getOperand(3));
11469     }
11470
11471     return SCC;
11472   }
11473   return SDValue();
11474 }
11475
11476 /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
11477 /// being selected between, see if we can simplify the select.  Callers of this
11478 /// should assume that TheSelect is deleted if this returns true.  As such, they
11479 /// should return the appropriate thing (e.g. the node) back to the top-level of
11480 /// the DAG combiner loop to avoid it being looked at.
11481 bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
11482                                     SDValue RHS) {
11483
11484   // Cannot simplify select with vector condition
11485   if (TheSelect->getOperand(0).getValueType().isVector()) return false;
11486
11487   // If this is a select from two identical things, try to pull the operation
11488   // through the select.
11489   if (LHS.getOpcode() != RHS.getOpcode() ||
11490       !LHS.hasOneUse() || !RHS.hasOneUse())
11491     return false;
11492
11493   // If this is a load and the token chain is identical, replace the select
11494   // of two loads with a load through a select of the address to load from.
11495   // This triggers in things like "select bool X, 10.0, 123.0" after the FP
11496   // constants have been dropped into the constant pool.
11497   if (LHS.getOpcode() == ISD::LOAD) {
11498     LoadSDNode *LLD = cast<LoadSDNode>(LHS);
11499     LoadSDNode *RLD = cast<LoadSDNode>(RHS);
11500
11501     // Token chains must be identical.
11502     if (LHS.getOperand(0) != RHS.getOperand(0) ||
11503         // Do not let this transformation reduce the number of volatile loads.
11504         LLD->isVolatile() || RLD->isVolatile() ||
11505         // If this is an EXTLOAD, the VT's must match.
11506         LLD->getMemoryVT() != RLD->getMemoryVT() ||
11507         // If this is an EXTLOAD, the kind of extension must match.
11508         (LLD->getExtensionType() != RLD->getExtensionType() &&
11509          // The only exception is if one of the extensions is anyext.
11510          LLD->getExtensionType() != ISD::EXTLOAD &&
11511          RLD->getExtensionType() != ISD::EXTLOAD) ||
11512         // FIXME: this discards src value information.  This is
11513         // over-conservative. It would be beneficial to be able to remember
11514         // both potential memory locations.  Since we are discarding
11515         // src value info, don't do the transformation if the memory
11516         // locations are not in the default address space.
11517         LLD->getPointerInfo().getAddrSpace() != 0 ||
11518         RLD->getPointerInfo().getAddrSpace() != 0 ||
11519         !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
11520                                       LLD->getBasePtr().getValueType()))
11521       return false;
11522
11523     // Check that the select condition doesn't reach either load.  If so,
11524     // folding this will induce a cycle into the DAG.  If not, this is safe to
11525     // xform, so create a select of the addresses.
11526     SDValue Addr;
11527     if (TheSelect->getOpcode() == ISD::SELECT) {
11528       SDNode *CondNode = TheSelect->getOperand(0).getNode();
11529       if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
11530           (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
11531         return false;
11532       // The loads must not depend on one another.
11533       if (LLD->isPredecessorOf(RLD) ||
11534           RLD->isPredecessorOf(LLD))
11535         return false;
11536       Addr = DAG.getSelect(SDLoc(TheSelect),
11537                            LLD->getBasePtr().getValueType(),
11538                            TheSelect->getOperand(0), LLD->getBasePtr(),
11539                            RLD->getBasePtr());
11540     } else {  // Otherwise SELECT_CC
11541       SDNode *CondLHS = TheSelect->getOperand(0).getNode();
11542       SDNode *CondRHS = TheSelect->getOperand(1).getNode();
11543
11544       if ((LLD->hasAnyUseOfValue(1) &&
11545            (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
11546           (RLD->hasAnyUseOfValue(1) &&
11547            (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
11548         return false;
11549
11550       Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
11551                          LLD->getBasePtr().getValueType(),
11552                          TheSelect->getOperand(0),
11553                          TheSelect->getOperand(1),
11554                          LLD->getBasePtr(), RLD->getBasePtr(),
11555                          TheSelect->getOperand(4));
11556     }
11557
11558     SDValue Load;
11559     // It is safe to replace the two loads if they have different alignments,
11560     // but the new load must be the minimum (most restrictive) alignment of the
11561     // inputs.
11562     bool isInvariant = LLD->isInvariant() & RLD->isInvariant();
11563     unsigned Alignment = std::min(LLD->getAlignment(), RLD->getAlignment());
11564     if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
11565       Load = DAG.getLoad(TheSelect->getValueType(0),
11566                          SDLoc(TheSelect),
11567                          // FIXME: Discards pointer and AA info.
11568                          LLD->getChain(), Addr, MachinePointerInfo(),
11569                          LLD->isVolatile(), LLD->isNonTemporal(),
11570                          isInvariant, Alignment);
11571     } else {
11572       Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
11573                             RLD->getExtensionType() : LLD->getExtensionType(),
11574                             SDLoc(TheSelect),
11575                             TheSelect->getValueType(0),
11576                             // FIXME: Discards pointer and AA info.
11577                             LLD->getChain(), Addr, MachinePointerInfo(),
11578                             LLD->getMemoryVT(), LLD->isVolatile(),
11579                             LLD->isNonTemporal(), isInvariant, Alignment);
11580     }
11581
11582     // Users of the select now use the result of the load.
11583     CombineTo(TheSelect, Load);
11584
11585     // Users of the old loads now use the new load's chain.  We know the
11586     // old-load value is dead now.
11587     CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
11588     CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
11589     return true;
11590   }
11591
11592   return false;
11593 }
11594
11595 /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
11596 /// where 'cond' is the comparison specified by CC.
11597 SDValue DAGCombiner::SimplifySelectCC(SDLoc DL, SDValue N0, SDValue N1,
11598                                       SDValue N2, SDValue N3,
11599                                       ISD::CondCode CC, bool NotExtCompare) {
11600   // (x ? y : y) -> y.
11601   if (N2 == N3) return N2;
11602
11603   EVT VT = N2.getValueType();
11604   ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
11605   ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
11606   ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
11607
11608   // Determine if the condition we're dealing with is constant
11609   SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
11610                               N0, N1, CC, DL, false);
11611   if (SCC.getNode()) AddToWorklist(SCC.getNode());
11612   ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
11613
11614   // fold select_cc true, x, y -> x
11615   if (SCCC && !SCCC->isNullValue())
11616     return N2;
11617   // fold select_cc false, x, y -> y
11618   if (SCCC && SCCC->isNullValue())
11619     return N3;
11620
11621   // Check to see if we can simplify the select into an fabs node
11622   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
11623     // Allow either -0.0 or 0.0
11624     if (CFP->getValueAPF().isZero()) {
11625       // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
11626       if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
11627           N0 == N2 && N3.getOpcode() == ISD::FNEG &&
11628           N2 == N3.getOperand(0))
11629         return DAG.getNode(ISD::FABS, DL, VT, N0);
11630
11631       // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
11632       if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
11633           N0 == N3 && N2.getOpcode() == ISD::FNEG &&
11634           N2.getOperand(0) == N3)
11635         return DAG.getNode(ISD::FABS, DL, VT, N3);
11636     }
11637   }
11638
11639   // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
11640   // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
11641   // in it.  This is a win when the constant is not otherwise available because
11642   // it replaces two constant pool loads with one.  We only do this if the FP
11643   // type is known to be legal, because if it isn't, then we are before legalize
11644   // types an we want the other legalization to happen first (e.g. to avoid
11645   // messing with soft float) and if the ConstantFP is not legal, because if
11646   // it is legal, we may not need to store the FP constant in a constant pool.
11647   if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
11648     if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
11649       if (TLI.isTypeLegal(N2.getValueType()) &&
11650           (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
11651                TargetLowering::Legal &&
11652            !TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0)) &&
11653            !TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0))) &&
11654           // If both constants have multiple uses, then we won't need to do an
11655           // extra load, they are likely around in registers for other users.
11656           (TV->hasOneUse() || FV->hasOneUse())) {
11657         Constant *Elts[] = {
11658           const_cast<ConstantFP*>(FV->getConstantFPValue()),
11659           const_cast<ConstantFP*>(TV->getConstantFPValue())
11660         };
11661         Type *FPTy = Elts[0]->getType();
11662         const DataLayout &TD = *TLI.getDataLayout();
11663
11664         // Create a ConstantArray of the two constants.
11665         Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
11666         SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
11667                                             TD.getPrefTypeAlignment(FPTy));
11668         unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
11669
11670         // Get the offsets to the 0 and 1 element of the array so that we can
11671         // select between them.
11672         SDValue Zero = DAG.getIntPtrConstant(0);
11673         unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
11674         SDValue One = DAG.getIntPtrConstant(EltSize);
11675
11676         SDValue Cond = DAG.getSetCC(DL,
11677                                     getSetCCResultType(N0.getValueType()),
11678                                     N0, N1, CC);
11679         AddToWorklist(Cond.getNode());
11680         SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(),
11681                                           Cond, One, Zero);
11682         AddToWorklist(CstOffset.getNode());
11683         CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx,
11684                             CstOffset);
11685         AddToWorklist(CPIdx.getNode());
11686         return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
11687                            MachinePointerInfo::getConstantPool(), false,
11688                            false, false, Alignment);
11689
11690       }
11691     }
11692
11693   // Check to see if we can perform the "gzip trick", transforming
11694   // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
11695   if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
11696       (N1C->isNullValue() ||                         // (a < 0) ? b : 0
11697        (N1C->getAPIntValue() == 1 && N0 == N2))) {   // (a < 1) ? a : 0
11698     EVT XType = N0.getValueType();
11699     EVT AType = N2.getValueType();
11700     if (XType.bitsGE(AType)) {
11701       // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
11702       // single-bit constant.
11703       if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
11704         unsigned ShCtV = N2C->getAPIntValue().logBase2();
11705         ShCtV = XType.getSizeInBits()-ShCtV-1;
11706         SDValue ShCt = DAG.getConstant(ShCtV,
11707                                        getShiftAmountTy(N0.getValueType()));
11708         SDValue Shift = DAG.getNode(ISD::SRL, SDLoc(N0),
11709                                     XType, N0, ShCt);
11710         AddToWorklist(Shift.getNode());
11711
11712         if (XType.bitsGT(AType)) {
11713           Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11714           AddToWorklist(Shift.getNode());
11715         }
11716
11717         return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11718       }
11719
11720       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0),
11721                                   XType, N0,
11722                                   DAG.getConstant(XType.getSizeInBits()-1,
11723                                          getShiftAmountTy(N0.getValueType())));
11724       AddToWorklist(Shift.getNode());
11725
11726       if (XType.bitsGT(AType)) {
11727         Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
11728         AddToWorklist(Shift.getNode());
11729       }
11730
11731       return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
11732     }
11733   }
11734
11735   // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
11736   // where y is has a single bit set.
11737   // A plaintext description would be, we can turn the SELECT_CC into an AND
11738   // when the condition can be materialized as an all-ones register.  Any
11739   // single bit-test can be materialized as an all-ones register with
11740   // shift-left and shift-right-arith.
11741   if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
11742       N0->getValueType(0) == VT &&
11743       N1C && N1C->isNullValue() &&
11744       N2C && N2C->isNullValue()) {
11745     SDValue AndLHS = N0->getOperand(0);
11746     ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
11747     if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
11748       // Shift the tested bit over the sign bit.
11749       APInt AndMask = ConstAndRHS->getAPIntValue();
11750       SDValue ShlAmt =
11751         DAG.getConstant(AndMask.countLeadingZeros(),
11752                         getShiftAmountTy(AndLHS.getValueType()));
11753       SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
11754
11755       // Now arithmetic right shift it all the way over, so the result is either
11756       // all-ones, or zero.
11757       SDValue ShrAmt =
11758         DAG.getConstant(AndMask.getBitWidth()-1,
11759                         getShiftAmountTy(Shl.getValueType()));
11760       SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
11761
11762       return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
11763     }
11764   }
11765
11766   // fold select C, 16, 0 -> shl C, 4
11767   if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
11768       TLI.getBooleanContents(N0.getValueType()) ==
11769           TargetLowering::ZeroOrOneBooleanContent) {
11770
11771     // If the caller doesn't want us to simplify this into a zext of a compare,
11772     // don't do it.
11773     if (NotExtCompare && N2C->getAPIntValue() == 1)
11774       return SDValue();
11775
11776     // Get a SetCC of the condition
11777     // NOTE: Don't create a SETCC if it's not legal on this target.
11778     if (!LegalOperations ||
11779         TLI.isOperationLegal(ISD::SETCC,
11780           LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
11781       SDValue Temp, SCC;
11782       // cast from setcc result type to select result type
11783       if (LegalTypes) {
11784         SCC  = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
11785                             N0, N1, CC);
11786         if (N2.getValueType().bitsLT(SCC.getValueType()))
11787           Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2),
11788                                         N2.getValueType());
11789         else
11790           Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11791                              N2.getValueType(), SCC);
11792       } else {
11793         SCC  = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
11794         Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2),
11795                            N2.getValueType(), SCC);
11796       }
11797
11798       AddToWorklist(SCC.getNode());
11799       AddToWorklist(Temp.getNode());
11800
11801       if (N2C->getAPIntValue() == 1)
11802         return Temp;
11803
11804       // shl setcc result by log2 n2c
11805       return DAG.getNode(
11806           ISD::SHL, DL, N2.getValueType(), Temp,
11807           DAG.getConstant(N2C->getAPIntValue().logBase2(),
11808                           getShiftAmountTy(Temp.getValueType())));
11809     }
11810   }
11811
11812   // Check to see if this is the equivalent of setcc
11813   // FIXME: Turn all of these into setcc if setcc if setcc is legal
11814   // otherwise, go ahead with the folds.
11815   if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
11816     EVT XType = N0.getValueType();
11817     if (!LegalOperations ||
11818         TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
11819       SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
11820       if (Res.getValueType() != VT)
11821         Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
11822       return Res;
11823     }
11824
11825     // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
11826     if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
11827         (!LegalOperations ||
11828          TLI.isOperationLegal(ISD::CTLZ, XType))) {
11829       SDValue Ctlz = DAG.getNode(ISD::CTLZ, SDLoc(N0), XType, N0);
11830       return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
11831                          DAG.getConstant(Log2_32(XType.getSizeInBits()),
11832                                        getShiftAmountTy(Ctlz.getValueType())));
11833     }
11834     // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
11835     if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
11836       SDValue NegN0 = DAG.getNode(ISD::SUB, SDLoc(N0),
11837                                   XType, DAG.getConstant(0, XType), N0);
11838       SDValue NotN0 = DAG.getNOT(SDLoc(N0), N0, XType);
11839       return DAG.getNode(ISD::SRL, DL, XType,
11840                          DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
11841                          DAG.getConstant(XType.getSizeInBits()-1,
11842                                          getShiftAmountTy(XType)));
11843     }
11844     // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
11845     if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
11846       SDValue Sign = DAG.getNode(ISD::SRL, SDLoc(N0), XType, N0,
11847                                  DAG.getConstant(XType.getSizeInBits()-1,
11848                                          getShiftAmountTy(N0.getValueType())));
11849       return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
11850     }
11851   }
11852
11853   // Check to see if this is an integer abs.
11854   // select_cc setg[te] X,  0,  X, -X ->
11855   // select_cc setgt    X, -1,  X, -X ->
11856   // select_cc setl[te] X,  0, -X,  X ->
11857   // select_cc setlt    X,  1, -X,  X ->
11858   // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
11859   if (N1C) {
11860     ConstantSDNode *SubC = nullptr;
11861     if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
11862          (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
11863         N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
11864       SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
11865     else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
11866               (N1C->isOne() && CC == ISD::SETLT)) &&
11867              N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
11868       SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
11869
11870     EVT XType = N0.getValueType();
11871     if (SubC && SubC->isNullValue() && XType.isInteger()) {
11872       SDValue Shift = DAG.getNode(ISD::SRA, SDLoc(N0), XType,
11873                                   N0,
11874                                   DAG.getConstant(XType.getSizeInBits()-1,
11875                                          getShiftAmountTy(N0.getValueType())));
11876       SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0),
11877                                 XType, N0, Shift);
11878       AddToWorklist(Shift.getNode());
11879       AddToWorklist(Add.getNode());
11880       return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
11881     }
11882   }
11883
11884   return SDValue();
11885 }
11886
11887 /// This is a stub for TargetLowering::SimplifySetCC.
11888 SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
11889                                    SDValue N1, ISD::CondCode Cond,
11890                                    SDLoc DL, bool foldBooleans) {
11891   TargetLowering::DAGCombinerInfo
11892     DagCombineInfo(DAG, Level, false, this);
11893   return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
11894 }
11895
11896 /// Given an ISD::SDIV node expressing a divide by constant, return
11897 /// a DAG expression to select that will generate the same value by multiplying
11898 /// by a magic number.
11899 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11900 SDValue DAGCombiner::BuildSDIV(SDNode *N) {
11901   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11902   if (!C)
11903     return SDValue();
11904
11905   // Avoid division by zero.
11906   if (!C->getAPIntValue())
11907     return SDValue();
11908
11909   std::vector<SDNode*> Built;
11910   SDValue S =
11911       TLI.BuildSDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11912
11913   for (SDNode *N : Built)
11914     AddToWorklist(N);
11915   return S;
11916 }
11917
11918 /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
11919 /// DAG expression that will generate the same value by right shifting.
11920 SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
11921   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11922   if (!C)
11923     return SDValue();
11924
11925   // Avoid division by zero.
11926   if (!C->getAPIntValue())
11927     return SDValue();
11928
11929   std::vector<SDNode *> Built;
11930   SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, &Built);
11931
11932   for (SDNode *N : Built)
11933     AddToWorklist(N);
11934   return S;
11935 }
11936
11937 /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
11938 /// expression that will generate the same value by multiplying by a magic
11939 /// number.
11940 /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
11941 SDValue DAGCombiner::BuildUDIV(SDNode *N) {
11942   ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
11943   if (!C)
11944     return SDValue();
11945
11946   // Avoid division by zero.
11947   if (!C->getAPIntValue())
11948     return SDValue();
11949
11950   std::vector<SDNode*> Built;
11951   SDValue S =
11952       TLI.BuildUDIV(N, C->getAPIntValue(), DAG, LegalOperations, &Built);
11953
11954   for (SDNode *N : Built)
11955     AddToWorklist(N);
11956   return S;
11957 }
11958
11959 SDValue DAGCombiner::BuildReciprocalEstimate(SDValue Op) {
11960   if (Level >= AfterLegalizeDAG)
11961     return SDValue();
11962
11963   // Expose the DAG combiner to the target combiner implementations.
11964   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
11965
11966   unsigned Iterations = 0;
11967   if (SDValue Est = TLI.getRecipEstimate(Op, DCI, Iterations)) {
11968     if (Iterations) {
11969       // Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
11970       // For the reciprocal, we need to find the zero of the function:
11971       //   F(X) = A X - 1 [which has a zero at X = 1/A]
11972       //     =>
11973       //   X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
11974       //     does not require additional intermediate precision]
11975       EVT VT = Op.getValueType();
11976       SDLoc DL(Op);
11977       SDValue FPOne = DAG.getConstantFP(1.0, VT);
11978
11979       AddToWorklist(Est.getNode());
11980
11981       // Newton iterations: Est = Est + Est (1 - Arg * Est)
11982       for (unsigned i = 0; i < Iterations; ++i) {
11983         SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, Est);
11984         AddToWorklist(NewEst.getNode());
11985
11986         NewEst = DAG.getNode(ISD::FSUB, DL, VT, FPOne, NewEst);
11987         AddToWorklist(NewEst.getNode());
11988
11989         NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
11990         AddToWorklist(NewEst.getNode());
11991
11992         Est = DAG.getNode(ISD::FADD, DL, VT, Est, NewEst);
11993         AddToWorklist(Est.getNode());
11994       }
11995     }
11996     return Est;
11997   }
11998
11999   return SDValue();
12000 }
12001
12002 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12003 /// For the reciprocal sqrt, we need to find the zero of the function:
12004 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12005 ///     =>
12006 ///   X_{i+1} = X_i (1.5 - A X_i^2 / 2)
12007 /// As a result, we precompute A/2 prior to the iteration loop.
12008 SDValue DAGCombiner::BuildRsqrtNROneConst(SDValue Arg, SDValue Est,
12009                                           unsigned Iterations) {
12010   EVT VT = Arg.getValueType();
12011   SDLoc DL(Arg);
12012   SDValue ThreeHalves = DAG.getConstantFP(1.5, VT);
12013
12014   // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
12015   // this entire sequence requires only one FP constant.
12016   SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg);
12017   AddToWorklist(HalfArg.getNode());
12018
12019   HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg);
12020   AddToWorklist(HalfArg.getNode());
12021
12022   // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
12023   for (unsigned i = 0; i < Iterations; ++i) {
12024     SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12025     AddToWorklist(NewEst.getNode());
12026
12027     NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst);
12028     AddToWorklist(NewEst.getNode());
12029
12030     NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst);
12031     AddToWorklist(NewEst.getNode());
12032
12033     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst);
12034     AddToWorklist(Est.getNode());
12035   }
12036   return Est;
12037 }
12038
12039 /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
12040 /// For the reciprocal sqrt, we need to find the zero of the function:
12041 ///   F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
12042 ///     =>
12043 ///   X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
12044 SDValue DAGCombiner::BuildRsqrtNRTwoConst(SDValue Arg, SDValue Est,
12045                                           unsigned Iterations) {
12046   EVT VT = Arg.getValueType();
12047   SDLoc DL(Arg);
12048   SDValue MinusThree = DAG.getConstantFP(-3.0, VT);
12049   SDValue MinusHalf = DAG.getConstantFP(-0.5, VT);
12050
12051   // Newton iterations: Est = -0.5 * Est * (-3.0 + Arg * Est * Est)
12052   for (unsigned i = 0; i < Iterations; ++i) {
12053     SDValue HalfEst = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf);
12054     AddToWorklist(HalfEst.getNode());
12055
12056     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Est);
12057     AddToWorklist(Est.getNode());
12058
12059     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg);
12060     AddToWorklist(Est.getNode());
12061
12062     Est = DAG.getNode(ISD::FADD, DL, VT, Est, MinusThree);
12063     AddToWorklist(Est.getNode());
12064
12065     Est = DAG.getNode(ISD::FMUL, DL, VT, Est, HalfEst);
12066     AddToWorklist(Est.getNode());
12067   }
12068   return Est;
12069 }
12070
12071 SDValue DAGCombiner::BuildRsqrtEstimate(SDValue Op) {
12072   if (Level >= AfterLegalizeDAG)
12073     return SDValue();
12074
12075   // Expose the DAG combiner to the target combiner implementations.
12076   TargetLowering::DAGCombinerInfo DCI(DAG, Level, false, this);
12077   unsigned Iterations = 0;
12078   bool UseOneConstNR = false;
12079   if (SDValue Est = TLI.getRsqrtEstimate(Op, DCI, Iterations, UseOneConstNR)) {
12080     AddToWorklist(Est.getNode());
12081     if (Iterations) {
12082       Est = UseOneConstNR ?
12083         BuildRsqrtNROneConst(Op, Est, Iterations) :
12084         BuildRsqrtNRTwoConst(Op, Est, Iterations);
12085     }
12086     return Est;
12087   }
12088
12089   return SDValue();
12090 }
12091
12092 /// Return true if base is a frame index, which is known not to alias with
12093 /// anything but itself.  Provides base object and offset as results.
12094 static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
12095                            const GlobalValue *&GV, const void *&CV) {
12096   // Assume it is a primitive operation.
12097   Base = Ptr; Offset = 0; GV = nullptr; CV = nullptr;
12098
12099   // If it's an adding a simple constant then integrate the offset.
12100   if (Base.getOpcode() == ISD::ADD) {
12101     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
12102       Base = Base.getOperand(0);
12103       Offset += C->getZExtValue();
12104     }
12105   }
12106
12107   // Return the underlying GlobalValue, and update the Offset.  Return false
12108   // for GlobalAddressSDNode since the same GlobalAddress may be represented
12109   // by multiple nodes with different offsets.
12110   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
12111     GV = G->getGlobal();
12112     Offset += G->getOffset();
12113     return false;
12114   }
12115
12116   // Return the underlying Constant value, and update the Offset.  Return false
12117   // for ConstantSDNodes since the same constant pool entry may be represented
12118   // by multiple nodes with different offsets.
12119   if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
12120     CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
12121                                          : (const void *)C->getConstVal();
12122     Offset += C->getOffset();
12123     return false;
12124   }
12125   // If it's any of the following then it can't alias with anything but itself.
12126   return isa<FrameIndexSDNode>(Base);
12127 }
12128
12129 /// Return true if there is any possibility that the two addresses overlap.
12130 bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) const {
12131   // If they are the same then they must be aliases.
12132   if (Op0->getBasePtr() == Op1->getBasePtr()) return true;
12133
12134   // If they are both volatile then they cannot be reordered.
12135   if (Op0->isVolatile() && Op1->isVolatile()) return true;
12136
12137   // Gather base node and offset information.
12138   SDValue Base1, Base2;
12139   int64_t Offset1, Offset2;
12140   const GlobalValue *GV1, *GV2;
12141   const void *CV1, *CV2;
12142   bool isFrameIndex1 = FindBaseOffset(Op0->getBasePtr(),
12143                                       Base1, Offset1, GV1, CV1);
12144   bool isFrameIndex2 = FindBaseOffset(Op1->getBasePtr(),
12145                                       Base2, Offset2, GV2, CV2);
12146
12147   // If they have a same base address then check to see if they overlap.
12148   if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
12149     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12150              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12151
12152   // It is possible for different frame indices to alias each other, mostly
12153   // when tail call optimization reuses return address slots for arguments.
12154   // To catch this case, look up the actual index of frame indices to compute
12155   // the real alias relationship.
12156   if (isFrameIndex1 && isFrameIndex2) {
12157     MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
12158     Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
12159     Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
12160     return !((Offset1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= Offset2 ||
12161              (Offset2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= Offset1);
12162   }
12163
12164   // Otherwise, if we know what the bases are, and they aren't identical, then
12165   // we know they cannot alias.
12166   if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
12167     return false;
12168
12169   // If we know required SrcValue1 and SrcValue2 have relatively large alignment
12170   // compared to the size and offset of the access, we may be able to prove they
12171   // do not alias.  This check is conservative for now to catch cases created by
12172   // splitting vector types.
12173   if ((Op0->getOriginalAlignment() == Op1->getOriginalAlignment()) &&
12174       (Op0->getSrcValueOffset() != Op1->getSrcValueOffset()) &&
12175       (Op0->getMemoryVT().getSizeInBits() >> 3 ==
12176        Op1->getMemoryVT().getSizeInBits() >> 3) &&
12177       (Op0->getOriginalAlignment() > Op0->getMemoryVT().getSizeInBits()) >> 3) {
12178     int64_t OffAlign1 = Op0->getSrcValueOffset() % Op0->getOriginalAlignment();
12179     int64_t OffAlign2 = Op1->getSrcValueOffset() % Op1->getOriginalAlignment();
12180
12181     // There is no overlap between these relatively aligned accesses of similar
12182     // size, return no alias.
12183     if ((OffAlign1 + (Op0->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign2 ||
12184         (OffAlign2 + (Op1->getMemoryVT().getSizeInBits() >> 3)) <= OffAlign1)
12185       return false;
12186   }
12187
12188   bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
12189                    ? CombinerGlobalAA
12190                    : DAG.getSubtarget().useAA();
12191 #ifndef NDEBUG
12192   if (CombinerAAOnlyFunc.getNumOccurrences() &&
12193       CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
12194     UseAA = false;
12195 #endif
12196   if (UseAA &&
12197       Op0->getMemOperand()->getValue() && Op1->getMemOperand()->getValue()) {
12198     // Use alias analysis information.
12199     int64_t MinOffset = std::min(Op0->getSrcValueOffset(),
12200                                  Op1->getSrcValueOffset());
12201     int64_t Overlap1 = (Op0->getMemoryVT().getSizeInBits() >> 3) +
12202         Op0->getSrcValueOffset() - MinOffset;
12203     int64_t Overlap2 = (Op1->getMemoryVT().getSizeInBits() >> 3) +
12204         Op1->getSrcValueOffset() - MinOffset;
12205     AliasAnalysis::AliasResult AAResult =
12206         AA.alias(AliasAnalysis::Location(Op0->getMemOperand()->getValue(),
12207                                          Overlap1,
12208                                          UseTBAA ? Op0->getAAInfo() : AAMDNodes()),
12209                  AliasAnalysis::Location(Op1->getMemOperand()->getValue(),
12210                                          Overlap2,
12211                                          UseTBAA ? Op1->getAAInfo() : AAMDNodes()));
12212     if (AAResult == AliasAnalysis::NoAlias)
12213       return false;
12214   }
12215
12216   // Otherwise we have to assume they alias.
12217   return true;
12218 }
12219
12220 /// Walk up chain skipping non-aliasing memory nodes,
12221 /// looking for aliasing nodes and adding them to the Aliases vector.
12222 void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
12223                                    SmallVectorImpl<SDValue> &Aliases) {
12224   SmallVector<SDValue, 8> Chains;     // List of chains to visit.
12225   SmallPtrSet<SDNode *, 16> Visited;  // Visited node set.
12226
12227   // Get alias information for node.
12228   bool IsLoad = isa<LoadSDNode>(N) && !cast<LSBaseSDNode>(N)->isVolatile();
12229
12230   // Starting off.
12231   Chains.push_back(OriginalChain);
12232   unsigned Depth = 0;
12233
12234   // Look at each chain and determine if it is an alias.  If so, add it to the
12235   // aliases list.  If not, then continue up the chain looking for the next
12236   // candidate.
12237   while (!Chains.empty()) {
12238     SDValue Chain = Chains.back();
12239     Chains.pop_back();
12240
12241     // For TokenFactor nodes, look at each operand and only continue up the
12242     // chain until we find two aliases.  If we've seen two aliases, assume we'll
12243     // find more and revert to original chain since the xform is unlikely to be
12244     // profitable.
12245     //
12246     // FIXME: The depth check could be made to return the last non-aliasing
12247     // chain we found before we hit a tokenfactor rather than the original
12248     // chain.
12249     if (Depth > 6 || Aliases.size() == 2) {
12250       Aliases.clear();
12251       Aliases.push_back(OriginalChain);
12252       return;
12253     }
12254
12255     // Don't bother if we've been before.
12256     if (!Visited.insert(Chain.getNode()).second)
12257       continue;
12258
12259     switch (Chain.getOpcode()) {
12260     case ISD::EntryToken:
12261       // Entry token is ideal chain operand, but handled in FindBetterChain.
12262       break;
12263
12264     case ISD::LOAD:
12265     case ISD::STORE: {
12266       // Get alias information for Chain.
12267       bool IsOpLoad = isa<LoadSDNode>(Chain.getNode()) &&
12268           !cast<LSBaseSDNode>(Chain.getNode())->isVolatile();
12269
12270       // If chain is alias then stop here.
12271       if (!(IsLoad && IsOpLoad) &&
12272           isAlias(cast<LSBaseSDNode>(N), cast<LSBaseSDNode>(Chain.getNode()))) {
12273         Aliases.push_back(Chain);
12274       } else {
12275         // Look further up the chain.
12276         Chains.push_back(Chain.getOperand(0));
12277         ++Depth;
12278       }
12279       break;
12280     }
12281
12282     case ISD::TokenFactor:
12283       // We have to check each of the operands of the token factor for "small"
12284       // token factors, so we queue them up.  Adding the operands to the queue
12285       // (stack) in reverse order maintains the original order and increases the
12286       // likelihood that getNode will find a matching token factor (CSE.)
12287       if (Chain.getNumOperands() > 16) {
12288         Aliases.push_back(Chain);
12289         break;
12290       }
12291       for (unsigned n = Chain.getNumOperands(); n;)
12292         Chains.push_back(Chain.getOperand(--n));
12293       ++Depth;
12294       break;
12295
12296     default:
12297       // For all other instructions we will just have to take what we can get.
12298       Aliases.push_back(Chain);
12299       break;
12300     }
12301   }
12302
12303   // We need to be careful here to also search for aliases through the
12304   // value operand of a store, etc. Consider the following situation:
12305   //   Token1 = ...
12306   //   L1 = load Token1, %52
12307   //   S1 = store Token1, L1, %51
12308   //   L2 = load Token1, %52+8
12309   //   S2 = store Token1, L2, %51+8
12310   //   Token2 = Token(S1, S2)
12311   //   L3 = load Token2, %53
12312   //   S3 = store Token2, L3, %52
12313   //   L4 = load Token2, %53+8
12314   //   S4 = store Token2, L4, %52+8
12315   // If we search for aliases of S3 (which loads address %52), and we look
12316   // only through the chain, then we'll miss the trivial dependence on L1
12317   // (which also loads from %52). We then might change all loads and
12318   // stores to use Token1 as their chain operand, which could result in
12319   // copying %53 into %52 before copying %52 into %51 (which should
12320   // happen first).
12321   //
12322   // The problem is, however, that searching for such data dependencies
12323   // can become expensive, and the cost is not directly related to the
12324   // chain depth. Instead, we'll rule out such configurations here by
12325   // insisting that we've visited all chain users (except for users
12326   // of the original chain, which is not necessary). When doing this,
12327   // we need to look through nodes we don't care about (otherwise, things
12328   // like register copies will interfere with trivial cases).
12329
12330   SmallVector<const SDNode *, 16> Worklist;
12331   for (const SDNode *N : Visited)
12332     if (N != OriginalChain.getNode())
12333       Worklist.push_back(N);
12334
12335   while (!Worklist.empty()) {
12336     const SDNode *M = Worklist.pop_back_val();
12337
12338     // We have already visited M, and want to make sure we've visited any uses
12339     // of M that we care about. For uses that we've not visisted, and don't
12340     // care about, queue them to the worklist.
12341
12342     for (SDNode::use_iterator UI = M->use_begin(),
12343          UIE = M->use_end(); UI != UIE; ++UI)
12344       if (UI.getUse().getValueType() == MVT::Other &&
12345           Visited.insert(*UI).second) {
12346         if (isa<MemIntrinsicSDNode>(*UI) || isa<MemSDNode>(*UI)) {
12347           // We've not visited this use, and we care about it (it could have an
12348           // ordering dependency with the original node).
12349           Aliases.clear();
12350           Aliases.push_back(OriginalChain);
12351           return;
12352         }
12353
12354         // We've not visited this use, but we don't care about it. Mark it as
12355         // visited and enqueue it to the worklist.
12356         Worklist.push_back(*UI);
12357       }
12358   }
12359 }
12360
12361 /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
12362 /// (aliasing node.)
12363 SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
12364   SmallVector<SDValue, 8> Aliases;  // Ops for replacing token factor.
12365
12366   // Accumulate all the aliases to this node.
12367   GatherAllAliases(N, OldChain, Aliases);
12368
12369   // If no operands then chain to entry token.
12370   if (Aliases.size() == 0)
12371     return DAG.getEntryNode();
12372
12373   // If a single operand then chain to it.  We don't need to revisit it.
12374   if (Aliases.size() == 1)
12375     return Aliases[0];
12376
12377   // Construct a custom tailored token factor.
12378   return DAG.getNode(ISD::TokenFactor, SDLoc(N), MVT::Other, Aliases);
12379 }
12380
12381 /// This is the entry point for the file.
12382 void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
12383                            CodeGenOpt::Level OptLevel) {
12384   /// This is the main entry point to this class.
12385   DAGCombiner(*this, AA, OptLevel).Run(Level);
12386 }